<?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');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

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 {
    // Introspect schema to build a compatible SELECT across environments
    $has_status = false; $has_used = false; $has_name = false; $has_expiry = false; $has_created = false; $has_used_at = false; $has_checkpoint = false;
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM withdrawal_pins");
        while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
            $f = strtolower($c['Field'] ?? '');
            if ($f === 'status') $has_status = true;
            if ($f === 'used') $has_used = true;
            if ($f === 'name') $has_name = true;
            if ($f === 'expiry_date') $has_expiry = true;
            if ($f === 'created_at') $has_created = true;
            if ($f === 'used_at') $has_used_at = true;
            if ($f === 'checkpoint_percentage') $has_checkpoint = true;
        }
    } catch (Exception $e) { /* ignore */ }

    $statusExpr = $has_status ? 'wp.status' : ($has_used ? "CASE WHEN wp.used=1 THEN 'used' ELSE 'active' END" : "'active'");

    $select = "SELECT wp.id, u.username, wp.pin";
    $select .= $has_name ? ", wp.name" : ", NULL AS name";
    $select .= ", $statusExpr AS status";
    $select .= $has_expiry ? ", wp.expiry_date" : ", NULL AS expiry_date";
    $select .= $has_created ? ", wp.created_at AS created" : ", NULL AS created";
    $select .= $has_used_at ? ", wp.used_at" : ", NULL AS used_at";
    $select .= $has_checkpoint ? ", wp.checkpoint_percentage" : ", NULL AS checkpoint_percentage";

    $orderBy = $has_created ? 'wp.created_at DESC' : 'wp.id DESC';

    $sql = $select . " FROM withdrawal_pins wp LEFT JOIN users u ON wp.user_id = u.id ORDER BY " . $orderBy;
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $pins = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(["success" => true, "pins" => $pins]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => $e->getMessage()]);
}
