<?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';

header('Content-Type: application/json');
$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; }

try {
  requireAdmin(true);
  $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
  if ($userId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'user_id required']);
    exit;
  }

  // Base user (tolerant select similar to get_profile.php)
  $fields = ['id','username','email','name','status','balance','total_earned','is_admin','created_at','updated_at'];
  $hasKycStatus = false; $hasAccountNumber = false;
  try {
    $ucols = $pdo->query("SHOW COLUMNS FROM users");
    while ($c = $ucols->fetch(PDO::FETCH_ASSOC)) {
      $f = strtolower($c['Field'] ?? '');
      if ($f === 'kycstatus') $hasKycStatus = true;
      if ($f === 'account_number') $hasAccountNumber = true;
    }
  } catch (Exception $e) { /* ignore */ }
  if ($hasKycStatus) array_unshift($fields, 'kycStatus');
  if ($hasAccountNumber) array_unshift($fields, 'account_number');

  $stmt = $pdo->prepare('SELECT ' . implode(',', $fields) . ' FROM users WHERE id = ?');
  $stmt->execute([$userId]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$user) { http_response_code(404); echo json_encode(['success'=>false,'message'=>'User not found']); exit; }

  // Extended profile
  $profile = null; $nok = null;
  try {
    // tables might not exist yet
    $p = $pdo->query("SHOW TABLES LIKE 'user_profiles'");
    if ($p && $p->rowCount() > 0) {
      $ps = $pdo->prepare('SELECT first_name,last_name,address1,address2,city,state,zip,phone,dob,country,gender,account_currency,account_type,account_photo_path FROM user_profiles WHERE user_id = ? ORDER BY id DESC LIMIT 1');
      $ps->execute([$userId]);
      $profile = $ps->fetch(PDO::FETCH_ASSOC) ?: null;
    }
    $k = $pdo->query("SHOW TABLES LIKE 'user_profiles_next_of_kin'");
    if ($k && $k->rowCount() > 0) {
      $ks = $pdo->prepare('SELECT name,phone,email,address FROM user_profiles_next_of_kin WHERE user_id = ? ORDER BY id DESC LIMIT 1');
      $ks->execute([$userId]);
      $nok = $ks->fetch(PDO::FETCH_ASSOC) ?: null;
    }
  } catch (Exception $e) { /* ignore */ }

  echo json_encode(['success' => true, 'message' => 'ok', 'data' => [ 'user' => $user, 'profile' => $profile, 'nextOfKin' => $nok ]]);
} catch (Exception $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => 'Server error']);
}
