<?php
/**
 * ASISMA CRM - Vista pública de cotizaciones de SERVICIO (documento premium)
 * Port 1:1 de asisma_ops/public/ver_cotizacion.php, parametrizado por la
 * configuración del servicio ($servicio). Con la semilla de Control Farma el
 * resultado es el mismo documento del OPS.
 * Recibe: $cotiz (Cotizacion::getByHash) y $servicio (Servicio::getDetalleCompleto).
 */

// ── Snapshot: plan cotizado + productos adicionales ─────────────────────────
$items = json_decode($cotiz['productos_json'], true);
if (!is_array($items)) $items = array();
$itemPlan = null;
$productosAdicionales = array();
foreach ($items as $item) {
    if (isset($item['clase']) && $item['clase'] === 'servicio_plan') {
        $itemPlan = $item;
    } else {
        $productosAdicionales[] = $item;
    }
}

// ── Configuración del servicio (defaults = Control Farma) ───────────────────
// La identidad corporativa (logo, colores, transferencia) y las condiciones
// vienen de la MARCA del servicio; se superponen a la fila del servicio.
$cfg = is_array($servicio) ? $servicio : array();
if (!empty($cfg['marca_id'])) {
    $marcaBrand = IdentidadHelper::brandingDeMarca($cfg['marca_id']);
    $cfg = array_merge($cfg, $marcaBrand['branding']);
    if (!empty($marcaBrand['condiciones'])) {
        $cfg['condiciones_json'] = json_encode($marcaBrand['condiciones'], JSON_UNESCAPED_UNICODE);
    }
}
$colorPrimario   = !empty($cfg['color_primario']) ? $cfg['color_primario'] : '#4a038d';
$colorSecundario = !empty($cfg['color_secundario']) ? $cfg['color_secundario'] : '#7c3aed';
$logoUrl         = !empty($cfg['logo_ruta']) ? APP_URL . '/public/' . ltrim($cfg['logo_ruta'], '/') : '';
$nombreServicio  = !empty($cfg['nombre']) ? $cfg['nombre'] : (isset($itemPlan['servicio_nombre']) ? $itemPlan['servicio_nombre'] : 'ASISMA');
$eslogan         = !empty($cfg['eslogan']) ? $cfg['eslogan'] : '';
$rotuloCliente   = !empty($cfg['rotulo_cliente']) ? $cfg['rotulo_cliente'] : 'usted';
$ciudadFirma     = !empty($cfg['ciudad_firma']) ? $cfg['ciudad_firma'] : 'Concepción';
$fraseDestacada  = !empty($cfg['frase_destacada']) ? $cfg['frase_destacada'] : '';
$tituloBonos     = !empty($cfg['titulo_bonos']) ? $cfg['titulo_bonos'] : 'Bonos exclusivos por compras antes de 48 horas.';
$telefonoContacto = !empty($cfg['telefono_contacto']) ? $cfg['telefono_contacto'] : '';

$parrafos = !empty($cfg['parrafos_presentacion']) ? json_decode($cfg['parrafos_presentacion'], true) : array();
if (!is_array($parrafos)) $parrafos = array();
$garantia = !empty($cfg['garantia_texto']) ? json_decode($cfg['garantia_texto'], true) : array();
if (!is_array($garantia)) $garantia = array();
$garantiaDias = isset($cfg['garantia_dias']) ? (int)$cfg['garantia_dias'] : 30;
$condiciones = !empty($cfg['condiciones_json']) ? json_decode($cfg['condiciones_json'], true) : array();
if (!is_array($condiciones)) $condiciones = array();

// Esta vista es EXCLUSIVA de Control Farma (plantilla ornamentada 'moderno').
// El resto de las cotizaciones usa el documento unificado (cotizaciones/publica).
// Por eso los bordes/curvas van fijos: es el diseño original de CF, intacto.

// ── Cálculos financieros (paridad OPS: CLP = valor * UF * 1.19) ─────────────
$uf = (float)$cotiz['valor_uf'];
$monedaPlan = $itemPlan && isset($itemPlan['moneda']) ? $itemPlan['moneda'] : 'UF';
$esUfPlan = $monedaPlan === 'UF';
$factorClp = $esUfPlan ? $uf : 1;

$setupBase = $itemPlan && $itemPlan['precio_inicial'] !== null ? (float)$itemPlan['precio_inicial'] : null;
$mensualBase = $itemPlan && $itemPlan['precio_mensual'] !== null ? (float)$itemPlan['precio_mensual'] : null;

// El descuento aplica al TOTAL inicial (plan + productos): se deriva de los
// montos GUARDADOS de la cotización (subtotal con IVA menos total), sin
// recomputarlo por línea. La fila del plan muestra su precio sin descontar.
$factorIvaDoc = 1 + ((float)$cotiz['impuesto_pct'] / 100);
$descTotalConIva = max(0, round((float)$cotiz['subtotal'] * $factorIvaDoc - (float)$cotiz['total']));

$setupClpNum   = $setupBase !== null ? round($setupBase * $factorClp * 1.19) : 0;
$setupClp      = number_format($setupClpNum, 0, ',', '.');
$mensualClp    = $mensualBase !== null ? number_format(round($mensualBase * $factorClp * 1.19), 0, ',', '.') : '';
$validez       = date('d/m/Y', strtotime($cotiz['vencimiento_at']));
$cuotas        = isset($cotiz['cuotas']) ? (int)$cotiz['cuotas'] : 1;

