<?php
require_once __DIR__ . '/../../includes/layout.php';

$pdo = getDBConnection();
$active_branch_id = (int)($_GET['sucursal_id'] ?? 0);

renderHeader('Usuarios y Sucursales', 'usuarios_sucursales');
?>

<!-- Include Scripts -->
<script src="assets/js/tailwind.js"></script>
<script>
    tailwind.config = {
        corePlugins: {
            preflight: false,
        },
        theme: {
            extend: {
                fontFamily: { sans: ['Inter', 'system-ui', 'sans-serif'] },
                keyframes: {
                    'fade-in-up': {
                        '0%': { opacity: '0', transform: 'translateY(15px)' },
                        '100%': { opacity: '1', transform: 'translateY(0)' }
                    }
                },
                animation: {
                    'fade-in-up': 'fade-in-up 0.3s ease-out'
                }
            }
        }
    }
</script>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<script src="assets/js/sweetalert2.min.js"></script>
<!-- PDF Generation Libraries -->
<script src="assets/js/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>

<style>
    /* Scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }
    ::-webkit-scrollbar-track {
        background: #1e293b;
        border-radius: 8px;
    }
    ::-webkit-scrollbar-thumb {
        background: #475569;
        border-radius: 8px;
    }
    ::-webkit-scrollbar-thumb:hover {
        background: #64748b;
    }
    /* Glass Effect */
    .glass {
        background: rgba(255, 255, 255, 0.03);
        backdrop-filter: blur(20px);
        border: 1px solid rgba(255, 255, 255, 0.08);
    }
    .user-card-premium {
        transition: all 0.2s ease;
        border: 1px solid rgba(255,255,255,0.05);
    }
    .user-card-premium.active {
        background: linear-gradient(135deg, rgba(79, 70, 229, 0.15), rgba(79, 70, 229, 0.05));
        border-color: #6366f1;
        box-shadow: 0 0 15px rgba(99, 102, 241, 0.15);
    }
    .tab-btn {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .tab-btn.active {
        background: rgba(255, 255, 255, 0.08);
        border-bottom: 2px solid #6366f1;
        color: #ffffff !important;
    }
    input[type="number"]::-webkit-inner-spin-button, 
    input[type="number"]::-webkit-outer-spin-button { 
        -webkit-appearance: none; 
        margin: 0; 
    }
</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 -->
    <header class="glass rounded-2xl p-6 mb-6 animate-fade-in-up" style="display: flex; flex-direction: row; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
        <div>
            <h1 class="text-2xl font-bold tracking-tight text-white m-0">Administración de Operaciones</h1>
            <p class="text-slate-400 text-sm mt-1 m-0">Gestión de accesos a sucursales, ingresos de mercancía y logística</p>
        </div>
        
        <!-- SUB-TAB NAVIGATION -->
        <div class="flex bg-slate-800/60 p-1 rounded-xl border border-slate-700/60">
            <button onclick="switchTab('usuarios')" id="tab-usuarios" class="tab-btn active text-slate-400 px-4 py-2 text-sm font-semibold rounded-lg border-0 bg-transparent cursor-pointer hover:text-white">
                <i class="bi bi-people-fill me-1"></i> Accesos
            </button>
            <button onclick="switchTab('distribucion')" id="tab-distribucion" class="tab-btn text-slate-400 px-4 py-2 text-sm font-semibold rounded-lg border-0 bg-transparent cursor-pointer hover:text-white">
                <i class="bi bi-box-seam me-1"></i> Distribución
            </button>
            <button onclick="switchTab('historial')" id="tab-historial" class="tab-btn text-slate-400 px-4 py-2 text-sm font-semibold rounded-lg border-0 bg-transparent cursor-pointer hover:text-white">
                <i class="bi bi-clock-history me-1"></i> Historial
            </button>
        </div>
    </header>

    <!-- CONTENT SECTIONS -->
    
    <!-- TAB 1: USUARIOS Y ACCESOS -->
    <section id="sec-usuarios" class="tab-content animate-fade-in-up">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- User Sidebar List -->
            <div class="glass rounded-2xl p-6 flex flex-col h-[65vh]">
                <h5 class="text-slate-300 font-semibold mb-4 text-base m-0 flex items-center gap-2">
                    <i class="bi bi-search text-indigo-400"></i> Buscar Usuario
                </h5>
                <input type="text" id="userSearch" placeholder="Nombre o usuario..." 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 mb-4">
                
                <div id="userList" class="flex-grow overflow-y-auto space-y-2 pr-1">
                    <div class="text-center py-12">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-slate-700 border-t-indigo-500 mb-2"></div>
                        <p class="text-slate-400 text-xs uppercase m-0">Cargando...</p>
                    </div>
                </div>
            </div>

            <!-- Branch Assignment Panel -->
            <div class="glass lg:col-span-2 rounded-2xl p-6 flex flex-col h-[65vh]">
                <div id="emptyUserState" class="flex-grow flex flex-col items-center justify-center text-slate-500">
                    <i class="bi bi-person-check text-5xl mb-3 opacity-20"></i>
                    <p class="text-lg m-0 font-medium">Selecciona un usuario para gestionar sus accesos</p>
                </div>

                <div id="assignmentPanel" class="hidden flex flex-col h-full">
                    <div class="flex justify-between items-start mb-6">
                        <div>
                            <h3 id="selectedUserName" class="text-xl font-bold text-white m-0">---</h3>
                            <p class="text-slate-400 text-xs mt-1 m-0">Define las sucursales a las que este usuario tiene permiso de ingresar ventas</p>
                        </div>
                        <button id="saveAssignmentsBtn" onclick="saveAssignments()" class="btn py-2 px-5 font-bold text-white rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 border-0 transition-all cursor-pointer">
                            <i class="bi bi-cloud-arrow-up-fill me-1"></i> Guardar Accesos
                        </button>
                    </div>

                    <div class="flex-grow overflow-y-auto pr-1">
                        <div id="branchGrid" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <!-- Injected branches -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- TAB 2: INGRESO Y DISTRIBUCION -->
    <section id="sec-distribucion" class="tab-content hidden animate-fade-in-up">
        <!-- Search Engine -->
        <div class="glass rounded-2xl p-6 mb-6">
            <h5 class="text-slate-300 font-semibold mb-3 text-base m-0 flex items-center gap-2">
                <i class="bi bi-search text-emerald-400"></i> Buscar Producto
            </h5>
            <div class="relative">
                <i class="bi bi-search absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 text-lg"></i>
                <input type="text" id="mainSearch" autocomplete="off" placeholder="Escribe el código interno, código de barra, nombre comercial o laboratorio..." 
                    class="w-full pl-12 pr-6 py-4 bg-slate-800/80 border border-slate-700/60 rounded-xl text-base text-white focus:outline-none focus:border-emerald-500 transition-all">
            </div>

            <!-- Results container -->
            <div id="searchResultsContainer" class="hidden mt-4 bg-slate-900/60 border border-slate-700/60 rounded-xl overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full text-left border-collapse text-xs">
                        <thead>
                            <tr class="bg-slate-850 border-b border-slate-700 text-slate-400 font-bold uppercase">
                                <th class="p-3">Producto / Laboratorio</th>
                                <th class="p-3 w-32">Presentación</th>
                                <th class="p-3 w-28 text-center">Total Ingreso</th>
                                <th class="p-3 w-36">Vencimiento</th>
                                <th class="p-3 w-24 text-center">Facturado</th>
                                <!-- Branch Headers will be dynamically injected here -->
                                <th class="p-3 text-center" id="searchActionHeader">Acción</th>
                            </tr>
                        </thead>
                        <tbody id="productTableBody" class="divide-y divide-slate-800/60 bg-slate-900/30">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Today's summary -->
        <div class="glass rounded-2xl p-6">
            <h5 class="text-slate-300 font-semibold mb-4 text-base m-0 flex items-center gap-2">
                <i class="bi bi-calendar2-check text-emerald-400"></i> Ingresos Realizados Hoy
            </h5>
            <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" id="summaryHeaderRow">
                            <th class="p-4">Producto / Laboratorio</th>
                            <th class="p-4 text-center bg-slate-700/50 w-28">Total Ingreso</th>
                            <!-- Branch Headers injected dynamically -->
                            <th class="p-4 text-center" id="summaryActionHeader">Acción</th>
                        </tr>
                    </thead>
                    <tbody id="todaySummaryBody" class="divide-y divide-slate-800/80">
                        <tr>
                            <td colspan="15" class="p-6 text-center text-slate-500 italic">No se han registrado ingresos hoy.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </section>

    <!-- TAB 3: HISTORIAL DE INGRESOS -->
    <section id="sec-historial" class="tab-content hidden animate-fade-in-up">
        <div id="historyContainer" class="space-y-6">
            <div class="text-center py-12">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-slate-700 border-t-indigo-500 mb-2"></div>
                <p class="text-slate-400 text-xs uppercase m-0">Cargando historial...</p>
            </div>
        </div>
    </section>

</div>

<!-- CORE JAVASCRIPT SYSTEM -->
<script>
    // Tab switching
    function switchTab(tabId) {
        document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(content => content.classList.add('hidden'));

        document.getElementById(`tab-${tabId}`).classList.add('active');
        document.getElementById(`sec-${tabId}`).classList.remove('hidden');

        if (tabId === 'historial') {
            loadHistory();
        }
    }

    // STATE MANAGEMENT
    const state = {
        users: [],
        branches: [],
        assignments: [],
        selectedUserId: null,
        searchResults: [],
        todayHistory: {}
    };

    // --- ACCESOS (TAB 1) ---
    async function loadAccessData() {
        try {
            const res = await fetch('api/usuarios_sucursales/get_data.php');
            const data = await res.json();
            if (data.success) {
                state.users = data.users;
                state.branches = data.branches;
                state.assignments = data.assignments;
                renderUserList();
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch (err) {
            console.error(err);
            Swal.fire('Error', 'Error de red al cargar accesos', 'error');
        }
    }

    function renderUserList(filter = '') {
        const list = document.getElementById('userList');
        const searchInput = document.getElementById('userSearch').value;
        const filtered = state.users.filter(u => 
            u.nombre.toLowerCase().includes(searchInput.toLowerCase()) ||
            u.usuario.toLowerCase().includes(searchInput.toLowerCase())
        );

        if (filtered.length === 0) {
            list.innerHTML = `<div class="text-center text-slate-500 py-6 italic text-sm">No se encontraron usuarios</div>`;
            return;
        }

        list.innerHTML = filtered.map(u => {
            const isActive = state.selectedUserId === u.id;
            return `
                <div onclick="selectUser(${u.id})" class="user-card-premium p-3 rounded-xl cursor-pointer hover:bg-slate-800/40 flex items-center gap-3 ${isActive ? 'active' : 'bg-slate-900/30'}">
                    <div class="w-9 h-9 rounded-lg bg-indigo-600/20 text-indigo-400 flex items-center justify-center font-bold text-sm">
                        ${u.nombre.charAt(0).toUpperCase()}
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="font-semibold text-sm text-white truncate m-0">${u.nombre}</p>
                        <p class="text-slate-400 text-xs truncate m-0">@${u.usuario}</p>
                    </div>
                </div>
            `;
        }).join('');
    }

    document.getElementById('userSearch').addEventListener('input', () => renderUserList());

    function selectUser(userId) {
        state.selectedUserId = userId;
        renderUserList();
        
        const user = state.users.find(u => u.id === userId);
        document.getElementById('emptyUserState').classList.add('hidden');
        document.getElementById('assignmentPanel').classList.remove('hidden');
        document.getElementById('selectedUserName').textContent = user.nombre;

        renderBranchGrid(userId);
    }

    function renderBranchGrid(userId) {
        const grid = document.getElementById('branchGrid');
        const userBranches = state.assignments
            .filter(a => parseInt(a.usuario_id) === parseInt(userId))
            .map(a => parseInt(a.sucursal_id));

        grid.innerHTML = state.branches.map(b => {
            const isAssigned = userBranches.includes(parseInt(b.id));
            return `
                <label class="relative flex items-center p-4 bg-slate-900/50 border rounded-xl cursor-pointer hover:bg-slate-800/60 transition-all ${isAssigned ? 'border-indigo-600/70 bg-indigo-950/15' : 'border-slate-800'}">
                    <input type="checkbox" name="branch_access" value="${b.id}" class="w-4 h-4 text-indigo-600 bg-slate-800 border-slate-700 rounded focus:ring-indigo-500 focus:ring-offset-slate-900" ${isAssigned ? 'checked' : ''} onchange="toggleBranchLabel(this)">
                    <div class="ms-3 flex-1">
                        <span class="block font-semibold text-sm text-white">${b.nombre}</span>
                        <span class="block text-slate-400 text-[10px] mt-0.5"><i class="bi bi-geo-alt-fill me-1"></i>${b.direccion || 'Sin dirección'}</span>
                    </div>
                </label>
            `;
        }).join('');
    }

    function toggleBranchLabel(checkbox) {
        const label = checkbox.closest('label');
        if (checkbox.checked) {
            label.classList.add('border-indigo-600/70', 'bg-indigo-950/15');
            label.classList.remove('border-slate-800');
        } else {
            label.classList.remove('border-indigo-600/70', 'bg-indigo-950/15');
            label.classList.add('border-slate-800');
        }
    }

    async function saveAssignments() {
        if (!state.selectedUserId) return;

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

        const checked = Array.from(document.querySelectorAll('input[name="branch_access"]:checked')).map(cb => parseInt(cb.value));

        try {
            const res = await fetch('api/usuarios_sucursales/save_assignment.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    usuario_id: state.selectedUserId,
                    sucursales: checked
                })
            });
            const data = await res.json();
            if (data.success) {
                // Update local model
                state.assignments = state.assignments.filter(a => parseInt(a.usuario_id) !== parseInt(state.selectedUserId));
                checked.forEach(bid => {
                    state.assignments.push({
                        usuario_id: state.selectedUserId,
                        sucursal_id: bid,
                        rol: 'vendedor',
                        activo: 1
                    });
                });
                
                Swal.fire({
                    icon: 'success',
                    title: '¡Guardado!',
                    text: 'Accesos actualizados correctamente.',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 2000
                });
            } else {
                Swal.fire('Error', data.message, 'error');
            }
        } catch (err) {
            console.error(err);
            Swal.fire('Error', 'Fallo al guardar en el servidor', 'error');
        } finally {
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-cloud-arrow-up-fill me-1"></i> Guardar Accesos';
        }
    }


    // --- DISTRIBUCION (TAB 2) ---
    async function loadBranchesForDistribution() {
        try {
            const res = await fetch('api/distribucion/get_sucursales.php');
            const branchesList = await res.json();
            
            // Exclude central admin branch if it's there
            state.branches = branchesList.filter(b => b.nombre.toUpperCase() !== 'VENTAS ADMINISTRACION');
            
            renderDynamicHeaders();
            loadTodaySummary();
        } catch (err) {
            console.error("Error loading branches for distribution", err);
        }
    }

    function renderDynamicHeaders() {
        const hRow = document.querySelector('#searchResultsContainer thead tr');
        const sHeader = document.getElementById('searchActionHeader');
        const sumRow = document.getElementById('summaryHeaderRow');
        const sumHeader = document.getElementById('summaryActionHeader');

        document.querySelectorAll('.dynamic-dist-header').forEach(el => el.remove());

        state.branches.forEach(b => {
            // Search Table Header
            const th = document.createElement('th');
            th.className = 'dynamic-dist-header p-3 text-center border-x border-slate-800 w-20';
            th.textContent = b.nombre;
            hRow.insertBefore(th, sHeader);

            // Summary Table Header
            const th2 = document.createElement('th');
            th2.className = 'dynamic-dist-header p-4 text-center border-x border-slate-800 bg-slate-800/40 min-w-[100px]';
            th2.innerHTML = `
                <div class="flex flex-col items-center gap-1.5">
                    <span>${b.nombre}</span>
                    <button onclick="printBranchReport(${b.id}, '${b.nombre}')" class="btn px-2 py-1 rounded bg-indigo-600 text-white border-0 hover:bg-indigo-500 cursor-pointer text-[10px] flex items-center gap-1">
                        <i class="bi bi-printer-fill"></i> PDF
                    </button>
                </div>
            `;
            sumRow.insertBefore(th2, sumHeader);
        });
    }

    // Search Engine listeners
    let searchTimeout;
    document.getElementById('mainSearch').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        const q = e.target.value.trim();

        if (q.length < 2) {
            state.searchResults = [];
            document.getElementById('searchResultsContainer').classList.add('hidden');
            return;
        }

        searchTimeout = setTimeout(async () => {
            try {
                const res = await fetch(`api/distribucion/productos_search.php?q=${encodeURIComponent(q)}`);
                const data = await res.json();
                state.searchResults = Array.isArray(data) ? data : [];
                
                const container = document.getElementById('searchResultsContainer');
                if (state.searchResults.length > 0) {
                    container.classList.remove('hidden');
                    renderSearchTable();
                } else {
                    container.classList.add('hidden');
                }
            } catch (err) {
                console.error(err);
            }
        }, 305);
    });

    function renderSearchTable() {
        const body = document.getElementById('productTableBody');
        body.innerHTML = state.searchResults.map((p, idx) => `
            <tr class="hover:bg-slate-800/25 transition-colors">
                <td class="p-3">
                    <p class="font-bold text-white text-xs m-0">${p.nombre}</p>
                    <p class="text-[10px] text-slate-400 mt-1 m-0">INT: ${p.CodigoInterno || 'N/A'} | BAR: ${p.CodigoBarra || 'N/A'}</p>
                    <p class="text-[9px] text-indigo-400 italic m-0 font-medium">${p.laboratorio || ''}</p>
                </td>
                <td class="p-3">
                    <select id="pres_${idx}" class="w-full bg-slate-800 border border-slate-700 rounded-lg p-1.5 text-xs text-white outline-none">
                        <option value="UNIDAD">UNIDAD</option>
                        <option value="BLISTER">BLISTER</option>
                        <option value="CAJA">CAJA</option>
                    </select>
                </td>
                <td class="p-3">
                    <div class="flex flex-col items-center">
                        <input type="number" id="total_${idx}" autocomplete="off" oninput="validateDistributionRow(${idx})" class="w-20 p-2 bg-slate-800 border border-slate-700 rounded-lg font-bold text-center text-white focus:border-emerald-500" value="0">
                        <div class="text-[9px] font-bold mt-1 uppercase text-slate-400" id="restante_label_${idx}">Restante: 0</div>
                    </div>
                </td>
                <td class="p-3">
                    <input type="date" id="venc_${idx}" onchange="validateDistributionRow(${idx})" class="w-full bg-slate-800 border border-slate-700 rounded-lg p-1.5 text-[11px] font-bold text-white outline-none">
                </td>
                <td class="p-3 text-center">
                    <div class="flex flex-col items-center gap-1.5">
                        <input type="checkbox" id="fact_${idx}" onchange="updateFactLabel(${idx})" checked class="w-4 h-4 text-emerald-600 bg-slate-800 border-slate-700 rounded">
                        <span id="fact_label_${idx}" class="text-[9px] font-bold uppercase text-emerald-400">Sí</span>
                    </div>
                </td>
                ${state.branches.map(b => `
                    <td class="p-3 text-center border-x border-slate-800/40">
                        <input type="number" data-bid="${b.id}" autocomplete="off" oninput="validateDistributionRow(${idx})" class="branch-input-${idx} w-16 p-2 bg-slate-800 border border-slate-700 rounded-lg font-medium text-center text-white focus:border-indigo-500" value="0">
                    </td>
                `).join('')}
                <td class="p-3 text-center">
                    <button id="btn_${idx}" onclick="submitEntry(${idx}, ${p.id})" disabled class="bg-slate-800 text-slate-500 px-4 py-2 rounded-lg font-bold text-[10px] uppercase border-0 cursor-not-allowed">Ingresar</button>
                </td>
            </tr>
        `).join('');
    }

    function updateFactLabel(idx) {
        const cb = document.getElementById(`fact_${idx}`);
        const label = document.getElementById(`fact_label_${idx}`);
        label.textContent = cb.checked ? 'Sí' : 'No';
        label.className = cb.checked ? 'text-[9px] font-bold uppercase text-emerald-400' : 'text-[9px] font-bold uppercase text-rose-400';
    }

    function validateDistributionRow(idx) {
        const totalInput = document.getElementById(`total_${idx}`);
        const total = parseInt(totalInput.value) || 0;
        const branchInputs = document.querySelectorAll(`.branch-input-${idx}`);
        let distributed = 0;
        branchInputs.forEach(input => distributed += (parseInt(input.value) || 0));

        const restante = total - distributed;
        const label = document.getElementById(`restante_label_${idx}`);
        label.textContent = `Rest: ${restante}`;
        
        if (restante >= 0 && total > 0) {
            label.className = 'text-[9px] font-bold text-center mt-1 uppercase text-emerald-400';
        } else {
            label.className = 'text-[9px] font-bold text-center mt-1 uppercase text-rose-400';
        }

        const btn = document.getElementById(`btn_${idx}`);
        if (restante >= 0 && total > 0) {
            btn.disabled = false;
            btn.className = "btn bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded-lg font-bold text-[10px] uppercase border-0 cursor-pointer";
        } else {
            btn.disabled = true;
            btn.className = "bg-slate-800 text-slate-500 px-4 py-2 rounded-lg font-bold text-[10px] uppercase border-0 cursor-not-allowed";
        }
    }

    async function submitEntry(idx, producto_id) {
        const btn = document.getElementById(`btn_${idx}`);
        btn.disabled = true;
        btn.innerHTML = '<span class="inline-block animate-spin rounded-full h-3 w-3 border-2 border-white border-t-transparent"></span>';

        const data = {
            producto_id,
            presentacion: document.getElementById(`pres_${idx}`).value,
            total_cantidad: parseInt(document.getElementById(`total_${idx}`).value),
            fecha_vencimiento: document.getElementById(`venc_${idx}`).value,
            facturado: document.getElementById(`fact_${idx}`).checked ? 1 : 0,
            distribucion: {}
        };

        const branchInputs = document.querySelectorAll(`.branch-input-${idx}`);
        branchInputs.forEach(i => {
            const bid = i.dataset.bid;
            const qty = parseInt(i.value) || 0;
            if (qty > 0) data.distribucion[bid] = qty;
        });

        try {
            const res = await fetch('api/distribucion/registrar.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();
            if (result.success) {
                Swal.fire({ 
                    icon: 'success', 
                    title: 'Ingreso Registrado', 
                    toast: true, 
                    position: 'top-end', 
                    showConfirmButton: false, 
                    timer: 2000 
                });
                
                document.getElementById('mainSearch').value = '';
                document.getElementById('searchResultsContainer').classList.add('hidden');
                state.searchResults = [];
                document.getElementById('mainSearch').focus();
                
                loadTodaySummary();
            } else { 
                Swal.fire('Error', result.message, 'error'); 
            }
        } catch (e) { 
            Swal.fire('Error', 'Fallo al procesar ingreso', 'error'); 
        } finally { 
            if (btn) { 
                btn.disabled = false; 
                btn.innerHTML = 'Ingresar'; 
            } 
        }
    }

    async function loadTodaySummary() {
        const body = document.getElementById('todaySummaryBody');
        try {
            const res = await fetch('api/distribucion/get_history.php');
            const data = await res.json();
            if (data.success) {
                const todayStr = new Date().toISOString().split('T')[0];
                state.todayHistory = data.history[todayStr] || {};
                renderTodaySummary(state.todayHistory);
            }
        } catch (e) { 
            console.error("Error loading today summary", e); 
        }
    }

    function renderTodaySummary(productsObj) {
        const body = document.getElementById('todaySummaryBody');
        if (Object.keys(productsObj).length === 0) {
            body.innerHTML = `<tr><td colspan="15" class="p-6 text-center text-slate-500 italic">No se han realizado ingresos hoy todavía.</td></tr>`;
            return;
        }

        body.innerHTML = Object.values(productsObj).map((p, pIdx) => {
            const dists = p.distribuciones;
            const rowId = `row_${pIdx}`;

            return `
                <tr id="sum_${rowId}" class="hover:bg-slate-800/10 transition-colors" data-ingreso="${p.ingreso_id}" data-fact="${p.sefactura}">
                    <td class="p-4">
                        <div class="font-bold text-white text-xs">${p.producto}</div>
                    </td>
                    <td class="p-4 text-center font-bold text-white bg-slate-800/30 border-x border-slate-800">
                        <span class="qty-text">${p.total_ingreso}</span>
                        <input type="number" value="${p.total_ingreso}" autocomplete="off" class="qty-input input-total hidden w-16 p-1 text-center bg-slate-700 border border-slate-600 rounded text-white font-bold text-xs">
                    </td>
                    ${state.branches.map(b => {
                        const d = dists[b.id];
                        const qty = d ? d.cantidad : 0;
                        const tid = d ? d.traslado_id : null;
                        return `
                            <td class="p-4 text-center text-xs font-bold ${qty > 0 ? 'text-indigo-400 bg-indigo-950/10' : 'text-slate-600'} branch-cell" data-bid="${b.id}" data-tid="${tid}">
                                <span class="qty-text">${qty}</span>
                                <input type="number" value="${qty}" autocomplete="off" class="qty-input input-branch hidden w-16 p-1 text-center bg-slate-700 border border-slate-600 rounded text-white font-bold text-xs">
                            </td>
                        `;
                    }).join('')}
                    <td class="p-4 text-center">
                        <button onclick="toggleEditRow('${rowId}')" class="edit-btn text-blue-400 hover:text-blue-300 font-bold text-[9px] uppercase px-2.5 py-1.5 bg-blue-950/20 border-0 rounded cursor-pointer">Editar</button>
                        <button onclick="saveEditRow('${rowId}')" class="save-btn hidden text-white bg-emerald-600 hover:bg-emerald-500 font-bold text-[9px] uppercase px-3 py-1.5 border-0 rounded cursor-pointer">Guardar</button>
                    </td>
                </tr>
            `;
        }).join('');
    }

    function toggleEditRow(rowId) {
        const row = document.getElementById(`sum_${rowId}`);
        row.querySelectorAll('.qty-text, .edit-btn').forEach(el => el.classList.add('hidden'));
        row.querySelectorAll('.qty-input, .save-btn').forEach(el => el.classList.remove('hidden'));
        row.querySelector('.input-total').focus();
    }

    async function saveEditRow(rowId) {
        const row = document.getElementById(`sum_${rowId}`);
        const ingreso_id = row.dataset.ingreso;
        const sefactura = row.dataset.fact;
        
        const totalInput = row.querySelector('.input-total');
        const totalVal = parseInt(totalInput.value) || 0;

        const branchCells = row.querySelectorAll('.branch-cell');
        const updates = [];
        let totalDistributed = 0;
        
        branchCells.forEach(cell => {
            const tid = cell.dataset.tid;
            const input = cell.querySelector('.input-branch');
            const nQty = parseInt(input.value) || 0;
            totalDistributed += nQty;
            if (tid && tid !== 'null' && nQty !== parseInt(input.defaultValue)) {
                updates.push({ traslado_id: tid, cantidad: nQty, sefactura });
            }
        });

        if (totalDistributed > totalVal) {
            Swal.fire({ 
                icon: 'warning', 
                title: 'Distribución excedida', 
                text: `La suma distribuida (${totalDistributed}) supera el total ingresado (${totalVal}).` 
            });
            return;
        }

        const payload = {};
        if (updates.length > 0) payload.updates = updates;
        if (totalVal !== parseInt(totalInput.defaultValue)) {
            payload.total_update = { ingreso_id, cantidad: totalVal, sefactura };
        }

        if (Object.keys(payload).length === 0) { 
            loadTodaySummary(); 
            return; 
        }

        try {
            const res = await fetch('api/distribucion/actualizar.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await res.json();
            if (result.success) {
                Swal.fire({ 
                    icon: 'success', 
                    title: 'Actualizado', 
                    toast: true, 
                    position: 'top-end', 
                    showConfirmButton: false, 
                    timer: 2000 
                });
                loadTodaySummary();
            } else { 
                Swal.fire('Error', result.message, 'error'); 
            }
        } catch (e) { 
            Swal.fire('Error', 'Fallo de red al actualizar', 'error'); 
        }
    }

    async function printBranchReport(branchId, branchName) {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        const todayStr = new Date().toLocaleDateString('es-GT');
        const rows = [];

        Object.values(state.todayHistory).forEach(p => {
            const dist = p.distribuciones[branchId];
            if (dist && dist.cantidad > 0) {
                rows.push([p.producto, dist.cantidad, p.sefactura == 1 ? 'SÍ' : 'NO', todayStr]);
            }
        });

        if (rows.length === 0) { 
            Swal.fire('Atención', 'No hay stock registrado hoy para ' + branchName, 'info'); 
            return; 
        }

        doc.setFontSize(16);
        doc.setFont("helvetica", "bold");
        doc.text(`REPORTE DE LOGÍSTICA: ${branchName.toUpperCase()}`, 105, 20, { align: 'center' });
        doc.setFontSize(10);
        doc.setFont("helvetica", "normal");
        doc.text(`Fecha del Informe: ${todayStr}`, 105, 28, { align: 'center' });
        
        doc.autoTable({
            head: [['Nombre del Producto', 'Cantidad', 'Facturado', 'Fecha']],
            body: rows,
            startY: 40,
            theme: 'grid',
            headStyles: { fillColor: [79, 70, 229], textColor: 255 },
            styles: { fontSize: 9, cellPadding: 4 }
        });

        const finalY = doc.lastAutoTable.finalY + 25;
        doc.line(20, finalY, 90, finalY);
        doc.text("Entregado Por (Firma)", 55, finalY + 5, { align: 'center' });
        doc.line(120, finalY, 190, finalY);
        doc.text("Recibido Por (Firma)", 155, finalY + 5, { align: 'center' });

        doc.save(`Informe_Distribucion_${branchName.replace(/\s+/g, '_')}_${todayStr}.pdf`);
    }

    // --- HISTORIAL (TAB 3) ---
    async function loadHistory() {
        const container = document.getElementById('historyContainer');
        container.innerHTML = `
            <div class="text-center py-12">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-slate-700 border-t-indigo-500 mb-2"></div>
                <p class="text-slate-400 text-xs uppercase m-0">Cargando historial...</p>
            </div>`;

        try {
            const res = await fetch('api/distribucion/get_history.php');
            const data = await res.json();
            if (data.success) {
                renderHistory(data.history);
            } else {
                container.innerHTML = `<div class="text-center p-8 bg-slate-900/60 rounded-xl text-rose-400 font-bold">Error: ${data.message}</div>`;
            }
        } catch (e) {
            console.error(e);
            container.innerHTML = `<div class="text-center p-8 bg-slate-900/60 rounded-xl text-rose-400 font-bold">Error de red al cargar el historial</div>`;
        }
    }

    function renderHistory(history) {
        const container = document.getElementById('historyContainer');
        const dates = Object.keys(history);

        if (dates.length === 0) {
            container.innerHTML = `<div class="text-center p-12 bg-slate-900/40 rounded-xl text-slate-500 italic">No hay registros de ingresos históricos.</div>`;
            return;
        }

        const sucursalesOrder = state.branches.map(b => ({ id: b.id, name: b.nombre }));

        container.innerHTML = dates.map((date, dIdx) => {
            const productsObj = history[date];
            
            return `
                <div class="glass rounded-2xl p-6">
                    <div class="flex justify-between items-center mb-4 flex-wrap gap-2">
                        <div class="flex items-center gap-3">
                            <span class="px-3.5 py-1.5 rounded-lg bg-indigo-600/20 text-indigo-400 font-bold text-xs tracking-wider">${formatDate(date)}</span>
                        </div>
                        <button onclick="window.open('api/distribucion/exportar_xlsx.php?fecha=${date}', '_blank')" class="btn px-4 py-2 text-xs font-bold text-white bg-emerald-600 hover:bg-emerald-500 rounded-lg border-0 cursor-pointer flex items-center gap-1.5">
                            <i class="bi bi-file-spreadsheet"></i> EXPORTAR A EXCEL
                        </button>
                    </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 w-1/3">Producto</th>
                                    <th class="p-3 text-center bg-slate-700/50 w-24">Total</th>
                                    ${sucursalesOrder.map(s => `
                                        <th class="p-3 text-center border-x border-slate-800">${s.name}</th>
                                    `).join('')}
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-800/60">
                                ${Object.values(productsObj).map(p => {
                                    const dists = p.distribuciones;
                                    const total = Object.values(dists).reduce((acc, curr) => acc + curr.cantidad, 0);
                                    return `
                                        <tr class="hover:bg-slate-800/10 transition-colors">
                                            <td class="p-3 font-bold text-white">${p.producto}</td>
                                            <td class="p-3 text-center font-bold text-white bg-slate-800/30 border-l border-slate-800">${total}</td>
                                            ${sucursalesOrder.map(s => {
                                                const d = dists[s.id];
                                                const qty = d ? d.cantidad : 0;
                                                return `
                                                    <td class="p-3 text-center font-bold ${qty > 0 ? 'text-indigo-400 bg-indigo-950/5' : 'text-slate-700'} border-x border-slate-800/40">
                                                        ${qty || '-'}
                                                    </td>
                                                `;
                                            }).join('')}
                                        </tr>
                                    `;
                                }).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        }).join('');
    }

    function formatDate(dateStr) {
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const date = new Date(dateStr + 'T12:00:00');
        return date.toLocaleDateString('es-ES', options).toUpperCase();
    }

    // INITIALIZATION
    window.onload = function() {
        loadAccessData();
        loadBranchesForDistribution();
    };
</script>

<?php
renderFooter();
?>

