<?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, 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;
}

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

// Require admin authentication
requireAdmin(true);

require_once 'db.php';

try {
    // Detect optional columns
    $hasCreated = false; $hasBalance = false; $hasWallet = false;
    try {
        $c1 = $pdo->query("SHOW COLUMNS FROM users LIKE 'created_at'");
        $hasCreated = $c1 && $c1->rowCount() > 0;
    } catch (Exception $e) {}
    try {
        $c2 = $pdo->query("SHOW COLUMNS FROM users LIKE 'balance'");
        $hasBalance = $c2 && $c2->rowCount() > 0;
    } catch (Exception $e) {}
    try {
        $c3 = $pdo->query("SHOW COLUMNS FROM users LIKE 'wallet_balance'");
        $hasWallet = $c3 && $c3->rowCount() > 0;
    } catch (Exception $e) {}

    $createdSel = $hasCreated ? 'created_at' : 'NULL AS created_at';
    $balanceSel = $hasBalance ? 'balance' : ($hasWallet ? 'wallet_balance AS balance' : '0 AS balance');
    $order = $hasCreated ? 'created_at DESC' : 'id DESC';

    $sql = "SELECT id, username, email, {$createdSel}, {$balanceSel} FROM users ORDER BY {$order}";
    $stmt = $pdo->query($sql);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    
    echo json_encode([
        'success' => true,
        'users' => $users
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch users: ' . $e->getMessage()
    ]);
}
?>
