<?php
/**
 * ICYLAB OS - Visor de Cotizaciones (Formato Carta Oficial Auto-Escalable)
 */

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/format.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';

require_login();
require_permission('module.crm'); 

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$pdo = db();

try {
    // 1. Obtener cabecera, metadatos y datos del cliente
    $stmt = $pdo->prepare("
        SELECT q.*, o.title AS opportunity_title, o.owner_name, 
               c.customer_name, c.legal_name, c.customer_tax_id, 
               c.email, c.phone, c.city, c.district, c.address, c.region, c.payment_terms, c.facto_payment_term
        FROM crm_quotes q
        LEFT JOIN crm_opportunities o ON q.opportunity_id = o.id
        JOIN crm_customers c ON q.customer_id = c.id
        WHERE q.id = ?
        LIMIT 1
    ");
    $stmt->execute(array($id));
    $quote = $stmt->fetch();

    if (!$quote) {
        die("Error: La cotización con ID $id no existe en el sistema.");
    }

    $quoteDeletedAt = $quote['deleted_at'] ?? null;
    $isQuoteDeleted = !empty($quoteDeletedAt);

    // 2. Obtener las filas de ítems del documento
    $stmtItems = $pdo->prepare("
        SELECT
            qi.*,
            p.description AS product_description
        FROM crm_quote_items qi
        LEFT JOIN products p ON p.id = qi.product_id
        WHERE qi.quote_id = ?
        ORDER BY qi.id ASC
    ");
    $stmtItems->execute(array($id));
    $items = $stmtItems->fetchAll();

    // 3. Cargar datos dinámicos de la empresa emisora
    $stmtSettings = $pdo->query("SELECT * FROM system_settings WHERE id = 1");
    $company = $stmtSettings->fetch() ?: array();

    // Calcular Neto
    $subtotalVal = isset($quote['subtotal']) ? (float)$quote['subtotal'] : 0.0;
    $discountVal = isset($quote['discount_amount']) ? (float)$quote['discount_amount'] : 0.0;
    $montoNeto = $subtotalVal - $discountVal;

    // Configurar dinámicamente la clase del badge de estado
    $statusValue = $quote['status'] ?? 'Borrador';
    $badgeClass = '';
    if ($statusValue === 'Aceptada') {
        $badgeClass = 'badge-success';
    } elseif ($statusValue === 'Enviada') {
        $badgeClass = 'badge-warning';
    } elseif ($statusValue === 'Rechazada') {
        $badgeClass = 'badge-error';
    }

    // Control de acceso a facturacion desde la cotizacion seleccionada
    $hasBillingAccess = function_exists('user_can') && user_can('module.billing');
    $billingDocumentId = trim((string)($quote['facto_document_id'] ?? ''));
    $billingInvoiceNumber = trim((string)($quote['invoice_number'] ?? ''));
    $hasLinkedTaxDocument = $billingDocumentId !== '' || $billingInvoiceNumber !== '';
    $canOpenBillingFlow = !$isQuoteDeleted && $hasBillingAccess && in_array($statusValue, array('Aceptada', 'Facturada', 'Esperando pago', 'Pagada'), true);
    $billingFlowUrl = '/modules/billing/index.php?quote_id=' . (int)$id . '&from=quote';

    // Determinar Razón Social real con respaldo seguro
    $razonSocial = !empty($quote['legal_name']) ? $quote['legal_name'] : $quote['customer_name'];
    $customerAddress = trim(implode(', ', array_filter(array(
        $quote['address'] ?? '',
        $quote['district'] ?? '',
        $quote['city'] ?? '',
        $quote['region'] ?? ''
    ), function ($value) {
        return trim((string)$value) !== '';
    })));
    $customerPaymentTerms = icylab_payment_terms_label($quote['payment_terms'] ?? ($quote['facto_payment_term'] ?? 'contado'));

} catch (Throwable $e) {
    echo "<div style='background:#1e293b; color:#ef4444; padding:25px; border-radius:8px; font-family:monospace; border:1px solid #334155; max-width:800px; margin:30px auto;'>";
    echo "<h3>💥 Error al cargar la Vista de Cotización:</h3>";
    echo "<p><strong>Mensaje:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "</div>";
    die();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cotización <?php echo safe_text($quote['quote_number'] ?? 'S/N'); ?></title>
    
    <link rel="stylesheet" href="/assets/css/02-themes.css">
    <link rel="stylesheet" href="/assets/css/06-components.css">
    <link rel="stylesheet" href="/assets/css/07-business-components.css">

    <style>
        :root {
            color-scheme: dark;
            --surface-0: #090909;
            --surface-1: #111111;
            --surface-2: #171717;
            --text-primary: #F5F5F5;
            --text-secondary: #B4B4B4;
            --text-muted: #8A8A8A;
            --text-inverse: #090909;
            --border-default: #303030;
            --border-strong: #474747;
            --color-primary: #00FF30;
            --color-success: #00FF30;
            --color-warning: #F4B400;
            --color-error: #FF4D4F;
            --shadow-md: 0 8px 24px rgba(0,0,0,.28);
            --shadow-lg: 0 24px 64px rgba(0,0,0,.42);
            --radius-md: 8px;
            --radius-xl: 18px;
            --radius-full: 999px;
            --motion-fast: .18s ease;
            --font-stack: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            --fs-xl: 20px;
            --fs-lg: 16px;
            --fs-md: 14px;
            --fs-base: 13px;
            --fs-sm: 12px;
            --fs-xs: 10px;
        }

        @page { size: letter; margin: 15mm 12mm; }
        *, *::before, *::after { box-sizing: border-box; }
        
        body { 
            font-family: var(--font-stack); 
            color: var(--text-primary); 
            font-size: var(--fs-base);
            line-height: 1.5;
            margin: 0; 
            padding: 30px 20px; 
            background-color: var(--surface-0);
            -webkit-print-color-adjust: exact; 
            print-color-adjust: exact; 
        }
        
        .quote-deleted-banner {
            max-width: 820px;
            margin: 0 auto 18px auto;
            border: 1px solid rgba(255, 77, 79, .45);
            background: rgba(255, 77, 79, .10);
            color: #ffd4d4;
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 13px;
        }
        .quote-deleted-banner strong { color: #fff; }

        /* ==========================================================================
           CONTROLES DEL HEADER
           ========================================================================== */
        .preview-app-header {
            max-width: 820px;
            margin: 0 auto 30px auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
            background: var(--surface-1);
            border: 1px solid var(--border-default);
            border-radius: var(--radius-xl);
            padding: 24px;
            box-shadow: var(--shadow-md);
        }

        .page-header-content { display: flex; flex-direction: column; gap: 6px; }
        .page-header-content h1 { margin: 0; font-size: 1.5rem; font-weight: 700; color: var(--text-primary); line-height: 1.2; }
        .page-header-content p { margin: 0; font-size: 0.88rem; color: var(--text-secondary); }

        .preview-badge {
            display: inline-flex; align-items: center; width: fit-content; min-height: 24px; padding: 0 10px;
            border-radius: var(--radius-full); font-size: 0.75rem; font-weight: 650; text-transform: uppercase;
            letter-spacing: 0.04em; background: var(--surface-2); border: 1px solid var(--border-default); color: var(--text-secondary);
        }
        .preview-badge.badge-success { color: var(--color-success); border-color: rgba(0, 255, 48, 0.28); }
        .preview-badge.badge-warning { color: var(--color-warning); border-color: rgba(244, 180, 0, 0.28); }
        .preview-badge.badge-error { color: var(--color-error); border-color: rgba(255, 77, 79, 0.28); }

        .actions-cluster { display: flex; align-items: center; gap: 12px; flex-shrink: 0; flex-wrap: wrap; justify-content: flex-end; }
        
        .btn { 
            display: inline-flex; align-items: center; justify-content: center; min-height: 40px; padding: 0 18px;
            border: 1px solid transparent; border-radius: var(--radius-md) !important; font-weight: 600; font-family: var(--font-stack);
            font-size: var(--fs-base); color: var(--text-primary); cursor: pointer; text-decoration: none; 
            transition: background var(--motion-fast), border-color var(--motion-fast), color var(--motion-fast);
            white-space: nowrap;
        }
        .btn-outline { background: transparent; border-color: var(--border-default); }
        .btn-outline:hover { background: var(--surface-2); border-color: var(--border-strong); }
        .btn-primary { background: var(--color-primary); color: var(--text-inverse); border: 1px solid var(--color-primary); }
        .btn-primary:hover { background: transparent; color: var(--color-primary); border-color: var(--color-primary); }
        
        /* ==========================================================================
           CONTENEDOR INTELIGENTE DEL DOCUMENTO (Aísla el escalado)
           ========================================================================== */
        .document-wrapper {
            width: 100%;
            overflow: hidden;
            box-sizing: border-box;
        }

        .page-document { 
            width: 820px; 
            min-width: 820px;
            margin: 0 auto; 
            background: #ffffff; 
            padding: 40px; 
            border-radius: var(--radius-xl); 
            box-shadow: var(--shadow-lg); 
            transform-origin: top left;
        }
        
        /* ==========================================================================
           ESTILOS ESTRICTOS DE HOJA CARTA
           ========================================================================== */
        .header-section { display: table; width: 100%; margin-bottom: 30px; }
        .company-info { display: table-cell; width: 60%; vertical-align: top; }
        .company-logo-img { max-height: 48px; margin-bottom: 12px; }
        .company-meta-text { color: #475569; font-size: var(--fs-sm); line-height: 1.4; }
        .company-name-fallback { font-size: var(--fs-xl); margin: 0 0 10px 0; color: #1e293b; }
        
        .company-activity { font-size: var(--fs-sm); font-weight: 700; line-height: 1.15; letter-spacing: -0.02em; text-transform: uppercase; color: #1e293b; display: block; max-width: 300px; margin-bottom: 5px; }
        
        .rut-box { display: table-cell; width: 40%; border: 2px solid var(--color-primary); border-radius: 6px; text-align: center; padding: 18px 10px; background: #f8fafc; vertical-align: top; color: #1e293b; }
        .rut-box h2 { margin: 0; font-size: var(--fs-lg); font-weight: 700; }
        .rut-box .doc-type { margin: 6px 0; font-size: var(--fs-xl); font-weight: 800; color: var(--color-primary); letter-spacing: 1px; }
        .rut-box .doc-number { font-size: var(--fs-md); font-weight: 700; color: #475569; }

        .info-table { width: 100%; border-collapse: separate; border-spacing: 0; border: 2px solid #e2e8f0; border-radius: 6px; overflow: hidden; margin-bottom: 25px; }
        .info-table td { padding: 6px 12px; border-bottom: 1px solid #e2e8f0; border-right: 1px solid #e2e8f0; vertical-align: middle; font-size: var(--fs-base); color: #1e293b; }
        .info-table td:last-child { border-right: none; }
        .info-table tr:last-child td { border-bottom: none; }
        .info-table td.bg-label { background-color: #f8fafc; font-weight: 600; color: #475569; width: 15%; }
        
        .items-table { width: 100%; border-collapse: separate; border-spacing: 0; border: 2px solid #e2e8f0; border-radius: 6px; overflow: hidden; margin-bottom: 25px; }
        .items-table th { background: #f8fafc; border-bottom: 2px solid #e2e8f0; text-align: left; padding: 8px 12px; font-weight: 600; color: #475569; font-size: var(--fs-sm); text-transform: uppercase; }
        .items-table td { padding: 8px 12px; border-bottom: 1px solid #e2e8f0; vertical-align: middle; font-size: var(--fs-base); color: #1e293b; }
        .items-table tr:last-child td { border-bottom: none; }
        .items-table tr.filler-row td { height: 36px; } 
        
        .sku-cell { font-size: var(--fs-xs); color: #475569; white-space: nowrap; letter-spacing: -0.02em; }
        .item-name { font-weight: 600; color: #0f172a; font-size: var(--fs-base); }
        .item-desc { font-size: var(--fs-sm); color: #475569; margin-top: 4px; line-height: 1.4; font-weight: 400; }
        .status-afecto { color: var(--color-primary); font-weight: 600; }
        
        .footer-summary-grid { display: flex !important; width: 100%; margin-top: 15px; gap: 30px; align-items: stretch; }
        .legal-and-payments { width: 58%; display: flex !important; flex-direction: column !important; gap: 12px; }
        
        .section-subtitle { font-size: var(--fs-sm); font-weight: 700; text-transform: uppercase; color: #475569 !important; margin: 0 0 6px 0; border-bottom: 1px solid #e2e8f0; padding-bottom: 4px; flex-shrink: 0; }
        .payment-details-box { background: #f8fafc !important; border: 1px solid #e2e8f0 !important; border-radius: 6px !important; padding: 10px 14px; font-size: var(--fs-sm); color: #475569 !important; line-height: 1.45; flex: 1 !important; }
        
        .totals-box { width: 42%; display: flex !important; flex-direction: column !important; }
        .totals-table-wrapper { width: 100%; display: block !important; }
        .totals-box table { width: 100%; border-collapse: collapse; height: auto !important; }
        .totals-box td { padding: 5px 10px; border-bottom: 1px solid #e2e8f0; font-size: var(--fs-base); color: #1e293b; }
        .totals-box tr.grand-total { font-size: var(--fs-md); font-weight: bold; background: #f8fafc; }
        .totals-box tr.grand-total td { border-bottom: 2px solid var(--color-primary); border-top: 1px solid #e2e8f0; }
        
        .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; }
        .text-center { text-align: center; }
        .text-right { text-align: right; }
        .font-medium { font-weight: 500; }
        .text-danger { color: var(--color-error); }

        /* ==========================================================================
           RESPONSIVIDAD (SOLO AFECTA A LA BARRA DE CONTROL EN MÓVIL)
           ========================================================================== */
        @media (max-width: 860px) {
            body { padding: 15px 10px; }
            .preview-app-header {
                flex-direction: column;
                align-items: stretch;
                padding: 20px 16px;
                gap: 16px;
            }
            .page-header-content { align-items: center; text-align: center; }
            .actions-cluster { flex-direction: column; width: 100%; gap: 8px; }
            .actions-cluster .btn { width: 100%; justify-content: center; }
        }

        @media print { 
            body { background: #ffffff !important; padding: 0 !important; margin: 0 !important; } 
            .preview-app-header { display: none !important; } 
            .document-wrapper { overflow: visible !important; display: block !important; }
            .page-document { 
                box-shadow: none !important; 
                padding: 0 !important; 
                max-width: 100% !important; 
                border-radius: 0 !important; 
                transform: none !important;
                margin: 0 !important;
                width: 100% !important;
                min-width: 0 !important;
            } 
        }
    </style>
</head>
<body>
<?php if (!empty($isQuoteDeleted)): ?>
    <div class="quote-deleted-banner">
        <strong>Cotización eliminada:</strong> este documento está en papelera lógica desde <?php echo safe_text(date('d-m-Y H:i', strtotime($quoteDeletedAt))); ?>. Se conserva sólo para revisión e historial.
    </div>
<?php endif; ?>

    <header class="preview-app-header">
        <div class="page-header-content">
            <span class="preview-badge <?php echo $badgeClass; ?>"><?php echo safe_text($statusValue); ?></span>
            <h1><?php echo safe_text($quote['quote_number'] ?? 'S/N'); ?></h1>
            <p class="text-secondary">Oportunidad: <?php echo safe_text(!empty($quote['opportunity_title']) ? $quote['opportunity_title'] : 'Venta directa'); ?></p>
        </div>
        
        <div class="actions-cluster">
            <?php 
            // Magia dinámica: Detecta de dónde viene el usuario para el botón "Volver"
            $backUrl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/modules/crm/quotes.php';
            ?>
            <a href="<?php echo safe_text($backUrl); ?>" class="btn btn-outline">Volver</a>
            <?php if (!empty($canOpenBillingFlow)): ?>
                <?php if (!empty($hasLinkedTaxDocument)): ?>
                    <a href="<?php echo safe_text($billingFlowUrl); ?>" class="btn btn-outline">Ver facturacion</a>
                <?php elseif ($statusValue === 'Aceptada'): ?>
                    <a href="<?php echo safe_text($billingFlowUrl); ?>" class="btn btn-primary">Facturar</a>
                <?php else: ?>
                    <a href="<?php echo safe_text($billingFlowUrl); ?>" class="btn btn-outline">Revisar facturacion</a>
                <?php endif; ?>
            <?php endif; ?>
            <button onclick="window.print();" class="btn btn-primary">Descargar PDF</button>
        </div>
    </header>

    <div class="document-wrapper">
        <div class="page-document">
            <header class="header-section">
                <div class="company-info">
                    <?php if (!empty($company['company_logo'])): ?>
                        <img src="<?php echo safe_text($company['company_logo']); ?>" alt="Logo" class="company-logo-img">
                    <?php else: ?>
                        <h1 class="company-name-fallback"><?php echo safe_text($company['company_name'] ?: 'ICYLAB SPA'); ?></h1>
                    <?php endif; ?>
                    <div class="company-meta-text">
                        <span class="company-activity"><?php echo safe_text($company['company_giro'] ?: 'PRODUCCIÓN, I+D Y VENTA DE ADITIVOS E INSUMOS PARA BEBIDAS Y ALIMENTOS'); ?></span>
                        Casa Matriz: <?php echo safe_text($company['company_address'] ?? ''); ?>, <?php echo safe_text($company['company_comuna'] ?? ''); ?>, <?php echo safe_text($company['company_ciudad'] ?? ''); ?><br>
                        Fono: <?php echo safe_text($company['company_phone'] ?? ''); ?> · Email: <?php echo safe_text($company['company_email'] ?? ''); ?>
                    </div>
                </div>
                <div class="rut-box">
                    <h2>R.U.T.: <?php echo safe_text($company['company_tax_id'] ?: '77.884.104-5'); ?></h2>
                    <div class="doc-type">COTIZACIÓN</div>
                    <div class="doc-number">Nº <?php echo safe_text(str_replace('COT-', '', $quote['quote_number'] ?? '0000')); ?></div>
                </div>
            </header>

            <table class="info-table">
                <tr>
                    <td class="bg-label">Razón Social</td>
                    <td style="width: 35%;"><strong><?php echo safe_text($razonSocial); ?></strong></td>
                    <td class="bg-label">Fecha</td>
                    <td style="width: 35%;"><?php echo isset($quote['created_at']) ? date('d-m-Y', strtotime($quote['created_at'])) : date('d-m-Y'); ?></td>
                </tr>
                <tr>
                    <td class="bg-label">R.U.T.</td>
                    <td><?php echo safe_text(format_rut($quote['customer_tax_id'] ?? '—')); ?></td>
                    <td class="bg-label">Email Cliente</td>
                    <td><?php echo safe_text($quote['email'] ?? '—'); ?></td>
                </tr>
                <tr>
                    <td class="bg-label">Teléfono</td>
                    <td><?php echo safe_text($quote['phone'] ?? '—'); ?></td>
                    <td class="bg-label">Vendedor</td>
                    <td><?php echo safe_text($quote['owner_name'] ?? 'Juan Pablo Daszenies'); ?></td>
                </tr>
                <tr>
                    <td class="bg-label">Dirección</td>
                    <td><?php echo safe_text($customerAddress !== '' ? $customerAddress : '—'); ?></td>
                    <td class="bg-label">Condición de pago</td>
                    <td><?php echo safe_text($customerPaymentTerms); ?></td>
                </tr>
            </table>

            <table class="items-table">
                <thead>
                    <tr>
                        <th style="width: 12%; white-space: nowrap;">SKU</th>
                        <th style="width: 40%;">Glosa / Descripción</th>
                        <th class="text-center" style="width: 10%;">Cant.</th>
                        <th class="text-center" style="width: 10%;">Unidad</th>
                        <th class="text-right" style="width: 12%;">Prc. Unit</th>
                        <th class="text-center" style="width: 12%;">Afecto</th>
                        <th class="text-right" style="width: 14%;">Monto</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $rowCount = 0;
                    if(isset($items) && is_array($items)): 
                        foreach ($items as $item): 
                            $rowCount++;
                            $itemSku = '—';
                            $itemName = $item['name'] ?? '';
                            
                            if (preg_match('/ \(SKU: (.*)\)$/', $itemName, $matches)) {
                                $itemSku = $matches[1];
                                $itemName = preg_replace('/ \(SKU: .*\)$/', '', $itemName);
                            }
                            
                            if (!empty($item['sku']) && $item['sku'] !== 'S/S') {
                                $itemSku = $item['sku'];
                            }
                    ?>
                        <tr>
                            <td class="font-mono sku-cell"><?php echo safe_text($itemSku); ?></td>
                            <td>
                                <div class="item-name"><?php echo safe_text($itemName); ?></div>
                                <?php
                                $itemDescription = trim((string)($item['description'] ?? ''));
                                $productDescription = trim((string)($item['product_description'] ?? ''));

                                if (
                                    $itemDescription === '' ||
                                    preg_match('/^SKU\s*:/i', $itemDescription) ||
                                    $itemDescription === $itemSku
                                ) {
                                    $itemDescription = $productDescription;
                                }
                                ?>
                                <?php if ($itemDescription !== ''): ?>
                                    <div class="item-desc">
                                        <?php echo nl2br(safe_text($itemDescription)); ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="text-center"><?php echo safe_text(format_quantity($item['quantity'] ?? 0)); ?></td>
                            <td class="text-center"><?php echo safe_text($item['unit'] ?? 'unidad'); ?></td>
                            <td class="text-right"><?php echo clp($item['price_unit'] ?? 0); ?></td>
                            <td class="text-center status-afecto">SI</td>
                            <td class="text-right font-medium"><?php echo clp($item['total_item'] ?? 0); ?></td>
                        </tr>
                    <?php 
                        endforeach; 
                    endif; 

                    $minRows = 5;
                    if ($rowCount < $minRows):
                        for ($i = $rowCount; $i < $minRows; $i++):
                    ?>
                        <tr class="filler-row">
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                        </tr>
                    <?php 
                        endfor;
                    endif;
                    ?>
                </tbody>
            </table>

            <div class="footer-summary-grid">
                
                <div class="legal-and-payments">
                    <h4 class="section-subtitle">Formas de pago</h4>
                    <div class="payment-details-box">
                        <strong>Transferencia bancaria:</strong><br>
                        <?php echo safe_text($company['bank_name'] ?: 'Banco Santander'); ?><br>
                        <?php echo safe_text($company['bank_account_type'] ?: 'Cuenta Corriente'); ?> · N° <?php echo safe_text($company['bank_account_number'] ?: '000094796822'); ?><br>
                        <?php echo safe_text($company['bank_holder_name'] ?: 'ICYLAB SPA'); ?> · RUT: <?php echo safe_text($company['bank_holder_tax_id'] ?: '77.884.104-5'); ?><br>
                        <?php echo safe_text($company['bank_email'] ?: 'contacto@icylab.cl'); ?>
                    </div>

                    <?php if (!empty($quote['notes'])): ?>
                        <h4 class="section-subtitle" style="margin-top: 10px;">Condiciones comerciales</h4>
                        <div class="payment-details-box" style="white-space: pre-line; padding: 12px 14px;">
                            <?php echo safe_text($quote['notes']); ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="totals-box">
                    <div class="totals-table-wrapper">
                        <table>
                            <tr>
                                <td>Subtotal Bruto:</td>
                                <td class="text-right"><?php echo clp($quote['subtotal'] ?? 0); ?></td>
                            </tr>
                            <?php if (isset($quote['discount_amount']) && $quote['discount_amount'] > 0): ?>
                                <tr class="text-danger font-medium">
                                    <td>Descuento (<?php echo (float)($quote['discount_percent'] ?? 0); ?>%):</td>
                                    <td class="text-right">- <?php echo clp($quote['discount_amount']); ?></td>
                                </tr>
                            <?php endif; ?>
                            <tr class="font-bold">
                                <td>Monto Neto:</td>
                                <td class="text-right"><?php echo clp($montoNeto); ?></td>
                            </tr>
                            <tr>
                                <td>Monto Exento:</td>
                                <td class="text-right">$ 0</td>
                            </tr>
                            <tr>
                                <td>IVA (19%):</td>
                                <td class="text-right"><?php echo clp($quote['iva'] ?? 0); ?></td>
                            </tr>
                            <tr class="grand-total">
                                <td>Total General:</td>
                                <td class="text-right"><?php echo clp($quote['total'] ?? 0); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <script>
    // =========================================================================
    // LÓGICA DE AUTO-ESCALADO (Magia Responsiva)
    // =========================================================================
    function scaleDocument() {
        const doc = document.querySelector('.page-document');
        const wrapper = document.querySelector('.document-wrapper');
        
        if (!doc || !wrapper) return;

        // Limpiamos estilos temporalmente para medir la pantalla cruda
        doc.style.transform = 'none';
        wrapper.style.height = 'auto';
        
        // Calculamos el ancho seguro en base a la pantalla y los paddings
        const isMobile = window.innerWidth <= 860;
        const safeWidth = window.innerWidth - (isMobile ? 20 : 40); 

        if (safeWidth < 820) {
            // El contenedor es más pequeño que el papel, aplicamos Scale
            const scale = safeWidth / 820;
            doc.style.transformOrigin = 'top left';
            doc.style.transform = 'scale(' + scale + ')';
            doc.style.margin = '0';
            
            // Recortamos el alto fantasma del wrapper
            wrapper.style.height = (doc.offsetHeight * scale) + 'px';
        } else {
            // Hay espacio de sobra, centrado natural
            doc.style.margin = '0 auto';
        }
    }

    window.addEventListener('resize', scaleDocument);
    window.addEventListener('DOMContentLoaded', scaleDocument);
    setTimeout(scaleDocument, 100);
    </script>
</body>
</html>