<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
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 expirada o inválida']);
    exit;
}

// ── Parámetros ────────────────────────────────────────────────────────────
$desde = trim($_GET['desde'] ?? '');
$hasta = trim($_GET['hasta'] ?? '');

if (!$desde || !$hasta) {
    echo json_encode(['ok' => false, 'error' => 'Parámetros desde y hasta requeridos']);
    exit;
}

$stmt = $db->prepare("
    SELECT
        v.idv,
        i.referencia,
        i.rfc,
        i.nombre,
        i.appat,
        i.apmat,
        v.total,
        v.restante,
        v.status,
        v.observaciones,
        v.fecha_cre
    FROM voucher v
    JOIN inversionista i ON i.id_inver = v.id_inv
    WHERE v.fecha_cre BETWEEN ? AND ?
    ORDER BY v.fecha_cre DESC, v.idv DESC
");
$stmt->execute([$desde, $hasta . ' 23:59:59']);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode(['ok' => true, 'vouchers' => $rows, 'total' => count($rows)]);
