<?php
require_once 'calcu.php';

if (!$_POST) {
    die('No hay datos para generar el reporte');
}

$calculadora = new CalculadoraTributariaBCB();
$fechaVencimiento = $_POST['fecha_vencimiento'];
$fechaPago = $_POST['fecha_pago'];
$tributoOmitido = floatval($_POST['tributo_omitido']);
$tipoContribuyente = $_POST['tipo_contribuyente'];
$referencia = trim($_POST['referencia'] ?? '');

$resultado = $calculadora->calcularDeudaTributaria($fechaVencimiento, $fechaPago, $tributoOmitido, $tipoContribuyente);
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Reporte de Cálculo de Deuda Tributaria</title>
    <style>
        @media print {
            * { margin: 0; padding: 0; }
            body { font-family: Arial, sans-serif; font-size: 11px; }
            @page { margin: 15mm; }
        }
        
        body { font-family: Arial, sans-serif; font-size: 11px; margin: 15px; }
        .header { text-align: center; margin-bottom: 20px; }
        .logo { max-height: 45px; margin-bottom: 10px; }
        h1 { color: #2c5aa0; margin: 10px 0; font-size: 20px; line-height: 1.2; }
        h2 { color: #2c5aa0; margin: 15px 0 10px 0; font-size: 14px; }
        table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        th, td { padding: 6px 8px; border: 1px solid #ddd; text-align: left; font-size: 10px; }
        th { background: #2c5aa0; color: white; font-weight: bold; }
        .total-row { background: #dc3545; color: white; font-weight: bold; }
        .info-section { background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 3px; }
        .footer { margin-top: 15px; font-size: 9px; color: #666; border-top: 1px solid #ddd; padding-top: 10px; }
        .compact-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 10px 0; }
        .tramos-detail { background: #fff8dc; padding: 8px; border-radius: 3px; margin: 5px 0; font-size: 9px; }
        .section-header { display: flex; justify-content: space-between; align-items: center; }
        .referencia { font-size: 10px; color: #666; font-style: italic; }
    </style>
    <script>
        window.onload = function() { window.print(); }
    </script>
</head>
<body>
    <div class="header">
        <img src="https://s1.boliviaimpuestos.com/img/2019/10/14111124/cropped-cropped-logo-bib-extended-350-x-60.png" 
             alt="Bolivia Impuestos" class="logo">
        <h1>REPORTE DE CÁLCULO DE DEUDA TRIBUTARIA</h1>
        <p><strong>BoliviaImpuestos.com</strong> | <?php echo date('d/m/Y H:i:s'); ?></p>
    </div>
    
    <div class="info-section">
        <div class="section-header">
            <h2 style="margin: 0;">DATOS GENERALES</h2>
            <?php if (!empty($referencia)): ?>
                <span class="referencia">Ref: <?php echo htmlspecialchars($referencia); ?></span>
            <?php endif; ?>
        </div>
        
        <div class="compact-grid">
            <table style="margin: 0;">
                <tr><td><strong>Fecha Vencimiento:</strong></td><td><?php echo date('d/m/Y', strtotime($resultado['fechaVencimiento'])); ?></td></tr>
                <tr><td><strong>Fecha de Pago:</strong></td><td><?php echo date('d/m/Y', strtotime($resultado['fechaPago'])); ?></td></tr>
                <tr><td><strong>Días de Mora:</strong></td><td><?php echo number_format($resultado['diasMora'], 0); ?> días</td></tr>
            </table>
            <table style="margin: 0;">
                <tr><td><strong>UFV Vencimiento:</strong></td><td><?php echo number_format($resultado['ufvVencimiento'], 5); ?></td></tr>
                <tr><td><strong>UFV Pago:</strong></td><td><?php echo number_format($resultado['ufvPago'], 5); ?></td></tr>
                <tr><td><strong>Tributo Original:</strong></td><td>Bs <?php echo number_format($resultado['tributoOmitido'], 2); ?></td></tr>
            </table>
        </div>
    </div>
    
    <h2>COMPOSICIÓN DEL FORMULARIO 1000</h2>
    <table>
        <thead>
            <tr>
                <th width="35%">CONCEPTO</th>
                <th width="45%">CÁLCULO</th>
                <th width="20%">IMPORTE (Bs)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>a) Importe de la deuda</td>
                <td>Tributo Omitido Original</td>
                <td style="text-align: right;"><?php echo number_format($resultado['tributoOmitido'], 2); ?></td>
            </tr>
            <tr>
                <td>b) Mantenimiento de Valor</td>
                <td>MV = [(<?php echo number_format($resultado['ufvPago'], 5); ?> ÷ <?php echo number_format($resultado['ufvVencimiento'], 5); ?>) - 1] × <?php echo number_format($resultado['tributoOmitido'], 2); ?> = <?php echo number_format((($resultado['ufvPago'] / $resultado['ufvVencimiento']) - 1) * $resultado['tributoOmitido'], 5); ?></td>
                <td style="text-align: right;"><?php echo number_format($resultado['mantenimientoValor'], 2); ?></td>
            </tr>
            <tr>
                <td>c) Intereses Moratorios</td>
                <td>
                    <?php 
                    $aniosMora = $resultado['diasMora'] / 365;
                    if ($aniosMora <= 4): ?>
                        Tasa única 4%: TOa × [(1 + 0.04/360)^<?php echo $resultado['diasMora']; ?> - 1]<br>
                        Factor = <?php echo number_format(pow(1+0.04/360, $resultado['diasMora']), 6); ?>
                    <?php else: ?>
                        <div class="tramos-detail">
                            <strong>Cálculo por tramos escalonados:</strong><br>
                            <?php
                            $diasRestantes = $resultado['diasMora'];
                            $principal = $resultado['tributoActualizado'];
                            $fechaInicial = new DateTime($resultado['fechaVencimiento']);
                            $fechaActual = clone $fechaInicial;
                            
                            // Tramo 1: Hasta 4 años al 4%
                            if ($diasRestantes > 0) {
                                $diasTramo1 = min($diasRestantes, 1460);
                                $fechaFinal1 = clone $fechaActual;
                                $fechaFinal1->add(new DateInterval("P{$diasTramo1}D"));
                                $factor1 = pow(1+0.04/360, $diasTramo1);
                                
                                echo "<strong>Tramo 1 (4%):</strong> " . $fechaActual->format('d/m/Y') . " al " . $fechaFinal1->format('d/m/Y') . " = $diasTramo1 días<br>";
                                echo "Factor: (1+0.04/360)^$diasTramo1 = " . number_format($factor1, 6) . "<br>";
                                
                                $fechaActual = $fechaFinal1;
                                $diasRestantes -= $diasTramo1;
                            }
                            
                            // Tramo 2: De 4 a 7 años al 6%
                            if ($diasRestantes > 0) {
                                $diasTramo2 = min($diasRestantes, 1095);
                                $fechaFinal2 = clone $fechaActual;
                                $fechaFinal2->add(new DateInterval("P{$diasTramo2}D"));
                                $factor2 = pow(1+0.06/360, $diasTramo2);
                                
                                echo "<strong>Tramo 2 (6%):</strong> " . $fechaActual->format('d/m/Y') . " al " . $fechaFinal2->format('d/m/Y') . " = $diasTramo2 días<br>";
                                echo "Factor: (1+0.06/360)^$diasTramo2 = " . number_format($factor2, 6) . "<br>";
                                
                                $fechaActual = $fechaFinal2;
                                $diasRestantes -= $diasTramo2;
                            }
                            
                            // Tramo 3: Más de 7 años al 10%
                            if ($diasRestantes > 0) {
                                $fechaFinal3 = clone $fechaActual;
                                $fechaFinal3->add(new DateInterval("P{$diasRestantes}D"));
                                $factor3 = pow(1+0.10/360, $diasRestantes);
                                
                                echo "<strong>Tramo 3 (10%):</strong> " . $fechaActual->format('d/m/Y') . " al " . $fechaFinal3->format('d/m/Y') . " = $diasRestantes días<br>";
                                echo "Factor: (1+0.10/360)^$diasRestantes = " . number_format($factor3, 6);
                            }
                            ?>
                        </div>
                    <?php endif; ?>
                </td>
                <td style="text-align: right;"><?php echo number_format($resultado['interesesMoratorios'], 2); ?></td>
            </tr>
            <tr>
                <td>d) Multa por Incumplimiento</td>
                <td><?php 
                if ($tipoContribuyente === 'natural') echo "Persona Natural: 50 × " . number_format($resultado['ufvPago'], 5);
                elseif ($tipoContribuyente === 'juridica') echo "Persona Jurídica: 100 × " . number_format($resultado['ufvPago'], 5);
                else echo "Sin multa aplicable";
                ?></td>
                <td style="text-align: right;"><?php echo number_format($resultado['multa'], 2); ?></td>
            </tr>
            <tr class="total-row">
                <td><strong>TOTAL A PAGAR</strong></td>
                <td><strong>Suma total con redondeo SIAT</strong></td>
                <td style="text-align: right;"><strong><?php echo number_format($resultado['totalDeuda'], 2); ?></strong></td>
            </tr>
        </tbody>
    </table>
    
    <div class="footer">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div>
                <p><strong>Normativa:</strong> RND N° 102500000013 (Redondeo SIAT), Tasas: 4% (≤4a), 6% (5-7a), 10% (8+a)</p>
                <p><strong>UFV:</strong> Banco Central de Bolivia | <strong>Generado:</strong> BoliviaImpuestos.com</p>
            </div>
            <div style="text-align: right; font-size: 8px;">
                <p><strong>Advertencia:</strong> Reporte informativo. Verificar con autoridades competentes.</p>
                <p>Los cálculos incluyen redondeo oficial SIAT a 2 decimales.</p>
            </div>
        </div>
    </div>
</body>
</html>