<?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, Cache-Control');
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 {
    // Check which balance columns exist
    $columns = ['id', 'username', 'email'];
    
    // Always include main balance column
    $columns[] = 'balance';
    
    // Include account currency if present
    try {
        $accCur = $pdo->query("SHOW COLUMNS FROM users LIKE 'account_currency'");
        if ($accCur && $accCur->rowCount() > 0) { $columns[] = 'account_currency'; }
    } catch (Exception $e) {}

    // Check for multi-wallet columns
    try {
        $checkStmt = $pdo->query("SHOW COLUMNS FROM users WHERE Field IN ('ton_balance', 'sui_balance', 'referral_balance')");
        while ($col = $checkStmt->fetch(PDO::FETCH_ASSOC)) {
            $columns[] = $col['Field'];
        }
    } catch (Exception $e) {}
    
    $columnsList = implode(', ', $columns);
    $sql = "SELECT {$columnsList} FROM users ORDER BY balance DESC";
    $stmt = $pdo->query($sql);
    $balances = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    
    echo json_encode([
        'success' => true,
        'balances' => $balances
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch balances: ' . $e->getMessage()
    ]);
}
?>