// Total inicial real de la cotización (plan + productos adicionales, IVA incl.)
$totalInicialNum = round((float)$cotiz['total']);
$hayProductos = !empty($productosAdicionales);

$caracts = $itemPlan && !empty($itemPlan['caracteristicas']) ? $itemPlan['caracteristicas'] : array();
if (empty($caracts)) {
    $caracts = array(
        array('titulo' => 'Módulos Administrativos', 'desc' => 'Gestión completa de finanzas y RRHH.'),
        array('titulo' => 'Boleta y Factura Electrónica', 'desc' => 'Sincronizado con SII sin demoras.')
    );
}
$bonos = $itemPlan && !empty($itemPlan['bonos']) ? $itemPlan['bonos'] : array();

// Bono de financiamiento dinámico (port de procesarBonosFinanciamiento del OPS):
// si hay cuotas, se inyecta en la posición 1 con el precio contado
if ($cuotas > 1 && $totalInicialNum > 0) {
    $bonoFinanciamiento = array(
        'titulo' => 'Pago inicial en ' . $cuotas . ' cuotas precio contado $' . number_format($totalInicialNum, 0, ',', '.') . '.',
        'desc'   => 'Divida su inversión inicial sin recargos. (IVA Inc.)'
    );
    array_splice($bonos, min(1, count($bonos)), 0, array($bonoFinanciamiento));
}

