<?php
/**
 * distribuidores-vouchers.php — Vouchers de un distribuidor en los últimos 6 meses
 * GET /admin/api/distribuidores-vouchers.php?id=ID_INVER
 */
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 inválida o expirada']);
    exit;
}

// ── Parámetros ───────────────────────────────────────────────────────────────
$id = (int)($_GET['id'] ?? 0);
if (!$id) {
    echo json_encode(['ok' => false, 'error' => 'ID requerido']);
    exit;
}

// ── Query ────────────────────────────────────────────────────────────────────
$stmt = $db->prepare("
    SELECT
        idv,
        total,
        restante,
        status,
        idcd,
        observaciones,
        fecha_cre
    FROM voucher
    WHERE id_inv = ?
      AND fecha_cre >= NOW() - INTERVAL 6 MONTH
    ORDER BY fecha_cre DESC
");
$stmt->execute([$id]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Mapear status a etiqueta legible
// 0 = Activo (con saldo), 1 = Usado (sin saldo)
foreach ($rows as &$row) {
    $row['status_label'] = ((int)$row['status'] === 0) ? 'Activo' : 'Usado';
}
unset($row);

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