<?php
/**
 * compra-voucher-validar.php
 * GET ?codigo=XXX → valida que el voucher exista, status=0 y restante>1
 */
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' => 'Sesión inválida o expirada']);
    exit;
}

$codigo = trim($_GET['codigo'] ?? '');
if ($codigo === '') {
    echo json_encode(['ok' => false, 'error' => 'Código de voucher requerido']);
    exit;
}

$stmt = $db->prepare("
    SELECT v.idv, v.total, v.restante, v.status, v.id_inv,
           CONCAT(i.nombre,' ',i.appat) AS nombre_dist
    FROM voucher v
    LEFT JOIN inversionista i ON v.id_inv = i.id_inver
    WHERE v.idv = ?
");
$stmt->execute([$codigo]);
$voucher = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$voucher) {
    echo json_encode(['ok' => false, 'error' => 'Voucher no encontrado']);
    exit;
}
if ((int)$voucher['status'] !== 0) {
    echo json_encode(['ok' => false, 'error' => 'Voucher ya utilizado o inactivo']);
    exit;
}
if ((float)$voucher['restante'] <= 1) {
    echo json_encode(['ok' => false, 'error' => 'Voucher sin saldo disponible']);
    exit;
}

echo json_encode([
    'ok'      => true,
    'voucher' => [
        'idv'         => $voucher['idv'],
        'total'       => (float)$voucher['total'],
        'restante'    => (float)$voucher['restante'],
        'nombre_dist' => $voucher['nombre_dist'],
    ],
], JSON_UNESCAPED_UNICODE);
