<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Medicamentos Controlados', 'controlados');
?>
<style>
::-webkit-scrollbar{width:8px;height:8px}
::-webkit-scrollbar-track{background:#1e293b;border-radius:8px}
::-webkit-scrollbar-thumb{background:#475569;border-radius:8px}
.glass{background:var(--card-bg);backdrop-filter:blur(20px);border:1px solid var(--border-color)}
.tab-btn{transition:all .2s}
.tab-btn.active{background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff}
</style>

<div class="relative z-10 max-w-[98%] mx-auto px-4 py-6" style="background:var(--card-bg); color:var(--text-primary); border-radius:var(--radius-lg); min-height:80vh;">
    <header class="glass rounded-2xl p-6 mb-6 flex justify-between items-center flex-wrap gap-3">
        <div><h1 class="text-2xl font-bold text-white m-0">Medicamentos Controlados</h1><p class="text-slate-400 text-sm mt-1 m-0">Gesti&oacute;n de productos que requieren receta y registro de dispensaciones</p></div>
    </header>

    <!-- Tabs -->
    <div class="flex gap-2 mb-6 flex-wrap" id="tabContainer">
        <button class="tab-btn active" data-tab="productos"><i class="bi bi-capsule me-1"></i> Productos Controlados</button>
        <button class="tab-btn" data-tab="dispensaciones"><i class="bi bi-clock-history me-1"></i> Dispensaciones</button>
    </div>

    <!-- TAB: Productos Controlados -->
    <div class="tab-content" id="tab-productos">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6" id="resumenCards"></div>
        <div class="glass rounded-2xl overflow-hidden">
            <div class="p-4 border-b border-slate-800 flex justify-between items-center flex-wrap gap-2">
                <div class="flex gap-2">
                    <input type="text" id="cpSearch" placeholder="Buscar producto..." class="bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500" oninput="filtrarProductos()">
                    <select id="cpFiltro" class="bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-indigo-500" onchange="cargarProductos(this.value)">
                        <option value="todos">Todos</option><option value="controlado">Controlados</option><option value="no_controlado">No Controlados</option>
                    </select>
                </div>
                <span class="text-xs text-slate-500" id="cpCount"></span>
            </div>
            <div id="loaderP" class="hidden text-center py-8"><div class="inline-block animate-spin rounded-full h-6 w-6 border-4 border-slate-700 border-t-indigo-500"></div></div>
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse text-xs">
                    <thead><tr class="bg-slate-800 border-b border-slate-700 text-slate-400 font-bold uppercase">
                        <th class="p-3">Producto</th><th class="p-3">C&oacute;digo</th><th class="p-3">Laboratorio</th><th class="p-3 text-center">Controlado</th><th class="p-3 text-center">Dispensaciones</th><th class="p-3 text-center">Acci&oacute;n</th>
                    </tr></thead>
                    <tbody id="productosBody" class="divide-y divide-slate-800/60"></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- TAB: Dispensaciones -->
    <div class="tab-content hidden" id="tab-dispensaciones">
        <section class="glass rounded-2xl p-5 mb-6">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Desde</label><input type="date" id="dfDesde" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-indigo-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Hasta</label><input type="date" id="dfHasta" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-indigo-500"></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Producto</label><select id="dfProducto" class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-indigo-500"><option value="">Todos</option></select></div>
                <div><label class="text-xs font-bold text-slate-400 uppercase mb-1.5 block">Buscar</label><input type="text" id="dfSearch" placeholder="Paciente, m&eacute;dico..." class="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-indigo-500"></div>
                <div class="flex gap-2"><button onclick="cargarDispensaciones()" class="py-2.5 px-4 font-bold text-white rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 border-0 cursor-pointer text-xs"><i class="bi bi-search"></i></button><button onclick="exportDispPDF()" class="py-2.5 px-3 font-bold text-rose-300 rounded-xl bg-rose-950/30 hover:bg-rose-950/50 border-0 cursor-pointer text-xs" title="PDF"><i class="bi bi-filetype-pdf"></i></button><button onclick="exportDispXLSX()" class="py-2.5 px-3 font-bold text-emerald-300 rounded-xl bg-emerald-950/30 hover:bg-emerald-950/50 border-0 cursor-pointer text-xs" title="Excel"><i class="bi bi-file-earmark-excel"></i></button></div>
            </div>
        </section>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6" id="dispCards"></div>
        <div class="glass rounded-2xl overflow-hidden">
            <div id="loaderD" class="hidden text-center py-8"><div class="inline-block animate-spin rounded-full h-6 w-6 border-4 border-slate-700 border-t-indigo-500"></div></div>
            <div id="dispTableContainer" class="overflow-x-auto">
                <table class="w-full text-left border-collapse text-xs">
                    <thead><tr class="bg-slate-800 border-b border-slate-700 text-slate-400 font-bold uppercase">
                        <th class="p-3">Fecha</th><th class="p-3">Producto</th><th class="p-3">Paciente</th><th class="p-3">M&eacute;dico</th><th class="p-3">Colegiado</th><th class="p-3">DPI</th><th class="p-3 text-center">Estado</th>
                    </tr></thead>
                    <tbody id="dispBody" class="divide-y divide-slate-800/60"></tbody>
                </table>
            </div>
            <div id="dispEmpty" class="hidden text-center py-8"><p class="text-slate-500 text-sm">No hay dispensaciones registradas</p></div>
        </div>
    </div>
</div>

<script src="assets/js/tailwind.js"></script>
<script>tailwind.config={corePlugins:{preflight:false},theme:{extend:{fontFamily:{sans:['Inter','system-ui','sans-serif']}}}}</script>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<script src="assets/js/sweetalert2.min.js"></script>
<script src="assets/js/jspdf.umd.min.js"></script>
<script src="assets/js/jspdf.plugin.autotable.min.js"></script>
<script src="assets/js/xlsx.full.min.js"></script>

<script>
let productosData = [];

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

// Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.tab-content').forEach(tc => tc.classList.add('hidden'));
        document.getElementById('tab-' + btn.dataset.tab).classList.remove('hidden');
        if (btn.dataset.tab === 'productos') cargarProductos();
        if (btn.dataset.tab === 'dispensaciones') cargarDispensaciones();
    });
});

