<?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;
}

$idv = $_GET['idv'] ?? null;
if (!$idv) {
    http_response_code(400);
    echo json_encode(['error' => 'Falta el parámetro idv.']);
    exit;
}

try {
    // Verificar que el voucher pertenece al distribuidor
    $stmtOwner = $pdo->prepare("SELECT id_inv FROM voucher WHERE idv = ?");
    $stmtOwner->execute([$idv]);
    $owner = $stmtOwner->fetchColumn();
    if ((int)$owner !== (int)$id_inver) {
        http_response_code(403);
        echo json_encode(['error' => 'No tienes permiso para ver este voucher.']);
        exit;
    }

    // Datos del voucher
    $stmtV = $pdo->prepare("SELECT idv, total, restante, status, fecha_cre FROM voucher WHERE idv = ?");
    $stmtV->execute([$idv]);
    $voucher = $stmtV->fetch(PDO::FETCH_ASSOC);
    if (!$voucher) {
        http_response_code(404);
        echo json_encode(['error' => 'Voucher no encontrado.']);
        exit;
    }

    // Historial de uso (desde depositos_transaccion)
    $stmtUsos = $pdo->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
    ");
    $stmtUsos->execute([$idv]);
    $usos = $stmtUsos->fetchAll(PDO::FETCH_ASSOC);

    // Convertir tipos
    $voucher['idv']      = (int)$voucher['idv'];
    $voucher['total']    = (float)$voucher['total'];
    $voucher['restante'] = (float)$voucher['restante'];
    $voucher['status']   = (int)$voucher['status'];

    foreach ($usos as &$u) {
        $u['idtransacciones']     = (int)$u['idtransacciones'];
        $u['monto']               = (float)$u['monto'];
        $u['tipostr_idtipostr']   = (int)$u['tipostr_idtipostr'];
        $u['nombre_completo']     = trim($u['nombre'] . ' ' . $u['appat'] . ' ' . $u['apmat']);
        unset($u['nombre'], $u['appat'], $u['apmat']);
    }

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

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