<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Promociones', 'promociones');
?>
<style>
    ::-webkit-scrollbar { width: 8px; height: 8px; }
    ::-webkit-scrollbar-track { background: var(--primary-dark); border-radius: 8px; }
    ::-webkit-scrollbar-thumb { background: var(--surface-elevated); border-radius: 8px; }
    ::-webkit-scrollbar-thumb:hover { background: var(--accent-color); }

    .pr-container { max-width: 1400px; margin: 0 auto; padding: 2rem; }
    .pr-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 2rem; }
    .pr-header h1 { font-family: 'League Spartan', sans-serif; font-size: 1.85rem; font-weight: 700; color: var(--text-primary); margin: 0; display: flex; align-items: center; gap: 0.75rem; }

    .pr-card { 
        background: var(--surface) !important; 
        border: 1px solid var(--border) !important; 
        border-radius: var(--radius) !important; 
        box-shadow: var(--shadow) !important;
        margin-bottom: 1.5rem;
        padding: 1.5rem;
    }

    .pr-input {
        background: var(--surface-elevated) !important;
        border: 1px solid var(--border) !important;
        color: var(--text-primary) !important;
        font-family: 'Poppins', sans-serif;
        transition: all var(--transition) !important;
    }
    .pr-input:focus {
        outline: none;
        border-color: var(--accent-color) !important;
        background: var(--surface) !important;
        box-shadow: var(--focus-ring) !important;
    }

    .btn-pr { 
        display: inline-flex; 
        align-items: center; 
        justify-content: center; 
        gap: 0.5rem; 
        padding: 0.6rem 1.25rem; 
        font-weight: 600; 
        font-size: 0.875rem; 
        border-radius: var(--radius-sm); 
        border: none; 
        cursor: pointer; 
        transition: all var(--transition); 
        text-decoration: none; 
    }
    .btn-pr-primary { 
        background: var(--accent-color) !important; 
        color: #0B0119 !important; 
        box-shadow: var(--shadow) !important;
    }
    .btn-pr-primary:hover { 
        transform: translateY(-1px); 
        box-shadow: var(--shadow-md) !important;
        opacity: 0.9;
    }
    .btn-pr-secondary { 
        background: var(--surface) !important; 
        border: 1px solid var(--border) !important; 
        color: var(--text-primary) !important; 
    }
    .btn-pr-secondary:hover { 
        background: var(--surface-hover) !important; 
    }
    .btn-pr-sm { 
        padding: 0.4rem 0.85rem; 
        font-size: 0.75rem; 
        border-radius: var(--radius-sm); 
    }

    .promo-card {
        background: var(--surface) !important;
        border: 1px solid var(--border) !important;
        border-radius: var(--radius) !important;
        padding: 1.25rem 1.5rem;
        box-shadow: var(--shadow-sm) !important;
        transition: all var(--transition) !important;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }
    .promo-card:hover {
        box-shadow: var(--shadow-md) !important;
        transform: translateY(-4px) scale(1.008) !important;
        border-color: var(--accent-color) !important;
    }

    .badge-soft-success {
        background: rgba(34,197,94,0.1);
        color: var(--success);
        border: 1px solid rgba(34,197,94,0.2);
    }
    .badge-soft-primary {
        background: rgba(30,58,95,0.1);
        color: var(--text-light);
        border: 1px solid rgba(210, 200, 221, 0.2);
    }
    .badge-soft-info {
        background: rgba(59, 130, 246, 0.1);
        color: #60a5fa;
        border: 1px solid rgba(59, 130, 246, 0.2);
    }
    .badge-soft-muted {
        background: var(--surface-hover);
        color: var(--text-light);
        border: 1px solid var(--border);
    }
    .badge-soft-danger {
        background: rgba(239,68,68,0.1);
        color: var(--danger);
        border: 1px solid rgba(239,68,68,0.2);
    }

    /* Modals */
    .modal-overlay { 
        position: fixed; 
        inset: 0; 
        z-index: 1000; 
        background: rgba(2, 6, 17, 0.8) !important; 
        align-items: center; 
        justify-content: center; 
        animation: fadeIn var(--transition) ease-out;
        display: none;
    }
    .modal-overlay:not(.hidden) {
        display: flex;
    }
    .modal-content { 
        background: var(--surface-elevated) !important; 
        border: 1px solid var(--border) !important; 
        border-radius: var(--radius-lg) !important; 
        width: 95%; 
        max-width: 540px; 
        max-height: 90vh; 
        overflow-y: auto; 
        padding: 0 !important; 
        box-shadow: var(--shadow-xl) !important; 
    }
    .modal-header { display: flex; align-items: center; justify-content: space-between; padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--border); }
    .modal-header h3 { font-family: 'League Spartan', sans-serif; font-size: 1.35rem; font-weight: 700; margin: 0; color: var(--text-primary); }
    .modal-close { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: var(--text-light); padding: 0.25rem; line-height: 1; transition: color var(--transition); }
    .modal-close:hover { color: var(--text-primary); }

    .modal-body { padding: 1.5rem; }
    .modal-footer { display: flex; gap: 0.75rem; padding: 1.25rem 1.5rem; border-top: 1px solid var(--border); }
    .modal-footer button { flex: 1; }

    .form-group { margin-bottom: 1.25rem; display: flex; flex-direction: column; gap: 0.35rem; }
    .form-group label { font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; letter-spacing: 0.05em; display: block; }
    .form-group input, .form-group textarea, .form-group select { 
        width: 100%; 
        padding: 0.65rem 0.85rem !important; 
        border-radius: var(--radius-sm) !important; 
        border: 1px solid var(--border) !important; 
        background: var(--surface) !important; 
        color: var(--text-primary) !important; 
        font-size: 0.875rem; 
        box-sizing: border-box; 
        transition: all var(--transition) !important;
    }
    .form-group input:focus, .form-group textarea:focus, .form-group select:focus { 
        outline: none; 
        border-color: var(--accent-color) !important; 
        box-shadow: var(--focus-ring) !important;
    }
    .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }

    .pr-table-wrap { overflow-x: auto; }
    .pr-table-wrap table { width: 100%; border-collapse: collapse; }
    .pr-table-wrap th { 
        background: var(--surface-elevated) !important;
        padding: 0.75rem 1rem !important; 
        font-size: 0.75rem; 
        font-weight: 700; 
        text-transform: uppercase; 
        letter-spacing: 0.05em; 
        color: var(--text-light) !important; 
        border-bottom: 2px solid var(--border) !important; 
        text-align: left; 
    }
    .pr-table-wrap td { 
        padding: 0.75rem 1rem !important; 
        font-size: 0.875rem; 
        border-bottom: 1px solid var(--border-light) !important; 
        vertical-align: middle; 
        color: var(--text-primary) !important;
    }
    .pr-table-wrap tr:hover { 
        background: var(--surface-hover) !important; 
    }

    .lab-dropdown-item {
        padding: 0.5rem 0.75rem;
        cursor: pointer;
        font-size: 0.75rem;
        color: var(--text-primary);
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid var(--border-light);
        transition: background var(--transition);
    }
    .lab-dropdown-item:hover {
        background: var(--surface-hover);
    }

    .empty-state { text-align: center; padding: 4rem 2rem; color: var(--text-secondary); }
    .empty-state i { font-size: 3.5rem; opacity: 0.3; margin-bottom: 1rem; display: block; color: var(--accent-color); }
