<?php
// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, 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;
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Centralized admin auth
requireAdmin(true);

try {
    $hasAcc = false; $hasPic = false; $hasKyc = false;
    try { $c1 = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_number'"); $hasAcc = $c1 && $c1->rowCount() > 0; } catch (Exception $e) {}
    try { $c2 = $pdo->query("SHOW COLUMNS FROM users LIKE 'profile_picture'"); $hasPic = $c2 && $c2->rowCount() > 0; } catch (Exception $e) {}

    // Detect kycStatus column (case-insensitive)
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM users");
        if ($cols) {
            while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
                if (strtolower($c['Field'] ?? '') === 'kycstatus') { $hasKyc = true; break; }
            }
        }
    } catch (Exception $e) {}

    $extra = [];
    if ($hasAcc) { $extra[] = 'account_number'; }
    if ($hasPic) { $extra[] = 'profile_picture'; }
    // Check for restriction flags
    $hasSusp = false; $hasTxSusp = false; $hasDormant = false;
    try { $hasSusp = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_suspended'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasTxSusp = $pdo->query("SHOW COLUMNS FROM users LIKE 'transfers_suspended'")->rowCount() > 0; } catch (Exception $e) {}
    try { $hasDormant = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_dormant'")->rowCount() > 0; } catch (Exception $e) {}
    if ($hasSusp) $extra[] = 'account_suspended';
    if ($hasTxSusp) $extra[] = 'transfers_suspended';
    if ($hasDormant) $extra[] = 'account_dormant';
    $sel = 'id, username, name, email, status, ' . ($hasKyc ? 'kycStatus' : 'NULL AS kycStatus') . ', balance' . (empty($extra) ? '' : ', ' . implode(', ', $extra));
    $stmt = $pdo->prepare("SELECT $sel FROM users");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(["success" => true, "users" => $users]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => $e->getMessage()]);
}
