<?php
/**
 * ICYLAB OS - Vista Previa de Cotizaciones (Soporte de Descripción Dinámica)
 */

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'; // 1. Motor de permisos

require_login();

function quote_preview_allowed_units()
{
    return array('unidad', 'mL', 'L', 'g', 'kg', 'pack', 'caja', 'servicio');
}

function quote_preview_clean_unit($unit)
{
    $unit = trim((string)$unit);
    return in_array($unit, quote_preview_allowed_units(), true) ? $unit : 'unidad';
}
require_permission('module.crm'); // 2. El candado definitivo

$pdo = db();

$opportunityId   = isset($_POST['opportunity_id']) ? (int) $_POST['opportunity_id'] : 0;
$customerId      = isset($_POST['customer_id']) ? (int) $_POST['customer_id'] : 0;
$quoteId         = isset($_POST['quote_id']) ? (int) $_POST['quote_id'] : 0; 
$status          = isset($_POST['status']) ? trim($_POST['status']) : 'Borrador'; /* 🔥 LÍNEA NUEVA */
$notes           = isset($_POST['notes']) ? trim($_POST['notes']) : '';
$discountPercent = isset($_POST['discount_percent']) ? (float) $_POST['discount_percent'] : 0.0;
$items           = isset($_POST['items']) ? $_POST['items'] : array();

// 1. Persistencia total: Guardamos el POST completo en la sesión
$_SESSION['quote_preview_old'] = $_POST;

$opportunityId   = isset($_POST['opportunity_id']) ? (int) $_POST['opportunity_id'] : 0;
$customerId      = isset($_POST['customer_id']) ? (int) $_POST['customer_id'] : 0;
$quoteId         = isset($_POST['quote_id']) ? (int) $_POST['quote_id'] : 0; 
$notes           = isset($_POST['notes']) ? trim($_POST['notes']) : '';
$discountPercent = isset($_POST['discount_percent']) ? (float) $_POST['discount_percent'] : 0.0;
$items           = isset($_POST['items']) ? $_POST['items'] : array();

if ($opportunityId === 0 || empty($items)) {
    die('Datos insuficientes para generar la vista previa.');
}