</style>

<div id="promociones-root" class="pr-container" style="opacity: 0; transition: opacity 0.25s ease;">
    <!-- HEADER -->
    <header class="pr-header">
        <div>
            <h1><i class="bi bi-gift-fill text-accent"></i> Promociones</h1>
            <p style="color: var(--text-secondary); font-size: 0.875rem; margin: 0.25rem 0 0 0;">Gestión de ofertas y descuentos por producto</p>
        </div>
        <button onclick="abrirModalPromo()" class="btn-pr btn-pr-primary">
            <i class="bi bi-plus-circle"></i> Nueva Promoción
        </button>
    </header>

    <!-- Filters -->
    <div class="pr-card" style="padding: 1.25rem 1.5rem; margin-bottom: 1.5rem;">
        <div style="display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
            <select id="filtroEstado" class="pr-input" style="padding: 0.5rem 1rem; border-radius: var(--radius-sm); font-size: 0.875rem;">
                <option value="">Todas las promociones</option>
                <option value="activa">Activas</option>
                <option value="programada">Programadas</option>
                <option value="vencida">Vencidas</option>
                <option value="inactiva">Inactivas</option>
            </select>
            <span style="font-size: 0.75rem; color: var(--text-secondary);" id="promoCount"></span>
        </div>
    </div>

    <!-- Promotions Grid -->
    <div id="loader" class="hidden text-center py-16">
        <div class="inline-block animate-spin rounded-full h-10 w-10 border-4 border-t-transparent mb-4" style="border-color: rgba(210,200,221,0.2); border-top-color: var(--accent-color);"></div>
        <p style="color: var(--text-secondary); font-size: 0.75rem; font-weight: bold; text-transform: uppercase; margin: 0;">Cargando promociones...</p>
    </div>
    <div id="promosGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"></div>
    <div id="emptyState" class="hidden empty-state">
        <i class="bi bi-gift"></i>
        <p>No se encontraron promociones</p>
    </div>
