<?php
// get_user_withdrawal_pins.php: Return the current user's withdrawal PINs (schema-agnostic)
header('Content-Type: application/json');
// Caching and CORS
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 {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
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;
}

// Guard and session
define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireLogin(true);

require_once __DIR__ . '/db.php';

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

    // Introspect schema for all relevant columns
    $has_status = false; $has_used = false; $has_created_at = false; $has_updated_at = false;
    $has_name = false; $has_expiry_date = false; $has_checkpoint_percentage = false;
    try {
        $cols = $pdo->query("SHOW COLUMNS FROM withdrawal_pins");
        while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
            $f = $c['Field'] ?? '';
            if ($f === 'status') $has_status = true;
            if ($f === 'used') $has_used = true;
            if ($f === 'created_at') $has_created_at = true;
            if ($f === 'updated_at') $has_updated_at = true;
            if ($f === 'name') $has_name = true;
            if ($f === 'expiry_date') $has_expiry_date = true;
            if ($f === 'checkpoint_percentage') $has_checkpoint_percentage = true;
        }
    } catch (Exception $e) { /* ignore */ }

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

    $select = "SELECT id, pin, $statusExpr AS status";
    $select .= $has_name ? ", name" : ", NULL AS name";
    $select .= $has_expiry_date ? ", expiry_date" : ", NULL AS expiry_date";
    $select .= $has_checkpoint_percentage ? ", checkpoint_percentage" : ", 92 AS checkpoint_percentage";
    $select .= $has_created_at ? ", created_at" : ", NULL AS created_at";
    $select .= $has_updated_at ? ", updated_at" : ", NULL AS updated_at";
    
    // Only return active, non-expired PINs to users
    $where = "WHERE user_id = ?";
    if ($has_status) {
        $where .= " AND status = 'active'";
    } elseif ($has_used) {
        $where .= " AND used = 0";
    }
    if ($has_expiry_date) {
        $where .= " AND (expiry_date IS NULL OR expiry_date > NOW())";
    }
    
    $sql = $select . " FROM withdrawal_pins " . $where . " ORDER BY " . ($has_created_at ? 'created_at ASC' : 'id ASC');

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_id]);
    $pins = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['success' => true, 'pins' => $pins]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to fetch withdrawal pins: ' . $e->getMessage()]);
}