$nombreCliente = $cotiz['cliente_razon_social'] ? $cotiz['cliente_razon_social'] : $cotiz['cliente_contacto_nombre'];
$primerNombre = explode(' ', trim($cotiz['cliente_contacto_nombre']));
$primerNombre = ucwords(strtolower($primerNombre[0]));
$planNombre = $itemPlan ? $itemPlan['plan_nombre'] : '';
$pdfNoDisponible = isset($_GET['pdf_no_disponible']);
?>
<!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 htmlspecialchars($nombreServicio); ?> - <?php echo htmlspecialchars($nombreCliente); ?></title>
    <link
        href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,400&display=swap"
        rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'brand-purple': '<?php echo htmlspecialchars($colorPrimario); ?>',
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Open Sans', sans-serif;
            background-color: #f8fafc;
        }

        h1, h2, h3, h4, h5, h6, strong, .font-bold, .font-black {
            font-family: 'Open Sans', sans-serif;
            font-weight: 700 !important;
        }

        p, span, li, div {
            font-family: 'Open Sans', sans-serif;
            font-weight: 400;
        }

        .glass {
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border: 1px solid rgba(255, 255, 255, 0.4);
        }

        .premium-gradient {
            background: linear-gradient(135deg, <?php echo htmlspecialchars($colorPrimario); ?> 0%, <?php echo htmlspecialchars($colorSecundario); ?> 100%);
        }

        .card-shadow {
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.08);
        }

        .animate-reveal {
            opacity: 1;
            animation: reveal 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;
        }

        @keyframes reveal {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .delay-1 { animation-delay: 0.1s; }
        .delay-2 { animation-delay: 0.2s; }
        .delay-3 { animation-delay: 0.3s; }

        .hover-lift { transition: transform 0.2s ease-out; }
        .hover-lift:hover { transform: translateY(-4px); }

        @media print {
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                color-adjust: exact !important;
            }

            .no-print { display: none !important; }

            .animate-reveal, [class*="delay-"], .opacity-0 {
                opacity: 1 !important;
                visibility: visible !important;
                animation: none !important;
                transform: none !important;
                transition: none !important;
            }

            .grid-cols-12 {
                display: grid !important;
                grid-template-columns: repeat(12, minmax(0, 1fr)) !important;
            }
            .lg\:col-span-8 { grid-column: span 8 / span 8 !important; }
            .lg\:col-span-4 { grid-column: span 4 / span 4 !important; }

            .premium-gradient {
                background: <?php echo htmlspecialchars($colorPrimario); ?> !important;
                background: linear-gradient(145deg, #1e0b36 0%, <?php echo htmlspecialchars($colorPrimario); ?> 40%, <?php echo htmlspecialchars($colorSecundario); ?> 100%) !important;
            }

            main {
                margin-top: -15px !important;
                padding-top: 0 !important;
                position: relative !important;
                z-index: 50 !important;
            }

            .glass {
                backdrop-filter: none !important;
                background: rgba(255, 255, 255, 1) !important;
                border: 1px solid #f1f5f9 !important;
                box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1) !important;
            }

            header .bg-white\/10 {
                background-color: rgba(255, 255, 255, 0.2) !important;
                border-color: rgba(255, 255, 255, 0.3) !important;
                backdrop-filter: none !important;
            }

            header p.opacity-90 { opacity: 1 !important; color: #f1f5f9 !important; }

            body { background: white !important; }

            aside > div, section, header {
                page-break-inside: avoid !important;
                break-inside: avoid !important;
            }

            .card-shadow { box-shadow: none !important; border: 1px solid #f1f5f9 !important; }

            .print-check-fix { display: none !important; }

            aside>div, section, .feature-item, .price-card {
                page-break-inside: avoid !important;
                break-inside: avoid !important;
            }

            header {
                min-height: 180px !important;
                display: block !important;
                padding-bottom: 20px !important;
                padding-top: 60px !important;
                position: relative !important;
                z-index: 1 !important;
            }

            .glass { padding: 40px !important; border-radius: 3rem !important; }

            section.datos-transferencia { padding: 20px !important; margin-top: 0 !important; }
            section.datos-transferencia .w-20.h-20 { width: 40px !important; height: 40px !important; }
            section.datos-transferencia .w-10.h-10 { width: 25px !important; height: 25px !important; }
            section.datos-transferencia h4 { font-size: 1.2rem !important; margin-bottom: 5px !important; }
            section.datos-transferencia .grid { gap: 8px !important; }
            section.datos-transferencia .p-4 { padding: 8px 12px !important; }

            .garantia-wrap {
                transform: scale(0.9);
                transform-origin: top center;
                margin-top: 0px !important;
                margin-bottom: -20px !important;
            }

            header p { color: #ffffff !important; opacity: 1 !important; font-weight: 500 !important; }

            header img {
                height: 60px !important;
                margin: 0 auto 10px auto !important;
                display: block !important;
                filter: brightness(0) invert(1) !important;
            }

            .shadow-2xl, .shadow-xl { box-shadow: none !important; }
        }
    </style>
</head>

<body class="text-slate-800 antialiased">

    <!-- Hero Header -->
    <header
        class="premium-gradient min-h-[320px] md:min-h-[400px] w-full relative overflow-hidden pt-8 md:pt-20 pb-32 md:pb-40">
        <!-- Decoración de fondo -->
        <div class="absolute inset-0 opacity-10">
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" class="w-full h-full text-white">
                <circle cx="10" cy="10" r="30" fill="currentColor" />
                <circle cx="90" cy="80" r="40" fill="currentColor" />
            </svg>
        </div>

        <div
            class="max-w-6xl mx-auto px-6 relative z-10 flex flex-col md:flex-row items-center justify-between gap-8 h-full">
            <!-- Logo a la izquierda -->
            <div class="animate-reveal">
                <?php if ($logoUrl): ?>
                <img src="<?php echo htmlspecialchars($logoUrl); ?>" alt="<?php echo htmlspecialchars($nombreServicio); ?> Logo"
                    class="h-16 md:h-20 filter brightness-0 invert">
                <?php else: ?>
                <span class="text-white text-2xl font-black tracking-tight"><?php echo htmlspecialchars($nombreServicio); ?></span>
                <?php endif; ?>
            </div>

            <!-- Título y Eslogan Centrado -->
            <div class="flex-1 text-center animate-reveal delay-1">
                <div
                    class="inline-block px-6 py-2 md:px-8 md:py-3 bg-white/10 text-white rounded-full text-sm md:text-xl font-bold uppercase tracking-[0.3em] mb-4 md:mb-8 backdrop-blur-xl border border-white/20 shadow-2xl whitespace-nowrap">
                    Cotización
                </div>
                <?php if ($eslogan): ?>
                <p
                    class="text-white text-base md:text-xl font-light opacity-90 max-w-2xl mx-auto leading-relaxed italic">
                    <?php echo htmlspecialchars($eslogan); ?>
                </p>
                <?php endif; ?>
            </div>

            <div class="hidden md:block w-[150px]"></div>
        </div>
    </header>

    <main class="max-w-6xl mx-auto px-4 -mt-24 md:-mt-32 pb-24 relative z-20 print:static print:mt-0 print:pt-4">
        <!-- Saludo y Narrativa Formal -->
        <div
            class="glass rounded-[2.5rem] md:rounded-[4rem] card-shadow p-6 md:p-14 mb-8 animate-reveal delay-1 relative">
            <div class="absolute top-6 right-6 md:top-12 md:right-14 text-right">
                <?php
                $meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
                $fecha_es = $ciudadFirma . ", " . date('d') . " de " . $meses[date('n') - 1] . " " . date('Y');
                ?>
                <h2 class="text-brand-purple font-bold uppercase tracking-widest text-[9px] md:text-[10px] mb-2">
                    <?php echo strtoupper($fecha_es); ?>
                </h2>
            </div>

            <!-- Saludo Principal -->
            <div class="mb-6 pt-12 md:pt-4">
                <p class="text-2xl md:text-5xl font-extrabold text-brand-purple tracking-tight mb-2">
                    Hola <?php echo htmlspecialchars($primerNombre); ?>,
                </p>
                <p class="text-brand-purple/70 font-bold text-xl">Presente.</p>
            </div>

            <?php if (!empty($parrafos)):
                // Dos columnas como el OPS: primera mitad izquierda, resto derecha
                $mitad = (int)ceil(count($parrafos) / 2);
                $columnaIzq = array_slice($parrafos, 0, $mitad);
                $columnaDer = array_slice($parrafos, $mitad);
            ?>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 md:gap-10 mt-6 pt-6 border-t border-slate-100/50">
                <div class="space-y-4 md:space-y-6 text-slate-600 leading-relaxed text-xs md:text-base">
                    <?php foreach ($columnaIzq as $parrafo): ?>
                    <p><?php echo $parrafo; // texto configurado por la matriz (permite <b>) ?></p>
                    <?php endforeach; ?>
                </div>
                <div class="space-y-6 text-slate-600 leading-relaxed text-sm md:text-base">
                    <?php foreach ($columnaDer as $parrafo): ?>
                    <p><?php echo $parrafo; ?></p>
                    <?php endforeach; ?>
                    <?php if ($fraseDestacada): ?>
                    <div
                        class="bg-indigo-50/50 p-6 rounded-[2rem] border border-indigo-100 italic text-indigo-900 font-medium">
                        "<?php echo htmlspecialchars($fraseDestacada); ?>"
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Info Card -->
        <div class="mb-8">
            <div
                class="glass rounded-[2.5rem] md:rounded-[3rem] card-shadow p-6 md:p-12 animate-reveal delay-2 print:static print:break-inside-auto">
                <div
                    class="flex flex-col md:flex-row justify-between items-start md:items-center border-b border-slate-100 pb-6 md:pb-8 mb-6 md:mb-8 gap-4 md:gap-6">
                    <div>
                        <h2
                            class="text-brand-purple font-bold mb-1 md:mb-2 uppercase tracking-widest text-[9px] md:text-[10px]">
                            Cotización para <?php echo htmlspecialchars($rotuloCliente); ?>:</h2>
                        <h3 class="text-xl md:text-3xl font-black text-brand-purple tracking-tight leading-tight">
                            <?php echo htmlspecialchars($nombreCliente); ?>
                        </h3>
                    </div>
                    <div
                        class="bg-purple-50 border border-purple-100 p-4 rounded-3xl text-center min-w-[140px] shadow-sm">
                        <p class="text-[9px] text-brand-purple/50 font-bold uppercase tracking-wider mb-1">Válida hasta</p>
                        <p class="text-lg font-black text-brand-purple"><?php echo $validez; ?></p>
                    </div>
                </div>

                <!-- Features Section -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div>
                        <h4 class="text-brand-purple font-bold mb-6 flex items-center text-lg">
                            <span
                                class="w-10 h-10 rounded-2xl bg-brand-purple text-white flex items-center justify-center mr-4 shadow-lg shadow-brand-purple/20">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"
                                        d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                                </svg>
                            </span>
                            <?php echo htmlspecialchars($planNombre); ?>
                        </h4>
                        <ul class="space-y-3">
                            <?php foreach ($caracts as $idx => $feat): ?>
                                <li class="flex items-center group animate-reveal"
                                    style="animation-delay: <?php echo 0.3 + ($idx * 0.1); ?>s">
                                    <div
                                        class="shrink-0 w-6 h-6 flex items-center justify-center mr-3 transition-transform group-hover:scale-110">
                                        <span class="text-lg">✅</span>
                                    </div>
                                    <div>
                                        <p class="font-bold text-slate-800 text-sm leading-tight">
                                            <?php echo htmlspecialchars($feat['titulo']); ?>
                                        </p>
                                        <?php if (!empty($feat['desc'])): ?>
                                            <p class="text-slate-500 text-[10px] leading-tight mt-0">
                                                <?php echo htmlspecialchars($feat['desc']); ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>

                    <div class="space-y-6">

                        <?php if (!empty($bonos)): ?>
                        <div class="bg-gradient-to-br from-brand-purple via-purple-800 to-purple-600 rounded-[2rem] p-6 shadow-xl shadow-brand-purple/10 text-white" style="background-image: linear-gradient(to bottom right, <?php echo htmlspecialchars($colorPrimario); ?>, <?php echo htmlspecialchars($colorSecundario); ?>);">
                            <h5
                                class="text-indigo-200 font-black text-xs tracking-widest mb-6 flex items-center">
                                <span class="mr-2">🎁</span> <?php echo htmlspecialchars($tituloBonos); ?>
                            </h5>
                            <div class="space-y-4">
                                <?php foreach ($bonos as $b): ?>
                                    <div class="relative pl-8 group">
                                        <span
                                            class="absolute left-0 top-0.5 text-indigo-300 transition-transform group-hover:scale-125">✨</span>
                                        <p class="text-xs font-black text-white mb-1">
                                            <?php echo htmlspecialchars($b['titulo']); ?>
                                        </p>
                                        <p class="text-[10px] text-indigo-100/70 leading-relaxed italic">
                                            <?php
                                            // Prioriza la descripción manual; si no, infiere por
                                            // palabras clave (misma lógica del OPS)
                                            $desc_manual = (isset($b['desc']) && !empty($b['desc'])) ? htmlspecialchars($b['desc']) : '';
                                            $desc_auto = "";
                                            if (stripos($b['titulo'], 'IA') !== false)
                                                $desc_auto = "Dashboard con Inteligencia Artificial y Análisis Estratégico avanzado.";
                                            elseif (stripos($b['titulo'], 'Yapp') !== false)
                                                $desc_auto = "Integración directa con Yapp para seguros complementarios.";
                                            elseif (stripos($b['titulo'], 'ISP') !== false)
                                                $desc_auto = "Listado de precios y consultor según exigencias ISP.";
                                            elseif (stripos($b['titulo'], 'Soporte') !== false)
                                                $desc_auto = "Reuniones 1 a 1 para optimizar tus procesos.";

                                            if (!empty($desc_manual)) {
                                                echo $desc_manual;
                                            } else {
                                                echo !empty($desc_auto) ? $desc_auto : 'Beneficio exclusivo para decisiones rápidas.';
                                            }
                                            ?>
                                        </p>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (!empty($garantia['cita'])): ?>
                        <style>
  @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;0,900;1,700&family=Inter:wght@400;500;600;700&display=swap');

  .garantia-wrap {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2rem 1rem;
  }

  .garantia-card {
    width: 340px;
    background: linear-gradient(145deg, #1a0f00, #2d1a00, #1a0f00);
    border-radius: 24px;
    border: 3px solid #c8920a;
    position: relative;
    overflow: hidden;
    box-shadow:
      0 0 0 1px #7a5500,
      inset 0 1px 0 rgba(255,210,80,0.2),
      inset 0 -1px 0 rgba(0,0,0,0.5);
    padding: 0;
  }

  .card-inner-border {
    margin: 6px;
    border-radius: 19px;
    border: 1.5px solid #a07010;
    padding: 24px 22px 20px;
    position: relative;
  }

  .sunburst {
    position: absolute;
    top: -60px;
    left: 50%;
    transform: translateX(-50%);
    width: 280px;
    height: 280px;
    opacity: 0.07;
    pointer-events: none;
  }

  .top-label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 14px;
  }

  .top-line {
    flex: 1;
    height: 1px;
    background: linear-gradient(to right, transparent, #c8920a, transparent);
  }

  .top-label-text {
    font-family: 'Inter', sans-serif;
    font-size: 9px;
    font-weight: 700;
    letter-spacing: 0.25em;
    color: #e8b030;
    text-transform: uppercase;
  }

  .stars-row {
    display: flex;
    gap: 3px;
    justify-content: center;
    margin-bottom: 12px;
  }

  .star {
    width: 8px;
    height: 8px;
    background: #c8920a;
    clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
  }

  .dias-badge {
    background: linear-gradient(180deg, #f5c84a 0%, #c8920a 40%, #a07010 70%, #c8920a 100%);
    border-radius: 10px;
    padding: 10px 16px 8px;
    text-align: center;
    margin-bottom: 14px;
    border: 1px solid #7a5500;
    box-shadow: inset 0 1px 0 rgba(255,240,140,0.4), inset 0 -2px 4px rgba(0,0,0,0.3);
    position: relative;
  }

  .dias-number {
    font-family: 'Playfair Display', serif;
    font-size: 52px;
    font-weight: 900;
    color: #1a0f00;
    line-height: 1;
    letter-spacing: -2px;
    text-shadow: 0 1px 0 rgba(255,220,80,0.4);
  }

  .dias-text {
    font-family: 'Inter', sans-serif;
    font-size: 13px;
    font-weight: 700;
    color: #1a0f00;
    letter-spacing: 0.2em;
    text-transform: uppercase;
    margin-top: -2px;
    text-shadow: 0 1px 0 rgba(255,220,80,0.3);
  }

  .bottom-label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 14px;
  }

  .bottom-label-text {
    font-family: 'Inter', sans-serif;
    font-size: 8px;
    font-weight: 700;
    letter-spacing: 0.2em;
    color: #e8b030;
    text-transform: uppercase;
  }

  .quote-text {
    font-family: 'Playfair Display', serif;
    font-size: 14px;
    font-style: italic;
    color: #f5e6b8;
    line-height: 1.55;
    text-align: center;
    margin-bottom: 14px;
    padding: 0 4px;
  }

  .highlight-gold {
    color: #f5c84a;
    font-weight: 700;
    text-decoration: underline;
    text-decoration-color: #c8920a;
    text-underline-offset: 3px;
  }

  .divider {
    height: 1px;
    background: linear-gradient(to right, transparent, #c8920a, transparent);
    margin: 12px 0;
  }

  .fine-print {
    font-family: 'Inter', sans-serif;
    font-size: 9px;
    color: #b08030;
    line-height: 1.7;
    text-align: center;
    letter-spacing: 0.03em;
  }
</style>

<div class="garantia-wrap">
  <div class="garantia-card">
    <div class="card-inner-border">

      <svg class="sunburst" viewBox="0 0 280 280" xmlns="http://www.w3.org/2000/svg">
        <g transform="translate(140,140)">
          <line x1="0" y1="-130" x2="0" y2="130" stroke="#f5c84a" stroke-width="1.5"/>
          <line x1="-130" y1="0" x2="130" y2="0" stroke="#f5c84a" stroke-width="1.5"/>
          <line x1="-92" y1="-92" x2="92" y2="92" stroke="#f5c84a" stroke-width="1.5"/>
          <line x1="92" y1="-92" x2="-92" y2="92" stroke="#f5c84a" stroke-width="1.5"/>
          <line x1="-50" y1="-120" x2="50" y2="120" stroke="#f5c84a" stroke-width="1"/>
          <line x1="50" y1="-120" x2="-50" y2="120" stroke="#f5c84a" stroke-width="1"/>
          <line x1="-120" y1="-50" x2="120" y2="50" stroke="#f5c84a" stroke-width="1"/>
          <line x1="120" y1="-50" x2="-120" y2="50" stroke="#f5c84a" stroke-width="1"/>
        </g>
      </svg>

      <div class="top-label">
        <div class="top-line"></div>
        <span class="top-label-text">Garantía de Satisfacción</span>
        <div class="top-line"></div>
      </div>

      <div class="stars-row">
        <div class="star"></div><div class="star"></div><div class="star"></div>
        <div class="star"></div><div class="star"></div><div class="star"></div>
        <div class="star"></div>
      </div>

      <div class="dias-badge">
        <div class="dias-number"><?php echo $garantiaDias; ?></div>
        <div class="dias-text">Días</div>
      </div>

      <div class="bottom-label">
        <div class="top-line"></div>
        <span class="bottom-label-text">Incondicional</span>
        <div class="top-line"></div>
      </div>

      <p class="quote-text">
        "<?php echo htmlspecialchars($garantia['cita']); ?>"
      </p>

      <div class="divider"></div>

      <div class="fine-print">
        <?php foreach ((isset($garantia['condiciones']) && is_array($garantia['condiciones'])) ? $garantia['condiciones'] : array() as $lineaGarantia): ?>
        <p><?php echo htmlspecialchars($lineaGarantia); ?></p>
        <?php endforeach; ?>
      </div>

    </div>
  </div>
</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Price Full Width Section (Formal) -->
        <section class="animate-reveal delay-3 mb-8 w-full print:break-inside-avoid">
            <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-8 md:p-12 relative overflow-hidden">
                <h4 class="text-slate-800 font-bold uppercase tracking-widest text-sm mb-6 pb-4 border-b border-slate-200">
                    Resumen de Inversión
                </h4>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-12 relative z-10">

                    <!-- Detalle Financiero -->
                    <div>
                        <table class="w-full text-sm text-slate-600 tabla-sin-item">
                            <tbody>
                                <?php if ($setupBase !== null): ?>
                                <!-- Pago Inicial -->
                                <tr class="border-b border-slate-100">
                                    <td class="py-4 align-top">
                                        <span class="font-bold text-slate-800 block">Licencia de uso e Implementación</span>
                                        <span class="text-[10px] text-slate-400 block mt-1">
                                            <?php echo $esUfPlan
                                                ? 'Equivalente a ' . number_format($setupBase, (floor($setupBase) == $setupBase ? 0 : 1), ',', '.') . ' UF'
                                                : 'Valor neto $' . number_format($setupBase, 0, ',', '.'); ?>
                                        </span>
                                        <span class="text-[10px] text-slate-400 block italic">Pago tras 48 hrs o antes</span>
                                    </td>
                                    <td class="py-4 text-right align-top">
                                        <span class="text-lg font-black text-slate-800">
                                            $<?php echo $setupClp; ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endif; ?>

                                <!-- Fila Descuento Explicito (sobre el TOTAL inicial) -->
                                <?php if ($descTotalConIva > 0): ?>
                                <tr class="border-b border-slate-100 bg-emerald-50/40">
                                    <td class="py-2 px-3 text-emerald-700 text-[11px] font-bold uppercase tracking-wide">
                                        Bonificación Especial Aplicada
                                    </td>
                                    <td class="py-2 px-3 text-right text-emerald-700 text-[11px] font-bold">
                                        -$<?php echo number_format($descTotalConIva, 0, ',', '.'); ?>
                                    </td>
                                </tr>
                                <?php endif; ?>

                                <?php if ($mensualBase !== null): ?>
                                <!-- Mensualidad -->
                                <tr class="border-b border-slate-100">
                                    <td class="py-4 align-top">
                                        <span class="font-bold text-slate-800 block">Mensualidad <?php echo htmlspecialchars($planNombre); ?></span>
                                        <span class="text-[10px] text-slate-400 block mt-1">Aprox $<?php echo $mensualClp; ?> CLP</span>
                                    </td>
                                    <td class="py-4 text-right align-top">
                                        <span class="text-lg font-black text-slate-800">
                                            <?php echo $esUfPlan
                                                ? number_format($mensualBase, (floor($mensualBase) == $mensualBase ? 0 : 1), ',', '.') . ' UF'
                                                : '$' . number_format($mensualBase, 0, ',', '.'); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endif; ?>

                                <?php if ($hayProductos): ?>
                                <!-- Productos adicionales incluidos en la cotización -->
                                <?php foreach ($productosAdicionales as $prod): ?>
                                <tr class="border-b border-slate-100">
                                    <td class="py-3 align-top">
                                        <span class="font-bold text-slate-800 block text-xs"><?php echo htmlspecialchars($prod['nombre']); ?></span>
                                        <span class="text-[10px] text-slate-400 block mt-0.5">Cantidad: <?php echo (int)$prod['cantidad']; ?></span>
                                    </td>
                                    <td class="py-3 text-right align-top">
                                        <span class="text-sm font-black text-slate-800">$<?php echo number_format((float)$prod['total'], 0, ',', '.'); ?></span>
                                        <span class="text-[9px] text-slate-400 block">+ IVA</span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                            <tfoot>
                                <?php if ($cuotas > 1):
                                    $montoCuotaClp = number_format(round($totalInicialNum / $cuotas), 0, ',', '.');
                                ?>
                                <tr>
                                    <td class="py-4 font-bold text-slate-800 text-[11px] align-middle">
                                        Inversión Total <?php echo $hayProductos ? 'Inicial' : 'Licencia'; ?>
                                    </td>
                                    <td class="py-4 text-right align-middle">
                                        <span class="text-base font-bold text-slate-800">$<?php echo number_format($totalInicialNum, 0, ',', '.'); ?></span>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="py-6 font-bold text-slate-800 uppercase tracking-widest text-xs align-middle border-t-2 border-slate-100">
                                        Valor Primera Cuota <br/><span class="text-[9px] text-slate-400 normal-case tracking-normal font-normal">(1 de <?php echo $cuotas; ?> cuotas - IVA Incl.)</span>
                                    </td>
                                    <td class="py-6 text-right align-middle border-t-2 border-slate-100">
                                        <span class="text-2xl font-black text-brand-purple">$<?php echo $montoCuotaClp; ?></span>
                                    </td>
                                </tr>
                                <?php else: ?>
                                <tr>
                                    <td class="py-6 font-bold text-slate-800 uppercase tracking-widest text-xs align-middle">
                                        Total Inicial a Transferir <br/><span class="text-[9px] text-slate-400 normal-case tracking-normal font-normal">(IVA Incluido)</span>
                                    </td>
                                    <td class="py-6 text-right align-middle">
                                        <span class="text-2xl font-black text-brand-purple">$<?php echo number_format($totalInicialNum, 0, ',', '.'); ?></span>
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Condiciones Comerciales -->
                    <?php if (!empty($condiciones)): ?>
                    <div class="bg-slate-50 p-6 rounded-lg border border-slate-200">
                        <h5 class="text-[11px] font-bold text-slate-800 uppercase tracking-widest mb-5">Condiciones Comerciales</h5>
                        <ul class="space-y-4 text-sm text-slate-600">
                            <?php foreach ($condiciones as $cond): ?>
                            <li class="flex items-start">
                                <span class="text-brand-purple font-bold mr-3 mt-0.5">•</span>
                                <div>
                                    <strong class="block text-slate-800 font-semibold text-[11px] uppercase tracking-wider mb-1"><?php echo htmlspecialchars($cond['titulo']); ?></strong>
                                    <span class="text-xs"><?php echo htmlspecialchars(str_replace('{vencimiento}', $validez, $cond['texto'])); ?></span>
                                </div>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>

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

        <!-- Formal Actions -->
        <div class="flex flex-col md:flex-row justify-between items-center gap-6 mb-8 no-print animate-reveal delay-3 border-t border-slate-200 pt-8 px-4 md:px-0">
            <?php $esPreview = isset($cotiz['hash']) && $cotiz['hash'] === 'preview'; ?>
            <?php if ($esPreview): ?>
            <span><!-- Vista previa: sin descarga de PDF (no hay cotización real) --></span>
            <?php elseif ($pdfNoDisponible): ?>
            <button onclick="window.print()"
                class="bg-brand-purple text-white px-6 py-3 rounded text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-3 w-full md:w-auto">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4H7v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
                </svg>
                Imprimir / Guardar como PDF
            </button>
            <?php else: ?>
            <a href="<?php echo APP_URL; ?>/cotizaciones/publica?h=<?php echo htmlspecialchars($cotiz['hash']); ?>&pdf=1"
                class="bg-brand-purple text-white px-6 py-3 rounded text-sm font-semibold hover:opacity-90 transition-opacity flex items-center justify-center gap-3 w-full md:w-auto">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a2 2 0 002 2h12a2 2 0 002-2v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                </svg>
                Descargar Cotización en PDF
            </a>
            <?php endif; ?>

            <?php if ($telefonoContacto): ?>
            <div class="text-slate-600 text-sm flex items-center gap-2">
                <span class="font-medium">¿Consultas adicionales? Comuníquese al</span>
                <a href="tel:<?php echo htmlspecialchars(preg_replace('/\s+/', '', $telefonoContacto)); ?>" class="text-brand-purple font-bold hover:underline"><?php echo htmlspecialchars($telefonoContacto); ?></a>
            </div>
            <?php endif; ?>
        </div>

        <?php if (!empty($cotiz['notas'])): ?>
            <section class="glass rounded-[3rem] p-8 mb-8 animate-reveal delay-3">
                <h4 class="text-slate-900 font-black text-sm uppercase tracking-[0.2em] mb-4 flex items-center italic">
                    <span class="w-2 h-6 bg-brand-purple mr-4 rounded-full"></span> Términos y Notas
                </h4>
                <div class="text-slate-600 text-sm leading-relaxed whitespace-pre-wrap pl-6">
                    <?php echo htmlspecialchars($cotiz['notas']); ?>
                </div>
            </section>
        <?php endif; ?>

        <?php if (!empty($cfg['transferencia_titular'])): ?>
        <!-- Bank Details Section -->
        <section
            class="glass datos-transferencia rounded-[2rem] md:rounded-[3rem] p-6 md:p-12 print:p-6 mb-8 print:mb-2 animate-reveal delay-3 overflow-hidden relative border-2 border-purple-100 shadow-xl shadow-brand-purple/5">
            <div class="absolute top-0 right-0 p-4 no-print">
                <div
                    class="bg-brand-purple text-white text-[8px] md:text-[10px] font-bold px-3 py-1 rounded-full uppercase tracking-wider animate-pulse">
                    Acción Requerida
                </div>
            </div>

            <div class="flex flex-col lg:flex-row print:flex-row items-center print:items-start gap-6 md:gap-10 print:gap-6">
                <div
                    class="shrink-0 w-20 h-20 print:w-16 print:h-16 bg-purple-50 rounded-3xl flex items-center justify-center text-brand-purple shadow-inner">
                    <svg class="w-10 h-10 print:w-8 print:h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                            d="M3 10h18M3 7l9-4 9 4M4 10h16v11H4V10z"></path>
                    </svg>
                </div>

                <div class="flex-1 text-center lg:text-left print:text-left">
                    <h4 class="text-2xl print:text-xl font-black text-slate-900 tracking-tight mb-2">Datos de Transferencia</h4>
                    <p class="text-slate-500 text-sm print:text-xs mb-6 print:mb-4 leading-relaxed max-w-md">Para iniciar el proceso de
                        implementación, por favor realice la transferencia y envíe el comprobante por WhatsApp o Email.
                    </p>

                    <div class="grid grid-cols-1 md:grid-cols-2 print:grid-cols-2 gap-4 text-left">
                        <div class="bg-slate-50/80 p-4 print:p-3 rounded-2xl border border-slate-100">
                            <p class="text-[9px] uppercase font-bold text-brand-purple/50 tracking-widest mb-1">Nombre /
                                Titular</p>
                            <p class="text-sm font-bold text-slate-800"><?php echo htmlspecialchars($cfg['transferencia_titular']); ?></p>
                        </div>
                        <div class="bg-slate-50/80 p-4 rounded-2xl border border-slate-100">
                            <p class="text-[9px] uppercase font-bold text-brand-purple/50 tracking-widest mb-1">RUT</p>
                            <p class="text-sm font-bold text-slate-800"><?php echo htmlspecialchars($cfg['transferencia_rut']); ?></p>
                        </div>
                        <div class="bg-slate-50/80 p-4 rounded-2xl border border-slate-100">
                            <p class="text-[9px] uppercase font-bold text-indigo-400 tracking-widest mb-1">Banco / Tipo
                                Cuenta</p>
                            <p class="text-sm font-bold text-slate-800"><?php echo htmlspecialchars($cfg['transferencia_banco'] . ' / ' . $cfg['transferencia_tipo_cuenta']); ?></p>
                        </div>
                        <div class="bg-slate-50/80 p-4 rounded-2xl border border-slate-100">
                            <p class="text-[9px] uppercase font-bold text-indigo-400 tracking-widest mb-1">Nº Cuenta /
                                Email</p>
                            <p class="text-sm font-bold text-slate-800"><?php echo htmlspecialchars($cfg['transferencia_numero_cuenta'] . ' / ' . $cfg['transferencia_correo']); ?></p>
                        </div>
                    </div>
                </div>

                <div class="shrink-0 space-y-3 w-full lg:w-auto no-print">
                    <button onclick="copiarDatosTransferencia()"
                        class="w-full lg:w-48 bg-brand-purple hover:opacity-90 text-white font-black py-4 px-6 rounded-2xl shadow-lg shadow-brand-purple/20 transition-all active:scale-95 flex items-center justify-center gap-3 group">
                        <svg class="w-5 h-5 transition-transform group-hover:rotate-12" fill="none"
                            stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3">
                            </path>
                        </svg>
                        <span>COPIAR DATOS</span>
                    </button>
                    <div id="copy-success"
                        class="bg-emerald-100 text-emerald-700 text-xs font-bold py-2 px-4 rounded-xl text-center opacity-0 transition-opacity duration-300">
                        ¡Copiado con éxito!
                    </div>
                </div>
            </div>

            <textarea id="datos-transferencia-text" class="hidden"><?php echo htmlspecialchars(strtoupper($cfg['transferencia_titular'])) . "\n"
                . htmlspecialchars(preg_replace('/[^0-9kK\-]/', '', $cfg['transferencia_rut'])) . "\n"
                . htmlspecialchars($cfg['transferencia_banco']) . "\n"
                . htmlspecialchars($cfg['transferencia_tipo_cuenta']) . "\n"
                . htmlspecialchars(preg_replace('/\s+/', '', $cfg['transferencia_numero_cuenta'])) . "\n"
                . htmlspecialchars($cfg['transferencia_correo']); ?></textarea>
        </section>

        <script>
            function copiarDatosTransferencia() {
                var copyText = document.getElementById("datos-transferencia-text");
                copyText.style.display = 'block';
                copyText.select();
                copyText.setSelectionRange(0, 99999);

                try {
                    document.execCommand("copy");
                    var successMsg = document.getElementById("copy-success");
                    successMsg.style.opacity = "1";
                    setTimeout(function () {
                        successMsg.style.opacity = "0";
                    }, 2000);
                } catch (err) {
                    console.error('Error al copiar: ', err);
                }

                copyText.style.display = 'none';
            }
        </script>
        <?php endif; ?>

        <!-- Footer -->
        <div class="mt-8 print:mt-0 text-center animate-reveal delay-3 print:break-inside-avoid">
            <img src="<?php echo APP_URL; ?>/public/assets/img/logo_asisma.png" alt="ASISMA Logo"
                class="h-10 mx-auto mb-1 opacity-30 grayscale hover:grayscale-0 transition-all duration-300">
            <p class="text-slate-400 text-[9px] font-bold uppercase tracking-[0.3em]">
                &copy; Asisma <?php echo date('Y'); ?> - Tecnología que impulsa negocios
            </p>
        </div>
    </main>

</body>

</html>