</div>

<!-- Modal Promocion -->
<div id="modalPromo" class="hidden modal-overlay" onclick="if(event.target===this)cerrarModalPromo()">
    <div class="modal-content" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h3 id="promoModalTitle">Nueva Promoción</h3>
            <button onclick="cerrarModalPromo()" class="modal-close">&times;</button>
        </div>
        <input type="hidden" id="promoEditId" value="">
        <div class="modal-body">
            <div class="form-group">
                <label>Nombre *</label>
                <input type="text" id="promoNombre" placeholder="Ej: Descuento Temporada">
            </div>
            <div class="form-group">
                <label>Descripción</label>
                <textarea id="promoDescripcion" rows="2" placeholder="Descripción opcional"></textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Tipo Descuento</label>
                    <select id="promoTipo">
                        <option value="porcentaje">Porcentaje (%)</option>
                        <option value="monto_fijo">Monto Fijo (Q)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Activo</label>
                    <select id="promoActivo">
                        <option value="1">Si</option>
                        <option value="0">No</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Fecha Inicio *</label>
                    <input type="date" id="promoFechaInicio">
                </div>
                <div class="form-group">
                    <label>Fecha Fin</label>
                    <input type="date" id="promoFechaFin">
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button onclick="guardarPromo()" id="btnGuardarPromo" class="btn-pr btn-pr-primary"><i class="bi bi-check2"></i> Guardar</button>
            <button onclick="cerrarModalPromo()" class="btn-pr btn-pr-secondary">Cancelar</button>
        </div>
    </div>
</div>

<!-- Modal Productos -->
<div id="modalProductos" class="hidden modal-overlay" onclick="if(event.target===this)cerrarModalProductos()">
    <div class="modal-content" style="max-width: 800px;" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h3 id="productosModalTitle">Productos en Promoción</h3>
            <button onclick="cerrarModalProductos()" class="modal-close">&times;</button>
        </div>
        <input type="hidden" id="productosPromoId" value="">
        
        <div class="modal-body">
            <!-- Add product form -->
            <div class="pr-card" style="padding: 1.25rem; margin-bottom: 1.5rem; background: var(--surface-elevated) !important;">
                <h4 style="font-family: 'League Spartan', sans-serif; font-size: 1rem; color: var(--text-primary); margin: 0 0 1rem 0;">Agregar Producto</h4>
                <div class="grid grid-cols-1 md:grid-cols-5 gap-3 items-end">
                    <div class="md:col-span-2" style="position: relative;">
                        <label style="font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; margin-bottom: 0.35rem; display: block;">Buscar Producto</label>
                        <input type="text" id="prodSearch" placeholder="Nombre o código..." class="pr-input" style="width:100%; box-sizing: border-box; padding: 0.5rem 0.75rem; border-radius: var(--radius-sm);" onkeyup="buscarProductosPromo(event)">
                        <div id="prodSearchResults" class="hidden absolute z-50 w-full mt-1 rounded-xl shadow-2xl max-h-48 overflow-y-auto" style="background: var(--surface-elevated); border: 1px solid var(--border);"></div>
                    </div>
                    <div>
                        <label style="font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; margin-bottom: 0.35rem; display: block;">Desc. %</label>
                        <input type="number" step="0.01" id="ppDescuentoPorc" placeholder="0.00" class="pr-input" style="width:100%; box-sizing: border-box; padding: 0.5rem 0.75rem; border-radius: var(--radius-sm);">
                    </div>
                    <div>
                        <label style="font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; margin-bottom: 0.35rem; display: block;">Desc. Q</label>
                        <input type="number" step="0.01" id="ppDescuentoMonto" placeholder="0.00" class="pr-input" style="width:100%; box-sizing: border-box; padding: 0.5rem 0.75rem; border-radius: var(--radius-sm);">
                    </div>
                    <div>
                        <label style="font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; margin-bottom: 0.35rem; display: block;">Precio Promo</label>
                        <div style="display: flex; gap: 0.5rem;">
                            <input type="number" step="0.01" id="ppPrecioPromo" placeholder="0.00" class="pr-input" style="width:100%; box-sizing: border-box; padding: 0.5rem 0.75rem; border-radius: var(--radius-sm);">
                            <button onclick="agregarProductoPromo()" class="btn-pr btn-pr-primary" style="padding: 0.5rem 0.75rem; border-radius: var(--radius-sm);"><i class="bi bi-plus-lg"></i></button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Products table -->
            <div id="productosList" class="pr-table-wrap">
                <p class="text-slate-500 text-center py-8 text-sm">Seleccione una promoción</p>
            </div>
        </div>
    </div>
