<?php
require_once dirname(__FILE__) . '/../config.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'GET') { jsonErr(405, 'Metodo no permitido.'); }

$payload  = auth();
$id_inver = (int)($payload['idinv'] ?? 0);
if (!$id_inver) { jsonErr(401, 'Token inválido.'); }

$db = getDB();

try {
    $stmt = $db->prepare("
        SELECT idv, total, restante, status, fecha_cre, descripcion, referencia
        FROM voucher
        WHERE id_inv = ?
        ORDER BY fecha_cre DESC
    ");
    $stmt->execute([$id_inver]);
    $vouchers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($vouchers as &$v) {
        $v['idv']      = (int)$v['idv'];
        $v['total']    = (float)$v['total'];
        $v['restante'] = (float)$v['restante'];
        $v['status']   = (int)$v['status'];
    }
    unset($v);

    jsonOk(['vouchers' => $vouchers]);

} catch (Throwable $e) {
    jsonErr(500, 'Error al obtener vouchers: ' . $e->getMessage());
}
