<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Precios y Márgenes', 'precios');
?>

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

<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); }
    
    input[type="number"]::-webkit-inner-spin-button,
    input[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }

    .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;
    }

    .pr-search { position: relative; width: 100%; }
    .pr-search i { position: absolute; left: 1.25rem; top: 50%; transform: translateY(-50%); color: var(--text-secondary); font-size: 1.1rem; }
    .pr-search input { 
        width: 100%; 
        padding: 1rem 1.25rem 1rem 3rem !important; 
        border-radius: var(--radius) !important; 
        border: 1px solid var(--border) !important; 
        background: var(--surface-elevated) !important; 
        font-size: 1rem; 
        color: var(--text-primary) !important; 
        box-sizing: border-box; 
        transition: all var(--transition) !important;
    }
    .pr-search input:focus { 
        outline: none; 
        border-color: var(--accent-color) !important; 
        box-shadow: var(--focus-ring) !important;
        background: var(--surface) !important;
    }

    .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: 1rem 1.25rem !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: 1rem 1.25rem !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 {
        transition: background-color var(--transition);
    }
    .pr-table-wrap tr:hover { 
        background: var(--surface-hover) !important; 
    }

    .pres-chip { 
        transition: all 0.15s ease;
        background: rgba(210, 200, 221, 0.04);
        border: 1px solid rgba(210, 200, 221, 0.12);
        color: var(--text-primary);
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.35rem 0.65rem;
        border-radius: 8px;
    }
    .pres-chip:hover { 
        background: rgba(210, 200, 221, 0.12) !important;
        border-color: rgba(210, 200, 221, 0.25) !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); 
    }

    .lab-dropdown-item {
        padding: 0.75rem 1rem;
        cursor: pointer;
        font-size: 0.875rem;
        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="precios-root" class="pr-container" style="opacity: 0; transition: opacity 0.25s ease;">

    <!-- HEADER -->
    <header class="pr-header">
        <div>
            <h1><i class="bi bi-tag-fill text-accent"></i> Precios y Márgenes</h1>
            <p style="color: var(--text-secondary); font-size: 0.875rem; margin: 0.25rem 0 0 0;">Define márgenes por presentación y por laboratorio basados en el Costo Promedio Ponderado (CPP)</p>
        </div>
        <button onclick="recalculateAll()" class="btn-pr btn-pr-primary" style="background:#f59e0b !important; color:#020e17 !important;">
            <i class="bi bi-calculator"></i> Recalcular Todo
        </button>
    </header>

    <!-- MARGEN POR LABORATORIO -->
    <section class="pr-card">
        <h5 style="font-family: 'League Spartan', sans-serif !important; font-size: 1.15rem; color: var(--text-primary); margin: 0 0 1rem 0; display: flex; align-items: center; gap: 0.5rem;">
            <i class="bi bi-building" style="color: var(--accent-color);"></i> Margen por Laboratorio
        </h5>
        <div style="display: flex; flex-wrap: wrap; align-items: flex-end; gap: 1rem;">
            <div style="flex: 1; min-width: 250px; display: flex; flex-direction: column; gap: 0.5rem;">
                <label style="font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; letter-spacing: 0.05em;">Buscar Laboratorio</label>
                <div style="position: relative;">
                    <input type="text" id="labSearchInput" autocomplete="off" placeholder="Escriba nombre del laboratorio..."
                        class="pr-input" style="width: 100%; padding: 0.65rem 0.85rem; border-radius: var(--radius-sm); box-sizing: border-box;">
                    <div id="labDropdown" 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>
            <div style="width: 120px; display: flex; flex-direction: column; gap: 0.5rem;">
                <label style="font-size: 0.75rem; font-weight: 600; color: var(--text-light); text-transform: uppercase; letter-spacing: 0.05em;">Margen %</label>
                <input type="number" id="labMargenInput" step="0.1" value="30" min="0" max="999"
                    class="pr-input font-bold text-center" style="width: 100%; padding: 0.65rem 0.85rem; border-radius: var(--radius-sm); box-sizing: border-box;">
            </div>
            <button onclick="applyLabMargin()" id="btnApplyLab" disabled
                class="btn-pr btn-pr-secondary" style="opacity: 0.5; height: 38px; box-sizing: border-box;">
                <i class="bi bi-check2-all"></i> Aplicar a Lab
            </button>
        </div>
        <div id="labSelectedInfo" class="hidden" style="margin-top: 0.75rem; font-size: 0.75rem; color: #f59e0b; font-weight: bold;"></div>
    </section>

    <!-- PRODUCT LIST CARD -->
    <div class="pr-card" style="padding: 0; overflow: hidden;">
        <div style="padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--border); background: rgba(2, 14, 23, 0.4);">
            <div class="pr-search">
                <i class="bi bi-search"></i>
                <input type="text" id="productSearch" autocomplete="off" placeholder="Buscar producto por código, nombre, laboratorio o genérico...">
            </div>
        </div>

        <div id="loader" class="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 productos...</p>
        </div>

        <div id="emptyState" class="hidden empty-state">
            <i class="bi bi-tags"></i>
            <p>No se encontraron productos</p>
        </div>

        <div id="tableContainer" class="hidden pr-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th style="width: 28%;">Producto / Laboratorio</th>
                        <th style="width: 12%; text-align: center;">CPP Base</th>
                        <th>Presentaciones (Costo → Margen % → Precio Venta)</th>
                        <th style="width: 12%; text-align: center;">Desc. Colab.</th>
                        <th style="width: 15%; text-align: center;">Acción</th>
                    </tr>
                </thead>
                <tbody id="productsBody"></tbody>
            </table>
        </div>
    </div>
</div>

<script>
    let searchTimeout = null;
    let selectedLab = null;

    // ========== PRODUCTS ==========
    async function loadProducts(query = '') {
        document.getElementById('loader').classList.remove('hidden');
        document.getElementById('tableContainer').classList.add('hidden');
        document.getElementById('emptyState').classList.add('hidden');

        try {
            const res = await fetch(`api/precios/get_productos.php?query=${encodeURIComponent(query)}&limit=30`);
            const data = await res.json();
            document.getElementById('loader').classList.add('hidden');

            if (data.success && data.data && data.data.length > 0) {
                renderProducts(data.data);
                document.getElementById('tableContainer').classList.remove('hidden');
            } else {
                document.getElementById('emptyState').classList.remove('hidden');
            }
        } catch (e) {
            console.error(e);
            document.getElementById('loader').innerHTML = '<p style="color: var(--danger); font-weight: bold; padding: 2rem;">Error al cargar datos</p>';
        }
    }

    function renderProducts(products) {
        const body = document.getElementById('productsBody');
        body.innerHTML = products.map((p, idx) => {
            const cpp = parseFloat(p.cpp_unidad) || 0;
            let presHtml = '';

            if (p.presentaciones && p.presentaciones.length > 0) {
                presHtml = p.presentaciones.map((pr, pi) => {
                    const costoPres = parseFloat(pr.costo_presentacion) || 0;
                    const precioActual = parseFloat(pr.precio_venta) || 0;
                    let margen = parseFloat(pr.margen_ganancia) || 30;
                    if (costoPres > 0 && precioActual > 0 && !pr.margen_ganancia) {
                        margen = ((precioActual / costoPres) - 1) * 100;
                    }

                    return `
                        <div class="pres-chip">
                            <span class="px-2 py-0.5 rounded font-extrabold text-[10px] uppercase tracking-wider min-w-[55px] text-center" style="background: rgba(210,200,221,0.1); color: var(--text-light); border: 1px solid rgba(210,200,221,0.2);">${pr.presentacion_nombre}</span>
                            <span style="color: var(--text-secondary); font-size: 10px; width: 64px; text-align: right;">C: Q${costoPres.toFixed(2)}</span>
                            <input type="number" step="0.1" value="${margen.toFixed(1)}" 
                                data-pid="${p.id}" data-presid="${pr.presentacion_id}" data-factor="${pr.factor_conversion}" data-cpp="${cpp}"
                                oninput="updatePriceCalc(this)"
                                class="margin-input pr-input w-16 p-1 rounded-lg text-center text-white font-bold text-xs">
                            <span style="color: var(--text-muted); font-size: 10px;">%→</span>
                            <span class="price-display font-bold text-emerald-400 text-xs min-w-[60px]">Q${precioActual.toFixed(2)}</span>
                        </div>`;
                }).join('');
            } else {
                presHtml = '<span style="color: var(--text-muted); font-style: italic; font-size: 10px;">Sin presentaciones configuradas</span>';
            }

            return `
                <tr data-product-id="${p.id}">
                    <td>
                        <div style="font-weight: bold; color: var(--text-primary); font-size: 0.875rem;">${escapeHtml(p.NombreComercial)}</div>
                        <div style="color: var(--accent-color); font-size: 10px; font-weight: 600; margin-top: 0.15rem;">${escapeHtml(p.laboratorio || 'Sin Lab')}</div>
                        <div style="color: var(--text-muted); font-size: 9px; margin-top: 0.15rem;">INT: ${p.CodigoInterno || 'N/A'} | ${p.NombreGenerico || ''}</div>
                        <div class="flex gap-2 mt-1.5">
                            ${p.es_exento_iva == 1 ? '<span class="px-1.5 py-0.5 rounded bg-amber-950/30 text-amber-400 text-[8px] font-bold border border-amber-800/30">EXENTO IVA</span>' : ''}
                        </div>
                    </td>
                    <td style="text-align: center;">
                        <div style="font-weight: bold; color: var(--text-primary); font-size: 0.875rem;">Q${cpp.toFixed(4)}</div>
                        <div style="color: var(--text-muted); font-size: 9px; margin-top: 0.25rem;">por unidad base</div>
                    </td>
                    <td>
                        <div style="display: flex; flex-direction: column; gap: 0.5rem;">${presHtml}</div>
                    </td>
                    <td style="text-align: center;">
                        <input type="number" step="0.5" value="0" min="0" max="100"
                            class="desc-colab-input pr-input w-16 p-1 rounded-lg text-center text-white font-bold text-xs">
                        <div style="color: var(--text-muted); font-size: 9px; margin-top: 0.25rem;">% descuento</div>
                    </td>
                    <td style="text-align: center;">
                        <button onclick="saveProduct(${p.id}, this)" class="btn-pr btn-pr-primary btn-pr-sm">
                            <i class="bi bi-floppy"></i> Guardar
                        </button>
                    </td>
                </tr>`;
        }).join('');
    }

    function updatePriceCalc(input) {
        const margin = parseFloat(input.value) || 0;
        const factor = parseFloat(input.dataset.factor) || 1;
        const cpp = parseFloat(input.dataset.cpp) || 0;
        const priceEl = input.parentElement.querySelector('.price-display');
        const newPrice = (cpp * factor) * (1 + (margin / 100));
        priceEl.textContent = `Q${newPrice.toFixed(2)}`;
    }

    async function saveProduct(productId, btn) {
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<span class="inline-block animate-spin rounded-full h-3 w-3 border-2 border-white border-t-transparent"></span>';
        btn.disabled = true;

        const row = btn.closest('tr');
        const marginInputs = row.querySelectorAll('.margin-input');
        const descInput = row.querySelector('.desc-colab-input');

        const presentaciones = [];
        marginInputs.forEach(input => {
            const margin = parseFloat(input.value) || 0;
            const factor = parseFloat(input.dataset.factor) || 1;
            const cpp = parseFloat(input.dataset.cpp) || 0;
            const precio = (cpp * factor) * (1 + (margin / 100));

            presentaciones.push({
                presentacion_id: input.dataset.presid,
                margen: margin,
                precio_venta: Math.round(precio * 100) / 100
            });
        });

        try {
            const res = await fetch('api/precios/save_margins.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    producto_id: productId,
                    presentaciones: presentaciones,
                    descuento_colaborador: parseFloat(descInput.value) || 0
                })
            });
            const data = await res.json();
            if (data.success) {
                Swal.fire({ icon:'success', title:'Guardado', text: data.message, toast:true, position:'top-end', showConfirmButton:false, timer:2000, 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' });
        } finally {
            btn.innerHTML = originalHtml;
            btn.disabled = false;
        }
    }

    async function recalculateAll() {
        const result = await Swal.fire({
            title: '¿Recalcular todos los precios?',
            text: 'Esto aplicará los márgenes actuales de cada producto sobre su CPP.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Sí, recalcular',
            cancelButtonText: 'Cancelar',
            background: '#052137',
            color: '#ffffff'
        });
        if (!result.isConfirmed) return;

        try {
            const res = await fetch('api/recalc_precios.php');
            const data = await res.json();
            Swal.fire({ icon: data.success ? 'success' : 'error', title: data.message, background:'#052137', color:'#ffffff' });
            loadProducts(document.getElementById('productSearch').value);
        } catch(e) {
            Swal.fire({ icon:'error', title:'Error', text: 'Fallo de red', background:'#052137', color:'#ffffff' });
        }
    }

    // ========== LABORATORIO MARGIN ==========
    let labTimeout;
    document.getElementById('labSearchInput').addEventListener('input', (e) => {
        clearTimeout(labTimeout);
        const q = e.target.value.trim();
        labTimeout = setTimeout(() => searchLabs(q), 300);
    });

    async function searchLabs(q) {
        try {
            const res = await fetch(`api/precios/get_laboratorios.php?q=${encodeURIComponent(q)}`);
            const data = await res.json();
            const dropdown = document.getElementById('labDropdown');

            if (data.success && data.data.length > 0) {
                dropdown.innerHTML = data.data.map(l => `
                    <div onclick="selectLab('${escapeHtml(l.laboratorio).replace(/'/g, "\\'")}', ${l.total})" 
                        class="lab-dropdown-item">
                        <span class="font-semibold">${escapeHtml(l.laboratorio)}</span>
                        <span style="color: var(--text-secondary); font-size: 10px; font-weight: bold;">${l.total} productos</span>
                    </div>
                `).join('');
                dropdown.classList.remove('hidden');
            } else {
                dropdown.classList.add('hidden');
            }
        } catch(e) { console.error(e); }
    }

    function selectLab(name, total) {
        selectedLab = name;
        document.getElementById('labSearchInput').value = name;
        document.getElementById('labDropdown').classList.add('hidden');
        document.getElementById('labSelectedInfo').classList.remove('hidden');
        document.getElementById('labSelectedInfo').innerHTML = `<i class="bi bi-check-circle-fill me-1"></i> Laboratorio seleccionado: <strong>${name}</strong> (${total} productos)`;

        const btn = document.getElementById('btnApplyLab');
        btn.disabled = false;
        btn.className = 'btn-pr btn-pr-primary';
        btn.style.opacity = '1';
    }

    async function applyLabMargin() {
        if (!selectedLab) return;
        const margen = parseFloat(document.getElementById('labMargenInput').value) || 0;

        const result = await Swal.fire({
            title: `¿Aplicar margen de ${margen}%?`,
            text: `Se actualizarán TODOS los precios del laboratorio "${selectedLab}" basándose en su CPP.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, aplicar',
            cancelButtonText: 'Cancelar',
            background: '#052137',
            color: '#ffffff'
        });
        if (!result.isConfirmed) return;

        try {
            const res = await fetch('api/precios/save_margen_laboratorio.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ laboratorio: selectedLab, margen: margen })
            });
            const data = await res.json();
            Swal.fire({ icon: data.success ? 'success' : 'error', title: data.message, background:'#052137', color:'#ffffff' });
            if (data.success) loadProducts(document.getElementById('productSearch').value);
        } catch(e) {
            Swal.fire({ icon:'error', title:'Error', text: 'Fallo de red', background:'#052137', color:'#ffffff' });
        }
    }

    // Hide dropdown on outside click
    document.addEventListener('click', (e) => {
        if (!e.target.closest('#labSearchInput') && !e.target.closest('#labDropdown')) {
            document.getElementById('labDropdown').classList.add('hidden');
        }
    });

    // ========== SEARCH ==========
    document.getElementById('productSearch').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => loadProducts(e.target.value.trim()), 400);
    });

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Init
    loadProducts();

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

<?php renderFooter(); ?>