</div>

<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<script src="assets/js/sweetalert2.min.js"></script>

<script>
    let promociones = [];

    function esc(t) { if(!t)return''; const d=document.createElement('div'); d.textContent=t; return d.innerHTML; }

    async function cargarPromociones() {
        const est = document.getElementById('filtroEstado').value;
        let url = 'api/promociones/listar.php';
        if (est === 'activa') url += '?activo=1';
        else if (est === 'inactiva') url += '?activo=0';

        l(true); pg(true); es(true);
        try {
            const res = await fetch(url); const data = await res.json();
            l(false);
            if (data.success) {
                promociones = data.data;
                document.getElementById('promoCount').textContent = data.data.length + ' promocion(es)';
                if (data.data.length === 0) { es(false); return; }

                const hoy = new Date().toISOString().slice(0,10);
                // Client-side filter for vencida/programada
                let filtered = data.data;
                if (est === 'vencida') filtered = data.data.filter(p => p.estado === 'vencida');
                else if (est === 'programada') filtered = data.data.filter(p => p.estado === 'programada');
                else if (est === 'activa') filtered = data.data.filter(p => p.estado === 'activa');
                else if (est === 'inactiva') filtered = data.data.filter(p => p.estado === 'inactiva');

                const badge = {
                    activa: 'badge-soft-success',
                    programada: 'badge-soft-info',
                    vencida: 'badge-soft-muted',
                    inactiva: 'badge-soft-danger'
                };
                const label = {activa:'Activa',programada:'Programada',vencida:'Vencida',inactiva:'Inactiva'};
                const border = {activa:'border-l-emerald-500',programada:'border-l-blue-500',vencida:'border-l-slate-600',inactiva:'border-l-rose-500'};

                document.getElementById('promosGrid').innerHTML = filtered.map(p => `
                    <div class="promo-card ${border[p.estado]||'border-l-pink-500'}" style="border-left-width: 4px !important;">
                        <div>
                            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 0.75rem;">
                                <h3 style="font-weight: bold; color: var(--text-primary); font-size: 0.95rem; margin: 0;">${esc(p.nombre)}</h3>
                                <span class="badge-premium ${badge[p.estado]}">${label[p.estado]||p.estado}</span>
                            </div>
                            ${p.descripcion?'<p style="font-size: 0.75rem; color: var(--text-secondary); margin: 0 0 0.75rem 0;">'+esc(p.descripcion)+'</p>':''}
                            <div style="display: flex; gap: 0.75rem; font-size: 10px; color: var(--text-muted); margin-bottom: 0.75rem;">
                                <span><i class="bi bi-calendar3"></i> ${p.fecha_inicio} → ${p.fecha_fin||'Sin fecha'}</span>
                                <span><i class="bi bi-box"></i> ${p.total_productos} producto(s)</span>
                            </div>
                        </div>
                        <div style="display: flex; gap: 0.5rem; margin-top: 1rem;">
                            <button onclick="abrirModalProductos(${p.id},'${esc(p.nombre)}')" class="btn-pr btn-pr-secondary btn-pr-sm" style="flex: 1;" title="Productos"><i class="bi bi-box"></i> Productos</button>
                            <button onclick="editarPromo(${p.id})" class="btn-pr btn-pr-secondary btn-pr-sm" title="Editar" style="padding: 0.4rem 0.6rem;"><i class="bi bi-pencil"></i></button>
                            <button onclick="eliminarPromo(${p.id})" class="btn-pr btn-pr-secondary btn-pr-sm" style="color: var(--danger) !important; padding: 0.4rem 0.6rem;" title="Eliminar"><i class="bi bi-trash"></i></button>
                        </div>
                    </div>
                `).join('');
                pg(false);
            } else { es(false); }
        } catch(e) { l(false); es(false); console.error(e); }
    }

    function l(s) { document.getElementById('loader').classList.toggle('hidden', !s); }
    function pg(s) { document.getElementById('promosGrid').classList.toggle('hidden', s); }
    function es(s) { document.getElementById('emptyState').classList.toggle('hidden', s); }

    // ====== CRUD PROMO ======
    function abrirModalPromo() {
        document.getElementById('promoEditId').value = '';
        document.getElementById('promoModalTitle').textContent = 'Nueva Promoción';
        document.getElementById('promoNombre').value = '';
        document.getElementById('promoDescripcion').value = '';
        document.getElementById('promoTipo').value = 'porcentaje';
        document.getElementById('promoActivo').value = '1';
        document.getElementById('promoFechaInicio').value = new Date().toISOString().slice(0,10);
        document.getElementById('promoFechaFin').value = '';
        document.getElementById('modalPromo').classList.remove('hidden');
        setTimeout(()=>document.getElementById('promoNombre').focus(),100);
    }

    function cerrarModalPromo() { document.getElementById('modalPromo').classList.add('hidden'); }

    function editarPromo(id) {
        const p = promociones.find(x => x.id === id);
        if (!p) return;
        document.getElementById('promoEditId').value = p.id;
        document.getElementById('promoModalTitle').textContent = 'Editar Promoción';
        document.getElementById('promoNombre').value = p.nombre;
        document.getElementById('promoDescripcion').value = p.descripcion||'';
        document.getElementById('promoTipo').value = p.tipo_descuento;
        document.getElementById('promoActivo').value = p.activo;
        document.getElementById('promoFechaInicio').value = p.fecha_inicio;
        document.getElementById('promoFechaFin').value = p.fecha_fin||'';
        document.getElementById('modalPromo').classList.remove('hidden');
    }

    async function guardarPromo() {
        const id = document.getElementById('promoEditId').value;
        const nombre = document.getElementById('promoNombre').value.trim();
        const descripcion = document.getElementById('promoDescripcion').value.trim()||null;
        const tipo = document.getElementById('promoTipo').value;
        const activo = parseInt(document.getElementById('promoActivo').value);
        const fi = document.getElementById('promoFechaInicio').value;
        const ff = document.getElementById('promoFechaFin').value||null;

        if (!nombre) { Swal.fire({icon:'warning',title:'Nombre requerido',background:'#052137',color:'#ffffff'}); return; }
        if (!fi) { Swal.fire({icon:'warning',title:'Fecha inicio requerida',background:'#052137',color:'#ffffff'}); return; }

        const btn = document.getElementById('btnGuardarPromo');
        btn.disabled = true; btn.innerHTML = '<span class="inline-block animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></span>';

        const body = {nombre,descripcion,tipo_descuento:tipo,fecha_inicio:fi,fecha_fin:ff,activo};
        const url = id ? 'api/promociones/actualizar.php' : 'api/promociones/crear.php';
        if (id) body.id = id;

        try {
            const res = await fetch(url, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
            const data = await res.json();
            if (data.success) { Swal.fire({icon:'success',title:id?'Actualizada':'Creada',toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#052137',color:'#ffffff'}); cerrarModalPromo(); cargarPromociones(); }
            else { Swal.fire({icon:'error',title:'Error',text:data.message,background:'#052137',color:'#ffffff'}); }
        } catch(e) { Swal.fire({icon:'error',title:'Error',text:'Fallo de red',background:'#052137',color:'#ffffff'}); }
        finally { btn.disabled = false; btn.innerHTML = '<i class="bi bi-check2"></i> Guardar'; }
    }

    async function eliminarPromo(id) {
        const r = await Swal.fire({title:'¿Eliminar promoción?',text:'Los productos asociados se eliminarán',icon:'warning',showCancelButton:true,confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar',background:'#052137',color:'#ffffff',confirmButtonColor:'#ef4444'});
        if (!r.isConfirmed) return;
        try {
            const res = await fetch('api/promociones/eliminar.php', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});
            const data = await res.json();
            if (data.success) { Swal.fire({icon:'success',title:'Eliminada',toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#052137',color:'#ffffff'}); cargarPromociones(); }
            else { Swal.fire({icon:'error',title:'Error',text:data.message,background:'#052137',color:'#ffffff'}); }
        } catch(e) { Swal.fire({icon:'error',title:'Error',text:'Fallo de red',background:'#052137',color:'#ffffff'}); }
    }

    // ====== PRODUCTOS EN PROMOCION ======
    let prodSearchTimeout = null;

    function abrirModalProductos(id, nombre) {
        document.getElementById('productosPromoId').value = id;
        document.getElementById('productosModalTitle').textContent = 'Productos - ' + nombre;
        document.getElementById('productosList').innerHTML = '<p class="text-slate-500 text-center py-8">Cargando...</p>';
        document.getElementById('modalProductos').classList.remove('hidden');
        cargarProductosPromo(id);
    }

    function cerrarModalProductos() { document.getElementById('modalProductos').classList.add('hidden'); document.getElementById('prodSearchResults').classList.add('hidden'); }

    async function cargarProductosPromo(id) {
        try {
            const res = await fetch('api/promociones/productos.php?promocion_id='+id);
            const data = await res.json();
            if (data.success) {
                if (data.data.length === 0) {
                    document.getElementById('productosList').innerHTML = '<p class="text-slate-500 text-center py-8 text-sm">No hay productos en esta promoción. Busque y agregue arriba.</p>';
                } else {
                    document.getElementById('productosList').innerHTML = `
                        <table>
                            <thead>
                                <tr>
                                    <th>Producto</th>
                                    <th>Código</th>
                                    <th style="text-align: right;">% Desc.</th>
                                    <th style="text-align: right;">Desc. Q</th>
                                    <th style="text-align: right;">Precio Promo</th>
                                    <th style="text-align: center; width: 60px;">Acción</th>
                                </tr>
                            </thead>
                            <tbody>${data.data.map(pp => `
                                <tr>
                                    <td style="font-weight: 600; color: var(--text-primary);">${esc(pp.producto)}</td>
                                    <td style="color: var(--text-secondary);">${esc(pp.codigo)}</td>
                                    <td style="text-align: right; color: var(--accent-color); font-weight: 600;">${pp.descuento_porcentaje?pp.descuento_porcentaje+'%':'-'}</td>
                                    <td style="text-align: right; color: var(--accent-color); font-weight: 600;">${pp.descuento_monto_fijo?'Q '+parseFloat(pp.descuento_monto_fijo).toFixed(2):'-'}</td>
                                    <td style="text-align: right; color: var(--success); font-weight: 700;">${pp.precio_promocional?'Q '+parseFloat(pp.precio_promocional).toFixed(2):'-'}</td>
                                    <td style="text-align: center;">
                                        <button onclick="quitarProducto(${pp.id})" class="btn-pr btn-pr-secondary btn-pr-sm" style="color: var(--danger) !important; padding: 0.35rem 0.5rem;" title="Quitar">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            `).join('')}</tbody>
                        </table>`;
                }
            }
        } catch(e) { console.error(e); }
    }

    function buscarProductosPromo(e) {
        clearTimeout(prodSearchTimeout);
        const q = e.target.value.trim();
        if (q.length < 2) { document.getElementById('prodSearchResults').classList.add('hidden'); return; }
        prodSearchTimeout = setTimeout(async () => {
            try {
                const res = await fetch('api/inventario/productos/buscar.php?query='+encodeURIComponent(q));
                const data = await res.json();
                const r = document.getElementById('prodSearchResults');
                if (data.success && data.data.products && data.data.products.length) {
                    r.innerHTML = data.data.products.slice(0,10).map(p => `
                        <div class="lab-dropdown-item" style="padding: 0.5rem 0.75rem; font-size: 0.75rem;" onclick="seleccionarProducto(${p.id},'${esc(p.NombreComercial)}','${esc(p.CodigoInterno)}')">
                            <span>${esc(p.NombreComercial)}</span>
                            <span style="color: var(--text-muted); font-weight: bold; margin-left: 0.5rem;">(${esc(p.CodigoInterno)})</span>
                        </div>
                    `).join('');
                    r.classList.remove('hidden');
                } else { r.classList.add('hidden'); }
            } catch(e) {}
        }, 300);
    }

    function seleccionarProducto(id, nombre, codigo) {
        document.getElementById('prodSearch').value = nombre + ' (' + codigo + ')';
        document.getElementById('prodSearch').dataset.productoId = id;
        document.getElementById('prodSearchResults').classList.add('hidden');
    }

    async function agregarProductoPromo() {
        const promId = parseInt(document.getElementById('productosPromoId').value);
        const prodId = parseInt(document.getElementById('prodSearch').dataset.productoId);
        if (!promId || !prodId) { Swal.fire({icon:'warning',title:'Seleccione un producto',background:'#052137',color:'#ffffff'}); return; }

        const dP = parseFloat(document.getElementById('ppDescuentoPorc').value)||null;
        const dM = parseFloat(document.getElementById('ppDescuentoMonto').value)||null;
        const pP = parseFloat(document.getElementById('ppPrecioPromo').value)||null;

        if (!dP && !dM && !pP) { Swal.fire({icon:'warning',title:'Defina descuento o precio promocional',background:'#052137',color:'#ffffff'}); return; }

        try {
            const res = await fetch('api/promociones/agregar_producto.php', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({promocion_id:promId, producto_id:prodId, descuento_porcentaje:dP, descuento_monto_fijo:dM, precio_promocional:pP})});
            const data = await res.json();
            if (data.success) {
                document.getElementById('prodSearch').value = '';
                document.getElementById('prodSearch').dataset.productoId = '';
                document.getElementById('ppDescuentoPorc').value = '';
                document.getElementById('ppDescuentoMonto').value = '';
                document.getElementById('ppPrecioPromo').value = '';
                cargarProductosPromo(promId);
                cargarPromociones();
                Swal.fire({icon:'success',title:'Producto agregado',toast:true,position:'top-end',showConfirmButton:false,timer:1500,background:'#052137',color:'#ffffff'});
            } else { Swal.fire({icon:'error',title:'Error',text:data.message,background:'#052137',color:'#ffffff'}); }
        } catch(e) { Swal.fire({icon:'error',title:'Error',text:'Fallo de red',background:'#052137',color:'#ffffff'}); }
    }

    async function quitarProducto(id) {
        const r = await Swal.fire({title:'¿Quitar producto?',icon:'question',showCancelButton:true,confirmButtonText:'Sí',cancelButtonText:'Cancelar',background:'#052137',color:'#ffffff'});
        if (!r.isConfirmed) return;
        try {
            const res = await fetch('api/promociones/quitar_producto.php', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});
            const data = await res.json();
            if (data.success) {
                cargarProductosPromo(parseInt(document.getElementById('productosPromoId').value));
                cargarPromociones();
            } else { Swal.fire({icon:'error',title:'Error',text:data.message,background:'#052137',color:'#ffffff'}); }
        } catch(e) { Swal.fire({icon:'error',title:'Error',text:'Fallo de red',background:'#052137',color:'#ffffff'}); }
    }

    document.getElementById('filtroEstado').addEventListener('change', cargarPromociones);
    cargarPromociones();

    // Smooth reveal to prevent FOUC / layout shift
    const revealRoot = () => {
        const root = document.getElementById('promociones-root');
        if (root) root.style.opacity = '1';
    };
    setTimeout(revealRoot, 50);
    window.addEventListener('load', revealRoot);
</script>
<?php renderFooter(); ?>
