<?php
if (!defined('TONSUI_LOADED')) { define('TONSUI_LOADED', true); }
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db.php';

$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) { header('Access-Control-Allow-Origin: ' . $origin); }
else if (!empty($_SERVER['HTTP_HOST'])) { $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https'; header('Access-Control-Allow-Origin: ' . $scheme . '://' . $_SERVER['HTTP_HOST']); }
header('Access-Control-Allow-Credentials: true');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

requireAdmin(true);

$hasProfiles = false; $hasNok = false; $hasCreatedAt = false;
try {
  $t1 = $pdo->query("SHOW TABLES LIKE 'user_profiles'");
  if ($t1 && $t1->rowCount() > 0) { $hasProfiles = true; }
  $t2 = $pdo->query("SHOW TABLES LIKE 'user_profiles_next_of_kin'");
  if ($t2 && $t2->rowCount() > 0) { $hasNok = true; }
  $uc = $pdo->query("SHOW COLUMNS FROM users");
  while ($c = $uc->fetch(PDO::FETCH_ASSOC)) { if (strtolower($c['Field'] ?? '') === 'created_at') { $hasCreatedAt = true; break; } }
} catch (Exception $e) {}

$cols = [
  'user_id','name','username','email'
];
if ($hasCreatedAt) { $cols[] = 'created_at'; }
$profileCols = ['first_name','last_name','address1','address2','city','state','zip','phone','dob','country','gender','account_type','account_photo_path'];
$nokCols = ['nok_name','nok_phone','nok_email','nok_address'];
if ($hasProfiles) { $cols = array_merge($cols, $profileCols); }
if ($hasNok) { $cols = array_merge($cols, $nokCols); }

$filename = 'registrations_export_' . date('Ymd_His') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $filename);

$out = fopen('php://output', 'w');
$write = function($row) use ($out) { fputcsv($out, $row); };
$write($cols);

$sql = 'SELECT u.id AS user_id, u.name, u.username, u.email' . ($hasCreatedAt ? ', u.created_at' : '') .
       ($hasProfiles ? ', up.first_name, up.last_name, up.address1, up.address2, up.city, up.state, up.zip, up.phone, up.dob, up.country, up.gender, up.account_type, up.account_photo_path' : '') .
       ($hasNok ? ', nk.name AS nok_name, nk.phone AS nok_phone, nk.email AS nok_email, nk.address AS nok_address' : '') .
       ' FROM users u ' .
       ($hasProfiles ? ' LEFT JOIN user_profiles up ON up.user_id = u.id' : '') .
       ($hasNok ? ' LEFT JOIN user_profiles_next_of_kin nk ON nk.user_id = u.id' : '');

$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $row = [];
  foreach ($cols as $c) { $row[] = isset($r[$c]) ? (string)$r[$c] : ''; }
  $write($row);
}

fclose($out);
exit;
