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

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$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-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

requireLogin(true);

try {
  $userId = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : 0;
  if ($userId <= 0) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
  }

  // Tolerant select for users table
  $baseCols = ['id','name','username','email'];
  $optCols = ['account_number','profile_picture','status'];
  $selectCols = [];
  // Always include base columns
  foreach ($baseCols as $c) { $selectCols[] = 'u.' . $c; }
  // Add optional columns if they exist
  try {
    $colsStmt = $pdo->query("SHOW COLUMNS FROM users");
    $existing = [];
    while ($r = $colsStmt->fetch(PDO::FETCH_ASSOC)) {
      $existing[] = strtolower($r['Field']);
    }
    foreach ($optCols as $c) {
      if (in_array(strtolower($c), $existing, true)) { $selectCols[] = 'u.' . $c; }
    }
  } catch (Throwable $e) {
    // ignore, fall back to base columns only
  }
  $sqlUser = 'SELECT ' . implode(',', $selectCols) . ' FROM users u WHERE u.id = :uid LIMIT 1';
  $st = $pdo->prepare($sqlUser);
  $st->execute([':uid' => $userId]);
  $user = $st->fetch(PDO::FETCH_ASSOC);

  // Fetch extended profile if table exists
  $profile = null;
  try {
    $chk = $pdo->query("SHOW TABLES LIKE 'user_profiles'");
    if ($chk && $chk->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 = :uid LIMIT 1");
      $ps->execute([':uid' => $userId]);
      $profile = $ps->fetch(PDO::FETCH_ASSOC) ?: null;
    }
  } catch (Throwable $e) { /* ignore */ }

  // Fetch next-of-kin if table exists (tolerant of schema differences)
  $nok = null;
  try {
    $chk2 = $pdo->query("SHOW TABLES LIKE 'user_profiles_next_of_kin'");
    if ($chk2 && $chk2->rowCount() > 0) {
      $existing = [];
      try {
        $colsStmt = $pdo->query("SHOW COLUMNS FROM user_profiles_next_of_kin");
        while ($r = $colsStmt->fetch(PDO::FETCH_ASSOC)) { $existing[] = strtolower($r['Field']); }
      } catch (Throwable $ie) {}
      $candidates = ['name','phone','email','address','relationship'];
      $sel = [];
      foreach ($candidates as $c) { if (in_array($c, $existing, true)) { $sel[] = $c; } }
      if (empty($sel)) { $sel = ['name','phone','email','address']; }
      $selList = implode(',', $sel);
      $ks = $pdo->prepare("SELECT $selList FROM user_profiles_next_of_kin WHERE user_id = :uid ORDER BY id DESC LIMIT 1");
      $ks->execute([':uid' => $userId]);
      $nok = $ks->fetch(PDO::FETCH_ASSOC) ?: null;
    }
  } catch (Throwable $e) { /* ignore */ }

  echo json_encode([
    'success' => true,
    'data' => [
      'user' => $user,
      'profile' => $profile,
      'nextOfKin' => $nok
    ]
  ]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