// ====== PRODUCTOS ======
async function cargarProductos(filtro) {
    lP(true);
    try {
        const f = filtro || document.getElementById('cpFiltro').value;
        const res = await fetch('api/controlados/productos.php?filtro='+f);
        const d = await res.json();
        lP(false);
        if (!d.success) return;
        productosData = d.data.productos;
        const ctl = productosData.filter(p => p.receta_controlada==1 || p.receta_requerida==1 || p.requiere_receta==1).length;
        document.getElementById('resumenCards').innerHTML = `
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Productos Controlados</div><div class="text-xl font-extrabold text-indigo-400 mt-1">${ctl}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Dispensaciones</div><div class="text-xl font-extrabold text-amber-400 mt-1">${d.data.total_dispensaciones}</div></div>
            <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Total Productos</div><div class="text-xl font-extrabold text-slate-300 mt-1">${d.data.productos.length}</div></div>
        `;
        filtrarProductos();
    } catch(e) { lP(false); console.error(e); }
}

function lP(s) { document.getElementById('loaderP').classList.toggle('hidden', !s); }

function filtrarProductos() {
    const q = document.getElementById('cpSearch').value.toLowerCase();
    let filtered = productosData;
    if (q) filtered = filtered.filter(p => (p.producto||'').toLowerCase().includes(q) || (p.codigo||'').toLowerCase().includes(q));

    document.getElementById('cpCount').textContent = filtered.length + ' producto(s)';
    document.getElementById('productosBody').innerHTML = filtered.map(p => `
        <tr class="hover:bg-slate-800/5 transition-colors">
            <td class="p-3 text-white font-medium">${esc(p.producto)}</td>
            <td class="p-3 text-slate-400">${esc(p.codigo)}</td>
            <td class="p-3 text-slate-400">${esc(p.laboratorio||'-')}</td>
            <td class="p-3 text-center">${(p.receta_controlada==1||p.receta_requerida==1||p.requiere_receta==1)?'<span class="px-2 py-0.5 rounded bg-rose-950/30 text-rose-400 text-[9px] font-bold">CONTROLADO</span>':'<span class="px-2 py-0.5 rounded bg-slate-700 text-slate-400 text-[9px] font-bold">LIBRE</span>'}</td>
            <td class="p-3 text-center text-slate-400">${p.dispensaciones}</td>
            <td class="p-3 text-center">
                <button onclick="toggleControlado(${p.id},${p.receta_controlada})" class="${p.receta_controlada==1?'text-amber-400 hover:text-amber-300 bg-amber-950/20 hover:bg-amber-950/40':'text-emerald-400 hover:text-emerald-300 bg-emerald-950/20 hover:bg-emerald-950/40'} p-2 rounded-lg border-0 cursor-pointer text-xs" title="${p.receta_controlada==1?'Quitar controlado':'Marcar controlado'}">
                    <i class="bi ${p.receta_controlada==1?'bi-shield-slash':'bi-shield-check'}"></i>
                </button>
            </td>
        </tr>
    `).join('') || '<tr><td class="p-6 text-center text-slate-500" colspan="6">No se encontraron productos</td></tr>';
}