// 2. Cargar metadatos de la oportunidad y configuración de la empresa
$stmt = $pdo->prepare("
    SELECT o.title AS opportunity_title, o.owner_name, c.customer_name, c.customer_tax_id, c.email, c.phone, c.address, c.district, c.city, c.region, c.payment_terms, c.facto_payment_term
    FROM crm_opportunities o
    JOIN crm_customers c ON o.customer_id = c.id
    WHERE o.id = ? LIMIT 1
");
$stmt->execute(array($opportunityId));
$meta = $stmt->fetch();

$customerAddress = trim(implode(', ', array_filter(array(
    $meta['address'] ?? '',
    $meta['district'] ?? '',
    $meta['city'] ?? '',
    $meta['region'] ?? ''
), function ($value) {
    return trim((string)$value) !== '';
})));
$customerPaymentTerms = icylab_payment_terms_label($meta['payment_terms'] ?? ($meta['facto_payment_term'] ?? 'contado'));

$stmtSettings = $pdo->query("SELECT * FROM system_settings WHERE id = 1");
$company = $stmtSettings->fetch() ?: array();

// 3. Procesa ítems e incluir descripción del catálogo
$subtotal = 0;
$validItems = array();

foreach ($items as $item) {
    $qty = isset($item['quantity']) ? parse_quantity($item['quantity']) : 0;
    $price = isset($item['price_unit']) ? (float) $item['price_unit'] : 0.0;
    $unit = quote_preview_clean_unit($item['unit'] ?? 'unidad');
    
    if ($qty > 0 && $price >= 0) {
        $itemTotal = $qty * $price;
        $subtotal += $itemTotal;
        
        $validItems[] = array(
            'product_id'  => $item['product_id'] ?? 'S/I',
            'name'        => !empty($item['name']) ? trim($item['name']) : 'Producto sin nombre',
            'sku'         => !empty($item['sku']) ? trim($item['sku']) : 'S/S',
            'description' => !empty($item['description']) ? trim($item['description']) : '', 
            'quantity'    => $qty,
            'unit'        => $unit,
            'price_unit'  => $price,
            'total_item'  => $itemTotal
        );
    }
}

$discountAmount = $subtotal * ($discountPercent / 100);
$netWithDiscount = $subtotal - $discountAmount;
$iva = $netWithDiscount * 0.19;
$totalGeneral = $netWithDiscount + $iva;

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Vista Previa de Cotizació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>
        /* ==========================================================================
           1. COMPILACIÓN E INYECCIÓN DE TOKENS DE DISEÑO (02-themes.css & 06-components.css)
           ========================================================================== */
        :root {
            color-scheme: dark;

            /* Escala de grises y fondos oficiales */
            --surface-0: #090909;
            --surface-1: #111111;
            --surface-2: #171717;
            --surface-3: #1F1F1F;
            --surface-4: #292929;

            /* Tipografía y estados textuales */
            --text-primary: #F5F5F5;
            --text-secondary: #B4B4B4;
            --text-muted: #8A8A8A;
            --text-inverse: #090909;

            /* Sistema de Bordes */
            --border-subtle: #202020;
            --border-default: #303030;
            --border-strong: #474747;

            /* Identidad de marca y semántica */
            --color-primary: #00FF30;
            --color-primary-hover: #2EFF58;
            --color-success: #00FF30;
            --color-warning: #F4B400;
            --color-error: #FF4D4F;

            /* Sombras y efectos de elevación */
            --shadow-md: 0 8px 24px rgba(0,0,0,.28);
            --shadow-lg: 0 24px 64px rgba(0,0,0,.42);

            /* Sistema de curvas unificado */
            --radius-md: 8px;
            --radius-xl: 18px;
            --radius-full: 999px;
            
            /* Animaciones y Fuentes Locales */
            --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; 
        }
        
        /* ==========================================================================
           2. CABECERA DE CONTROL HOMOLOGADA (.page-header de opportunity.php)
           ========================================================================== */
        .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;
            color: var(--text-secondary);
            background: var(--surface-2);
            border: 1px solid var(--border-default);
            text-transform: uppercase;
            letter-spacing: 0.04em;
        }

        .actions-cluster {
            display: flex;
            align-items: center;
            gap: 12px;
            flex-shrink: 0;
        }
        
        /* ==========================================================================
           3. BOTONES OPERATIVOS COMPATIBLES (06-components.css)
           ========================================================================== */
        .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), box-shadow var(--motion-fast);
        }

        .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);
        }
        
        /* ==========================================================================
           4. HOJA FÍSICA IMPRESA (Mantiene proporciones y tipografía fidedigna)
           ========================================================================== */
        .page-document { 
            max-width: 820px; 
            margin: auto; 
            background: #ffffff; 
            padding: 40px; 
            border-radius: var(--radius-xl); 
            box-shadow: var(--shadow-lg); 
        }
        
        .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 100px 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; }
        
        /* Alto de filas compacto regulado a 6px */
        .info-table { 
            width: 100%; 
            border-collapse: separate; 
            border-spacing: 0; 
            margin-bottom: 25px; 
            border: 2px solid #e2e8f0; 
            border-radius: 6px; 
            overflow: hidden; 
        }
        .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%; }
        
        /* Alto de filas compacto en la tabla de productos regulado a 8px */
        .items-table { 
            width: 100%; 
            border-collapse: separate; 
            border-spacing: 0; 
            margin-bottom: 25px; 
            border: 2px solid #e2e8f0; 
            border-radius: 6px; 
            overflow: hidden; 
        }
        .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; }
        
        /* ==========================================================================
           5. SISTEMA FLEXBOX BLINDADO CONTRA DESCUADRES VERTICALES (ESCRITORIO/IMPRESIÓN)
           ========================================================================== */
        .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;
        }
        
        .summary-section {
            display: flex !important;
            flex-direction: column !important;
            flex: 1 !important; 
            min-height: 0;
        }
        
        .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); }

        @media print { 
            body { background: #ffffff !important; padding: 0 !important; margin: 0 !important; } 
            .preview-app-header { display: none !important; } 
            .page-document { box-shadow: none !important; padding: 0 !important; max-width: 100% !important; border-radius: 0 !important; } 
        }
    </style>
</head>
<body>

    <header class="preview-app-header">
        <div class="page-header-content">
            <span class="preview-badge">Modo Vista Previa</span>
            <h1>Validación de Cotización</h1>
            <p class="text-secondary">Verifica que las glosas, cantidades y el descuento sean correctos antes del registro definitivo.</p>
        </div>
        
        <div class="actions-cluster">
            <?php 
            $backUrl = ($quoteId > 0) 
                ? "/modules/crm/quote_edit.php?id=" . $quoteId 
                : "/modules/crm/quote_create.php?opportunity_id=" . $opportunityId;
            ?>
            <a href="<?php echo $backUrl; ?>" class="btn btn-outline">Volver a Modificar</a>
            
            <form action="/modules/crm/quote_store.php" method="POST" style="margin:0; display:inline-block;">
                <input type="hidden" name="opportunity_id" value="<?php echo $opportunityId; ?>">
                <input type="hidden" name="customer_id" value="<?php echo $customerId; ?>">
                <input type="hidden" name="quote_id" value="<?php echo $quoteId; ?>">
                <input type="hidden" name="status" value="<?php echo safe_text($status); ?>"> <input type="hidden" name="notes" value="<?php echo safe_text($notes); ?>">
                <input type="hidden" name="discount_percent" value="<?php echo $discountPercent; ?>">
                
                <?php foreach ($validItems as $idx => $vItem): ?>
                    <input type="hidden" name="items[<?php echo $idx; ?>][product_id]" value="<?php echo safe_text($vItem['product_id']); ?>">
                    <input type="hidden" name="items[<?php echo $idx; ?>][name]" value="<?php echo safe_text($vItem['name']); ?>">
                    <input type="hidden" name="items[<?php echo $idx; ?>][sku]" value="<?php echo safe_text($vItem['sku']); ?>">
                    <input type="hidden" name="items[<?php echo $idx; ?>][description]" value="<?php echo safe_text($vItem['description']); ?>">
                    <input type="hidden" name="items[<?php echo $idx; ?>][quantity]" value="<?php echo safe_text(format_quantity($vItem['quantity'])); ?>">
                    <input type="hidden" name="items[<?php echo $idx; ?>][unit]" value="<?php echo safe_text($vItem['unit'] ?? 'unidad'); ?>">
                    <input type="hidden" name="items[<?php echo $idx; ?>][price_unit]" value="<?php echo (float)$vItem['price_unit']; ?>">
                <?php endforeach; ?>

                <button type="submit" class="btn btn-primary">Confirmar y Generar Cotización</button>
            </form>
        </div>
    </header>

    <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"><?php echo $quoteId > 0 ? 'MÓDULO EDICIÓN' : 'MÓDULO BORRADOR'; ?></div>
            </div>
        </header>

        <table class="info-table">
            <tr>
                <td class="bg-label">Señor(es)</td>
                <td style="width: 35%;"><strong><?php echo safe_text($meta['customer_name']); ?></strong></td>
                <td class="bg-label">Fecha</td>
                <td style="width: 35%;"><?php echo date('d-m-Y'); ?></td>
            </tr>
            <tr>
                <td class="bg-label">R.U.T.</td>
                <td><?php echo safe_text($meta['customer_tax_id'] ?: '—'); ?></td>
                <td class="bg-label">Email Cliente</td>
                <td><?php echo safe_text($meta['email'] ?: '—'); ?></td>
            </tr>
            <tr>
                <td class="bg-label">Teléfono</td>
                <td><?php echo safe_text($meta['phone'] ?: '—'); ?></td>
                <td class="bg-label">Vendedor</td>
                <td><?php echo safe_text($meta['owner_name'] ?: 'Sistema'); ?></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;
                foreach ($validItems as $vItem): 
                    $rowCount++;
                ?>
                    <tr>
                        <td class="font-mono sku-cell"><?php echo safe_text($vItem['sku']); ?></td>
                        <td>
                            <div class="item-name"><?php echo safe_text($vItem['name']); ?></div>
                            <?php if (!empty($vItem['description'])): ?>
                                <div class="item-desc">
                                    <?php echo nl2br(safe_text($vItem['description'])); ?>
                                </div>
                            <?php endif; ?>
                        </td>
                        <td class="text-center"><?php echo safe_text(format_quantity($vItem['quantity'])); ?></td>
                        <td class="text-center"><?php echo safe_text($vItem['unit'] ?? 'unidad'); ?></td>
                        <td class="text-right"><?php echo clp($vItem['price_unit']); ?></td>
                        <td class="text-center status-afecto">SI</td>
                        <td class="text-right font-medium"><?php echo clp($vItem['total_item']); ?></td>
                    </tr>
                <?php 
                endforeach; 

                // Relleno estructural si la vista previa cuenta con menos de 5 ítems
                $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" style="display: flex; flex-direction: column; gap: 20px; margin-top: 20px;">
            
            <div style="display: flex; gap: 30px; align-items: stretch; width: 100%;">
                <div style="width: 58%; display: flex; flex-direction: column;">
                    <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>
                </div>

                <div class="totals-box" style="width: 42%;">
                    <div class="totals-table-wrapper">
                        <table>
                            <tr>
                                <td>Subtotal Bruto:</td>
                                <td class="text-right"><?php echo clp($subtotal); ?></td>
                            </tr>
                            <?php if ($discountAmount > 0): ?>
                                <tr class="text-danger font-medium">
                                    <td>Descuento (<?php echo $discountPercent; ?>%):</td>
                                    <td class="text-right">- <?php echo clp($discountAmount); ?></td>
                                </tr>
                            <?php endif; ?>
                            <tr class="font-bold">
                                <td>Monto Neto:</td>
                                <td class="text-right"><?php echo clp($netWithDiscount); ?></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($iva); ?></td>
                            </tr>
                            <tr class="grand-total">
                                <td>Total General:</td>
                                <td class="text-right"><?php echo clp($totalGeneral); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <?php if (!empty($notes)): ?>
                <div style="width: 100%; display: flex; flex-direction: column;">
                    <h4 class="section-subtitle">Condiciones comerciales</h4>
                    <div class="payment-details-box" style="white-space: pre-line; flex: none !important; min-height: auto !important; padding: 12px 14px;">
                        <?php echo safe_text($notes); ?>
                    </div>
                </div>
            <?php endif; ?>

        </div>
    </div>
</body>
</html>