<?php
session_start();

require_once __DIR__ . '/../config/database.php';

function e($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

try {
    if (!isset($_SESSION['user']['codempleado'])) {
        http_response_code(401);
        echo 'No autorizado';
        exit;
    }

    $ventaId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    if ($ventaId <= 0) {
        http_response_code(400);
        echo 'ID inválido';
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $stmtEmpresa = $conn->prepare("SELECT codempresa FROM templeado WHERE codempleado = ?");
    $stmtEmpresa->execute([$_SESSION['user']['codempleado']]);
    $empresa = $stmtEmpresa->fetch(PDO::FETCH_ASSOC);
    if (!$empresa || !$empresa['codempresa']) {
        http_response_code(403);
        echo 'Empresa no encontrada';
        exit;
    }

    $stmtVenta = $conn->prepare("SELECT id, nombres_ap_raz_soc, tipo_documento, nro_documento FROM timportventas WHERE id = ? AND codempresa = ?");
    $stmtVenta->execute([$ventaId, $empresa['codempresa']]);
    $venta = $stmtVenta->fetch(PDO::FETCH_ASSOC);
    if (!$venta) {
        http_response_code(404);
        echo 'Venta no encontrada';
        exit;
    }

    $stmt = $conn->prepare("SELECT nropago, fecha_entrega, fecha_iniciocobranza, fechapago, estado, monto, pagadofecha FROM tcronogramaventas WHERE id = ? ORDER BY COALESCE(fechapago, fecha_entrega) ASC, codcronogramaventas ASC");
    $stmt->execute([$ventaId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $filename = 'cronograma_ventas_' . $ventaId . '_' . date('Ymd_His') . '.xls';
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename=' . $filename);
    header('Pragma: no-cache');
    header('Expires: 0');
    echo "\xEF\xBB\xBF";
    echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>";
    echo '<h3>Cronograma de Pagos - ' . e($venta['nombres_ap_raz_soc']) . ' (' . e($venta['tipo_documento']) . ' ' . e($venta['nro_documento']) . ')</h3>';
    echo "<table border=\"1\" cellspacing=\"0\" cellpadding=\"5\">";
    echo '<tr style="background:#e8f5e9;font-weight:bold">'
        . '<td>#</td>'
        . '<td>N° Pago</td>'
        . '<td>Fecha Entrega</td>'
        . '<td>Inicio Cobranza</td>'
        . '<td>Fecha Pago</td>'
        . '<td>Estado</td>'
        . '<td>Monto</td>'
        . '<td>Pagado Fecha</td>'
        . '</tr>';
    $total = 0.0;
    foreach ($rows as $idx => $r) {
        if ($r['monto'] !== null) { $total += (float)$r['monto']; }
        echo '<tr>'
            . '<td>' . ($idx + 1) . '</td>'
            . '<td>' . e($r['nropago']) . '</td>'
            . '<td>' . ($r['fecha_entrega'] ? date('d/m/Y', strtotime($r['fecha_entrega'])) : '') . '</td>'
            . '<td>' . ($r['fecha_iniciocobranza'] ? date('d/m/Y', strtotime($r['fecha_iniciocobranza'])) : '') . '</td>'
            . '<td>' . ($r['fechapago'] ? date('d/m/Y', strtotime($r['fechapago'])) : '') . '</td>'
            . '<td>' . e($r['estado']) . '</td>'
            . '<td>' . ($r['monto'] !== null ? number_format((float)$r['monto'], 2) : '') . '</td>'
            . '<td>' . ($r['pagadofecha'] ? date('d/m/Y', strtotime($r['pagadofecha'])) : '') . '</td>'
            . '</tr>';
    }
    echo '<tr style="font-weight:bold"><td colspan="6" align="right">Total</td><td>' . number_format($total, 2) . '</td><td></td></tr>';
    echo '</table>';
    echo '</body></html>';
    exit;
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Error al exportar: ' . $e->getMessage();
}


