<?php
declare(strict_types=1);
// Script de diagnóstico — SIN AUTH — BORRAR DESPUÉS
require_once dirname(__FILE__) . '/../config.php';
$idinv = (int)($_GET['idinv'] ?? 1459);
$db    = getDB();

$fechaHace6Meses = date('Y-m-d', strtotime('-6 months'));

// Ejecutar la misma query que list.php pero mostrar errores detallados
try {
    $stmt = $db->prepare(
        'SELECT
            t.idtransacciones        AS id_transaccion,
            t.nota                   AS numero_nota,
            t.fechat                 AS fecha,
            t.horat                  AS hora,
            t.consec                 AS consecutivo,
            t.tipostr_idtipostr      AS tipo_id,
            COALESCE(p.efectivo,  0) AS pago_efectivo,
            COALESCE(p.deposito,  0) AS pago_deposito,
            COALESCE(p.tarjeta,   0) AS pago_tarjeta,
            COALESCE(p.voucher,   0) AS pago_voucher,
            COALESCE(p.porpagar,  0) AS por_pagar,
            COALESCE(p.efectivo,0) + COALESCE(p.deposito,0) + COALESCE(p.tarjeta,0)
                + COALESCE(p.voucher,0) + COALESCE(p.porpagar,0) AS total_venta,
            COALESCE(ta.costoEnvio, 0) AS costo_envio,
            t.carrier                AS carrier,
            t.tracking_number        AS tracking
         FROM transacciones t
         LEFT JOIN pagovta p ON p.idtransacciones = t.idtransacciones
         LEFT JOIN transaccion_adicionales ta ON ta.idtransacciones = t.idtransacciones
         WHERE t.inversionista_id_inver = ?
           AND t.tipostr_idtipostr IN (7, 8, 10, 11, 12)
           AND t.fechat >= ?
         ORDER BY t.fechat DESC, t.horat DESC
         LIMIT 100'
    );
    $stmt->execute([$idinv, $fechaHace6Meses]);
    $compras = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $tiposLabel = [
        7  => 'Venta Pendiente',
        8  => 'Por Asignar Pendiente',
        10 => 'Venta',
        11 => 'Por Asignar',
        12 => 'Asignación',
    ];

    $lista = [];
    foreach ($compras as $c) {
        $tipo = (int)$c['tipo_id'];
        $lista[] = [
            'id_transaccion' => (int)$c['id_transaccion'],
            'numero_nota'    => (int)$c['numero_nota'],
            'consecutivo'    => (int)$c['consecutivo'],
            'fecha'          => $c['fecha'],
            'hora'           => $c['hora'],
            'tipo_id'        => $tipo,
            'tipo_label'     => $tiposLabel[$tipo] ?? 'Desconocido',
            'es_pendiente'   => ($tipo === 7 || $tipo === 8),
            'total_venta'    => (float)$c['total_venta'],
            'pago_efectivo'  => (float)$c['pago_efectivo'],
            'pago_deposito'  => (float)$c['pago_deposito'],
            'pago_tarjeta'   => (float)$c['pago_tarjeta'],
            'pago_voucher'   => (float)$c['pago_voucher'],
            'por_pagar'      => (float)$c['por_pagar'],
            'costo_envio'    => (float)$c['costo_envio'],
            'carrier'        => $c['carrier'] ?? null,
            'tracking'       => $c['tracking'] ?? null,
        ];
    }

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success' => true,
        'data'    => ['compras' => $lista, 'total' => count($lista)],
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'file'    => $e->getFile(),
        'line'    => $e->getLine(),
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
