<?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 ────────────────────────────────────────────────────────────
$idv = intval($_GET['idv'] ?? 0);
if (!$idv) {
    echo json_encode(['ok' => false, 'error' => 'Parámetro idv requerido']);
    exit;
}

// ── Datos del voucher + propietario ───────────────────────────────────────
$stmtV = $db->prepare("
    SELECT
        v.idv,
        v.total,
        v.restante,
        v.status,
        v.referencia,
        v.observaciones,
        v.descripcion,
        v.fecha_cre,
        v.creado_por,
        i.id_inver,
        i.nombre,
        i.appat,
        i.apmat,
        i.referencia AS ref_dist,
        i.rfc
    FROM voucher v
    JOIN inversionista i ON i.id_inver = v.id_inv
    WHERE v.idv = ?
");
$stmtV->execute([$idv]);
$voucher = $stmtV->fetch(PDO::FETCH_ASSOC);

if (!$voucher) {
    echo json_encode(['ok' => false, 'error' => 'Voucher no encontrado']);
    exit;
}

// ── Notas en las que se usó el voucher ───────────────────────────────────
$stmtN = $db->prepare("
    SELECT
        t.idtransacciones,
        t.fechat,
        i.nombre,
        i.appat,
        i.apmat,
        dt.monto,
        t.tipostr_idtipostr
    FROM depositos_transaccion dt
    JOIN transacciones t ON t.idtransacciones = dt.idtransacciones
    JOIN inversionista i ON t.inversionista_id_inver = i.id_inver
    WHERE dt.id_voucher = ?
    ORDER BY t.fechat DESC
");
$stmtN->execute([$idv]);
$notas = $stmtN->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'ok'     => true,
    'voucher' => $voucher,
    'notas'   => $notas
]);