async function toggleControlado(id, actual) {
    const nuevo = actual ? 0 : 1;
    const accion = nuevo ? 'marcar como controlado' : 'quitar como controlado';
    const r = await Swal.fire({title: '¿' + (nuevo?'Marcar':'Quitar') + '?',text: '¿' + accion + '?',icon:'question',showCancelButton:true,confirmButtonText:'Sí',cancelButtonText:'Cancelar',background:'#1e293b',color:'#f1f5f9'});
    if (!r.isConfirmed) return;
    try {
        const res = await fetch('api/controlados/toggle.php', {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({producto_id:id, receta_controlada:nuevo})});
        const d = await res.json();
        if (d.success) { Swal.fire({icon:'success',title:d.message,toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#1e293b',color:'#f1f5f9'}); cargarProductos(); }
        else { Swal.fire({icon:'error',title:'Error',text:d.message,background:'#1e293b',color:'#f1f5f9'}); }
    } catch(e) { Swal.fire({icon:'error',title:'Error',text:'Fallo de red',background:'#1e293b',color:'#f1f5f9'}); }
}

// ====== DISPENSACIONES ======
async function cargarDispensaciones() {
    const p = new URLSearchParams();
    if (document.getElementById('dfDesde').value) p.append('fecha_desde', document.getElementById('dfDesde').value);
    if (document.getElementById('dfHasta').value) p.append('fecha_hasta', document.getElementById('dfHasta').value);
    if (document.getElementById('dfProducto').value) p.append('producto_id', document.getElementById('dfProducto').value);
    const s = document.getElementById('dfSearch').value.trim();
    if (s) p.append('search', s);
    lD(true); dTC(true); dE(true);
    try {
        const res = await fetch('api/controlados/dispensaciones.php?'+p.toString()+sucursalFilter());
        const d = await res.json();
        lD(false);
        if (d.success) {
            document.getElementById('dispCards').innerHTML = `
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Total Dispensaciones</div><div class="text-xl font-extrabold text-white mt-1">${d.data.total}</div></div>
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Con Receta</div><div class="text-xl font-extrabold text-emerald-400 mt-1">${d.data.total - d.data.omitidas}</div></div>
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">Omitidas</div><div class="text-xl font-extrabold text-rose-400 mt-1">${d.data.omitidas}</div></div>
                <div class="glass rounded-2xl p-5"><div class="text-xs font-bold text-slate-400 uppercase">% Cumplimiento</div><div class="text-xl font-extrabold text-amber-400 mt-1">${d.data.total>0?((d.data.total-d.data.omitidas)/d.data.total*100).toFixed(1):'0'}%</div></div>
            `;
            if (d.data.dispensaciones.length > 0) {
                document.getElementById('dispBody').innerHTML = d.data.dispensaciones.map(dv => `
                    <tr class="hover:bg-slate-800/5 transition-colors ${dv.fue_omitida?'opacity-60':''}">
                        <td class="p-3 text-slate-300 whitespace-nowrap">${dv.created_at.slice(0,10)}</td>
                        <td class="p-3 text-white font-medium">${esc(dv.producto)}</td>
                        <td class="p-3 text-slate-300">${dv.fue_omitida?'<span class="text-slate-500 italic">Omitido</span>':esc(dv.nombre_paciente)}</td>
                        <td class="p-3 text-slate-300">${dv.fue_omitida?'-':esc(dv.nombre_medico)}</td>
                        <td class="p-3 text-slate-400">${dv.colegiado||'-'}</td>
                        <td class="p-3 text-slate-400">${dv.dpi_paciente||'-'}</td>
                        <td class="p-3 text-center">${dv.fue_omitida?'<span class="px-2 py-0.5 rounded bg-rose-950/30 text-rose-400 text-[9px] font-bold">OMITIDA</span>':'<span class="px-2 py-0.5 rounded bg-emerald-950/30 text-emerald-400 text-[9px] font-bold">REGISTRADA</span>'}</td>
                    </tr>
                `).join('');
                dTC(false);
            } else { dE(false); }
        } else { dE(false); }
    } catch(e) { lD(false); dE(false); console.error(e); }
}

function lD(s) { document.getElementById('loaderD').classList.toggle('hidden', !s); }
function dTC(s) { document.getElementById('dispTableContainer').classList.toggle('hidden', s); }
function dE(s) { document.getElementById('dispEmpty').classList.toggle('hidden', s); }

// Export
function getDispData() {
    const rows = []; const tb = document.getElementById('dispBody')?.querySelectorAll('tr');
    if (tb) tb.forEach(tr => { const td = tr.querySelectorAll('td'); if(td.length) rows.push([td[0].textContent.trim(), td[1].textContent.trim(), td[2].textContent.trim(), td[3].textContent.trim(), td[4].textContent.trim(), td[5].textContent.trim(), td[6].textContent.trim()]); });
    return rows;
}
function exportDispPDF() {
    const d = getDispData(); const { jsPDF } = window.jspdf; const doc = new jsPDF();
    doc.setFontSize(16); doc.text('Dispensaciones - Medicamentos Controlados', 14, 20);
    doc.setFontSize(8); doc.text('Generado: '+new Date().toLocaleString('es-GT'), 14, 27);
    doc.autoTable({head:[['Fecha','Producto','Paciente','Medico','Colegiado','DPI','Estado']],body:d,startY:32,styles:{fontSize:7},headStyles:{fillColor:[99,102,241]},alternateRowStyles:{fillColor:[240,240,245]}});
    doc.save('dispensaciones_controladas.pdf');
}
function exportDispXLSX() {
    const d = getDispData(); const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([['Fecha','Producto','Paciente','Medico','Colegiado','DPI','Estado'], ...d]);
    XLSX.utils.book_append_sheet(wb, ws, 'Dispensaciones');
    XLSX.writeFile(wb, 'dispensaciones_controladas.xlsx');
}

// Init
function poblarSelectorProductos() {
    const sel = document.getElementById('dfProducto');
    sel.innerHTML = '<option value="">Todos</option>';
    productosData.forEach(p => { const o = document.createElement('option'); o.value = p.id; o.textContent = p.producto; sel.appendChild(o); });
}
async function init() {
    await cargarProductos('todos');
    poblarSelectorProductos();
}
init();
</script>
<?php renderFooter(); ?>

