<?php
/**
 * compra-bancos.php
 * GET → devuelve bancos activos (activa=1, tipo=1) para el selector de depósito
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require_once __DIR__ . '/../../config.php';
$db = getDB();

// ── Validar token ─────────────────────────────────────────────────────────────
$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!preg_match('/Bearer\s+(.+)/i', $authHeader, $m)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Token requerido']);
    exit;
}
$token = trim($m[1]);
$stmtTok = $db->prepare("SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expira > NOW()");
$stmtTok->execute([$token]);
if (!$stmtTok->fetch()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesion invalida o expirada']);
    exit;
}

try {
    $bancos = $db->query("
        SELECT idbanco, cuenta, numero
        FROM bancos
        WHERE activa = 1 AND tipo = 1
        ORDER BY cuenta
    ")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($bancos as &$b) {
        $b['idbanco'] = (int)$b['idbanco'];
    }
    unset($b);

    echo json_encode(['ok' => true, 'bancos' => $bancos], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
