<?php
require_once dirname(__FILE__) . '/../config.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(200); exit; }

try {
    $payload  = auth();
    $id_inver = (int)($payload['idinv'] ?? 0);
    if (!$id_inver) { jsonErr(401, 'Token inválido.'); }
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Token inválido.']);
    exit;
}

try {
    // Últimos 6 meses de vouchers del distribuidor
    $stmt = $pdo->prepare("
        SELECT idv, total, restante, status, fecha_cre
        FROM voucher
        WHERE id_inv = ?
          AND fecha_cre >= NOW() - INTERVAL 6 MONTH
        ORDER BY fecha_cre DESC
    ");
    $stmt->execute([$id_inver]);
    $vouchers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Convertir tipos
    foreach ($vouchers as &$v) {
        $v['idv']      = (int)$v['idv'];
        $v['total']    = (float)$v['total'];
        $v['restante'] = (float)$v['restante'];
        $v['status']   = (int)$v['status'];
        // fecha_cre ya viene como string "YYYY-MM-DD HH:MM:SS"
    }

    echo json_encode(['success' => true, 'vouchers' => $vouchers]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Error al obtener vouchers.', 'detail' => $e->getMessage()]);
}
