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

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

renderHeader('Pedidos Sucursales', 'pedidos');
?>

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

<style>
    .report-wrap {
        max-width: 1400px;
        margin: 0 auto;
        padding: 1.5rem;
        display: flex;
        flex-direction: column;
        gap: 1.5rem;
    }
    .report-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 0.5rem;
        flex-wrap: wrap;
        gap: 1rem;
    }
    .report-header h1 {
        font-size: 1.75rem;
        font-weight: 800;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    /* Premium Export Buttons */
    .btn-export-excel-green {
        background: rgba(16, 185, 129, 0.1) !important;
        color: #10b981 !important;
        border: 1px solid rgba(16, 185, 129, 0.2) !important;
        font-weight: 700 !important;
        height: 38px;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.8rem;
        cursor: pointer;
        transition: all var(--transition) !important;
        white-space: nowrap;
        border-radius: var(--radius-sm);
        padding: 0 1rem;
    }
    .btn-export-excel-green:hover {
        background: #10b981 !important;
        color: var(--primary) !important;
        border-color: #10b981 !important;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
    }
    
    .filters-card {
        background: var(--surface-elevated);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 1.25rem 1.5rem;
    }
    .filters-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 1.25rem;
        align-items: end;
    }
    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 0.35rem;
    }
    .filter-label {
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: var(--text-secondary);
    }
    .filter-input {
        width: 100%;
        padding: 0.6rem 0.85rem;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border);
        background: var(--surface);
        color: var(--text-primary);
        font-size: 0.875rem;
        outline: none;
        transition: border-color var(--transition), box-shadow var(--transition);
        box-sizing: border-box;
    }
    .filter-input:focus {
        border-color: var(--accent-color);
        box-shadow: var(--focus-ring);
    }
    .btn-filter-group {
        display: flex;
        gap: 0.75rem;
        height: 38px;
        margin-top: 1.25rem;
    }
    .btn-filter {
        padding: 0.65rem 1.25rem;
        background: var(--accent-color);
        color: var(--primary);
        border: none;
        border-radius: var(--radius-sm);
        font-weight: 700;
        font-size: 0.875rem;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        transition: all var(--transition);
    }
    .btn-filter:hover {
        opacity: 0.9;
        transform: translateY(-1px);
    }
    .btn-clear {
        padding: 0.65rem 1.25rem;
        background: transparent;
        color: var(--text-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        font-weight: 700;
        font-size: 0.875rem;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        transition: all var(--transition);
    }
    .btn-clear:hover {
        background: var(--surface-hover);
        color: var(--text-primary);
    }
    .badge-soft-danger {
        background: rgba(239, 68, 68, 0.12);
        color: var(--danger);
        border: 1px solid rgba(239, 68, 68, 0.25);
    }
    .badge-soft-primary {
        background: rgba(30, 58, 95, 0.12);
        color: var(--accent-color);
        border: 1px solid rgba(30, 58, 95, 0.25);
    }
    
    /* CSS Fade In Up Animation to replace Tailwind custom config */
    @keyframes fadeInUp {
        0% { opacity: 0; transform: translateY(15px); }
        100% { opacity: 1; transform: translateY(0); }
    }
    .animate-fade-in-up {
        animation: fadeInUp 0.3s ease-out forwards;
    }
    /* Custom Scrollbars */
    ::-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;
    }
    .urgent-pulse {
        animation: pulse 2.2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
    }
    @keyframes pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: .7; transform: scale(0.95); }
    }

    /* KPIs Vibe from Caja Chica */
    .kpis-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 1.5rem;
    }
    .kpi-card {
        background: var(--surface);
        border: 1px solid var(--border);
        border-radius: var(--radius);
        padding: 1.5rem;
        position: relative;
        overflow: hidden;
    }
    .kpi-card-icon {
        position: absolute;
        right: 1.25rem;
        top: 1.25rem;
        font-size: 2rem;
        opacity: 0.15;
    }
    .kpi-card-label {
        font-size: 0.75rem;
        text-transform: uppercase;
        font-weight: 700;
        color: var(--text-secondary);
        letter-spacing: 0.05em;
    }
    .kpi-card-value {
        font-size: 2.25rem;
        font-weight: 800;
        margin-top: 0.5rem;
    }
    
    /* Pagination Styles */
    .pagination-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1rem 1.5rem;
        background: var(--surface);
        border-top: 1px solid var(--border);
        flex-wrap: wrap;
        gap: 1rem;
    }
    .btn-page {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-width: 32px;
        height: 32px;
        padding: 0 6px;
        font-size: 0.85rem;
        font-weight: 600;
        color: var(--text-secondary);
        background: transparent;
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        cursor: pointer;
        transition: all var(--transition);
    }
    .btn-page:hover:not(:disabled) {
        background: var(--surface-hover);
        color: var(--text-primary);
        border-color: var(--text-secondary);
    }
    .btn-page.active {
        background: var(--accent-color);
        color: var(--primary);
        border-color: var(--accent-color);
    }
    .btn-page:disabled {
        opacity: 0.4;
        cursor: not-allowed;
    }
</style>

<div class="report-wrap animate-fade-in-up">
    
    <!-- HEADER -->
    <div class="report-header">
        <div>
            <h1 style="font-size: 1.5rem; font-family: 'League Spartan'; font-weight: 800; margin: 0; display: flex; align-items: center; gap: 0.5rem;">
                <i class="fas fa-cart-plus" style="color:var(--accent-color); margin-right:0.5rem;"></i>
                Consola de Pedidos
            </h1>
            <p style="color: var(--text-secondary); margin-top: 0.35rem; font-size: 0.875rem; margin-bottom: 0;">Monitorea y gestiona los requerimientos de medicamentos e insumos de las sucursales</p>
        </div>
        <div style="display: flex; align-items: center; gap: 0.75rem;">
            <div id="resultsCountBadge" class="badge-premium badge-soft-primary" style="font-size: 0.75rem; padding: 0.5rem 1rem;">
                0 productos
            </div>
            <button onclick="exportToExcel()" class="btn-export-excel-green">
                <i class="bi bi-file-earmark-spreadsheet"></i> Excel
            </button>
        </div>
    </div>

    <!-- FILTERS PANEL -->
    <div class="filters-card">
        <h5 style="font-size: 0.875rem; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 1rem 0; display: flex; align-items: center; gap: 0.5rem;">
            <i class="bi bi-funnel-fill" style="color: var(--accent-color);"></i> Filtros de Pedidos
        </h5>
        
        <div class="filters-grid">
            <div class="filter-group">
                <label class="filter-label">Sucursal</label>
                <select id="branchFilter" class="filter-input">
                    <option value="0">Todas las Sucursales</option>
                </select>
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Laboratorio</label>
                <input type="text" id="labFilter" placeholder="Ej. Bayer..." class="filter-input">
            </div>
            
            <div class="filter-group">
                <label class="filter-label">Categoría</label>
                <select id="catFilter" class="filter-input">
                    <option value="0">Todas las Categorías</option>
                </select>
            </div>

            <div class="filter-group">
                <label class="filter-label">Fecha Desde</label>
                <input type="date" id="dateFrom" class="filter-input">
            </div>

            <div class="filter-group">
                <label class="filter-label">Fecha Hasta</label>
                <input type="date" id="dateTo" class="filter-input">
            </div>
            
            <div class="filter-group" style="height: 38px; display: flex; justify-content: center;">
                <label class="checkbox-label" style="margin: 0; display: flex; align-items: center; gap: 0.5rem; cursor: pointer; user-select: none;">
                    <input type="checkbox" id="urgentFilter" style="width: 18px; height: 18px; accent-color: var(--accent-color); cursor: pointer; margin: 0;">
                    <span>Solo Urgentes</span>
                </label>
            </div>
        </div>

        <div class="btn-filter-group">
            <button onclick="applyFilters()" class="btn-filter">
                <i class="bi bi-search"></i> Aplicar Filtros
            </button>
            <button onclick="resetFilters()" class="btn-clear">
                <i class="bi bi-arrow-counterclockwise"></i> Limpiar
            </button>
        </div>
    </div>

    <!-- SEARCH BAR -->
    <div class="filters-card" style="padding: 1rem 1.5rem;">
        <div style="display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;">
            <div class="filter-label" style="display: flex; align-items: center; gap: 0.5rem; margin: 0;">
                <i class="bi bi-search"></i> Buscar
            </div>
            <div style="position: relative; flex: 1; min-width: 200px;">
                <i class="bi bi-search" style="position: absolute; left: 1rem; top: 50%; transform: translateY(-50%); color: var(--text-muted); pointer-events: none;"></i>
                <input type="text" id="searchBox" placeholder="Nombre, código interno, código de barra o laboratorio..." class="filter-input" style="padding-left: 2.5rem !important; width: 100%;">
            </div>
            <button onclick="clearSearch()" class="btn-clear" style="height: 38px; padding: 0 1rem; display: flex; align-items: center; justify-content: center;">
                <i class="bi bi-x-lg"></i> Limpiar
            </button>
            <span id="searchCount" style="font-size: 0.75rem; color: var(--text-muted); font-weight: 500;"></span>
        </div>
    </div>

    <!-- KPIs -->
    <div class="kpis-grid" id="kpisGrid" style="margin-bottom: 1.5rem; display: none;">
        <div class="kpi-card">
            <div class="kpi-card-icon"><i class="bi bi-cart-check" style="color: var(--accent-color);"></i></div>
            <div class="kpi-card-label">Total Productos Solicitados</div>
            <div id="kpiTotalProducts" class="kpi-card-value" style="color: var(--text-primary);">0</div>
        </div>
        <div class="kpi-card" style="border-color: rgba(239, 68, 68, 0.25);">
            <div class="kpi-card-icon"><i class="bi bi-exclamation-triangle" style="color: var(--danger);"></i></div>
            <div class="kpi-card-label">Pedidos Urgentes</div>
            <div id="kpiUrgentProducts" class="kpi-card-value" style="color: var(--danger);">0</div>
        </div>
        <div class="kpi-card">
            <div class="kpi-card-icon"><i class="bi bi-building" style="color: var(--success);"></i></div>
            <div class="kpi-card-label">Sucursales con Pedidos</div>
            <div id="kpiActiveBranches" class="kpi-card-value" style="color: var(--success);">0</div>
        </div>
    </div>

    <!-- CONTENT DATA PANEL -->
    <div id="resultsPanel" class="card" style="padding: 0; overflow: hidden; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);">
        <!-- Table Container -->
        <div id="tableContainer" class="table-wrapper" style="border: none; border-radius: 0; margin-top: 0; overflow-x: auto;">
            <table class="table-premium">
                <thead>
                    <tr id="tableHeader">
                        <th>Código</th>
                        <th>Producto</th>
                        <th>Laboratorio</th>
                        <th>Categoría</th>
                        <th>Cantidad</th>
                        <th>Presentación</th>
                        <th>Sucursal</th>
                        <th>Fecha</th>
                        <th style="text-align: center;">Acción</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <!-- Rows dynamically injected -->
                </tbody>
            </table>
        </div>

        <!-- Pagination Container -->
        <div id="paginationContainer" class="pagination-container" style="display: none;">
            <div style="font-size: 0.85rem; color: var(--text-secondary);">
                Mostrando <span id="pagStart" style="font-weight: 700; color: var(--text-primary);">0</span> a <span id="pagEnd" style="font-weight: 700; color: var(--text-primary);">0</span> de <span id="pagTotal" style="font-weight: 700; color: var(--text-primary);">0</span> pedidos
            </div>
            
            <div style="display: flex; align-items: center; gap: 0.5rem;">
                <label style="font-size: 0.85rem; color: var(--text-secondary); margin: 0;">Filas por página:</label>
                <select id="pageSizeSelect" class="filter-input" style="width: auto; padding: 0.35rem 0.5rem; font-size: 0.85rem; height: auto;" onchange="changePageSize(this.value)">
                    <option value="25">25</option>
                    <option value="50" selected>50</option>
                    <option value="100">100</option>
                    <option value="200">200</option>
                </select>
            </div>

            <div class="pagination-buttons" style="display: flex; align-items: center; gap: 0.25rem;" id="paginationButtons">
                <!-- Buttons injected dynamically -->
            </div>
        </div>
    </div>

</div>

<!-- JAVASCRIPT LOGIC -->
<script>
    const API_BASE = '../pedidos/api/';
    let searchTerm = '';

    // Filter State
    let currentFilters = {
        sucursal_id: 0,
        laboratorio: '',
        categoria_id: 0,
        fecha_inicio: '',
        fecha_fin: '',
        es_urgente: false
    };

    let branches = [];
    let currentViewMode = null;
    let currentData = null;
    let currentBranches = [];

    window.onload = function() {
        loadBranches();
        loadCategories();
        loadOrders();
        document.getElementById('searchBox').addEventListener('input', applySearchFilter);
    };

    async function loadBranches() {
        try {
            const res = await fetch(API_BASE + 'get_branches.php');
            const data = await res.json();
            if (data.success) {
                branches = data.data;
                const select = document.getElementById('branchFilter');
                data.data.forEach(b => {
                    const opt = document.createElement('option');
                    opt.value = b.id;
                    opt.textContent = b.nombre;
                    select.appendChild(opt);
                });
            }
        } catch (err) {
            console.error('Error loading branches:', err);
        }
    }

    async function loadCategories() {
        try {
            const res = await fetch(API_BASE + 'get_filters.php');
            const data = await res.json();
            if (data.success && data.data.categorias) {
                const select = document.getElementById('catFilter');
                data.data.categorias.forEach(c => {
                    const opt = document.createElement('option');
                    opt.value = c.id;
                    opt.textContent = c.nombre;
                    select.appendChild(opt);
                });
            }
        } catch (err) {
            console.error('Error loading categories:', err);
        }
    }

    function applyFilters() {
        currentFilters = {
            sucursal_id: parseInt(document.getElementById('branchFilter').value),
            laboratorio: document.getElementById('labFilter').value.trim(),
            categoria_id: parseInt(document.getElementById('catFilter').value),
            fecha_inicio: document.getElementById('dateFrom').value,
            fecha_fin: document.getElementById('dateTo').value,
            es_urgente: document.getElementById('urgentFilter').checked
        };
        loadOrders();
    }

    function resetFilters() {
        document.getElementById('branchFilter').value = '0';
        document.getElementById('labFilter').value = '';
        document.getElementById('catFilter').value = '0';
        document.getElementById('dateFrom').value = '';
        document.getElementById('dateTo').value = '';
        document.getElementById('urgentFilter').checked = false;
        document.getElementById('searchBox').value = '';
        searchTerm = '';
        document.getElementById('searchCount').textContent = '';

        currentFilters = {
            sucursal_id: 0,
            laboratorio: '',
            categoria_id: 0,
            fecha_inicio: '',
            fecha_fin: '',
            es_urgente: false
        };
        loadOrders();
    }

    let currentPage = 1;
    let itemsPerPage = 50;

    async function loadOrders() {
        showLoading(true);
        try {
            const params = new URLSearchParams();
            if (currentFilters.sucursal_id > 0) params.append('sucursal_id', currentFilters.sucursal_id);
            if (currentFilters.laboratorio) params.append('laboratorio', currentFilters.laboratorio);
            if (currentFilters.categoria_id > 0) params.append('categoria_id', currentFilters.categoria_id);
            if (currentFilters.fecha_inicio) params.append('fecha_inicio', currentFilters.fecha_inicio);
            if (currentFilters.fecha_fin) params.append('fecha_fin', currentFilters.fecha_fin);
            if (currentFilters.es_urgente) params.append('es_urgente', '1');

            const res = await fetch(API_BASE + 'get_admin_orders.php?' + params.toString());
            const data = await res.json();
            
            if (data.success) {
                currentViewMode = data.view_mode;
                currentData = data.data;
                currentBranches = data.branches || [];
                currentPage = 1; // Reset to page 1 on new load
                applySearchFilter();
            } else {
                Swal.fire({
                    title: 'Error',
                    text: data.error || 'Error al obtener pedidos',
                    icon: 'error',
                    background: '#1e293b',
                    color: '#f1f5f9'
                });
                showEmpty();
            }
        } catch (err) {
            console.error('Error fetching orders:', err);
            showEmpty();
        }
    }

    function showLoading(show) {
        if (show) {
            const body = document.getElementById('tableBody');
            body.innerHTML = `
                <tr>
                    <td colspan="100" style="text-align: center; padding: 4rem;">
                        <i class="fas fa-spinner fa-pulse" style="font-size: 2rem; margin-bottom: 0.75rem; display: block; color: var(--accent-color);"></i>
                        <p style="color: var(--text-secondary); font-weight: 700; font-size: 0.85rem; text-transform: uppercase; margin: 0; letter-spacing: 0.05em;">Consultando pedidos...</p>
                    </td>
                </tr>
            `;
            document.getElementById('paginationContainer').style.display = 'none';
        }
    }

    function showEmpty() {
        const body = document.getElementById('tableBody');
        body.innerHTML = `
            <tr>
                <td colspan="100" style="text-align: center; padding: 4rem; color: var(--text-muted);">
                    <i class="bi bi-inbox" style="font-size: 2.5rem; display: block; margin-bottom: 0.75rem; opacity: 0.5;"></i>
                    <p style="font-weight: 700; font-size: 0.85rem; text-transform: uppercase; margin: 0;">No se encontraron pedidos con los filtros actuales</p>
                </td>
            </tr>
        `;
        document.getElementById('paginationContainer').style.display = 'none';
        updateResultsCount(0);
        updateKPIs([]);
    }

    function updateResultsCount(count) {
        const badge = document.getElementById('resultsCountBadge');
        const total = currentData ? currentData.length : 0;
        if (searchTerm && total > 0) {
            badge.textContent = `${count} de ${total} producto${total !== 1 ? 's' : ''}`;
        } else {
            badge.textContent = `${count} producto${count !== 1 ? 's' : ''}`;
        }
    }

    function updateKPIs(data) {
        if (!data || data.length === 0) {
            document.getElementById('kpiTotalProducts').textContent = '0';
            document.getElementById('kpiUrgentProducts').textContent = '0';
            document.getElementById('kpiActiveBranches').textContent = '0';
            document.getElementById('kpisGrid').style.display = 'grid';
            return;
        }

        // Total products requested (entries in the current filtered data)
        const total = data.length;
        document.getElementById('kpiTotalProducts').textContent = total;

        // Urgent products
        const urgent = data.filter(p => p.es_urgente == 1 || p.es_urgente === true).length;
        document.getElementById('kpiUrgentProducts').textContent = urgent;

        // Unique branches with orders
        let uniqueBranches = new Set();
        if (currentViewMode === 'consolidated') {
            data.forEach(p => {
                if (p.sucursales) {
                    Object.keys(p.sucursales).forEach(bId => {
                        const presentations = p.sucursales[bId].presentaciones || {};
                        const hasQty = Object.values(presentations).some(qty => qty > 0);
                        if (hasQty) {
                            uniqueBranches.add(bId);
                        }
                    });
                }
            });
        } else {
            data.forEach(p => {
                if (p.sucursal_id) {
                    uniqueBranches.add(p.sucursal_id);
                }
            });
        }
        document.getElementById('kpiActiveBranches').textContent = uniqueBranches.size;
        document.getElementById('kpisGrid').style.display = 'grid';
    }

    function applySearchFilter() {
        const term = document.getElementById('searchBox').value.trim().toLowerCase();
        searchTerm = term;
        if (!currentData) return;
        let filtered = currentData;
        if (term) {
            filtered = currentData.filter(p => {
                const name = (p.nombre_comercial || '').toLowerCase();
                const code = (p.codigo_interno || '').toLowerCase();
                const bar = (p.codigo_barra || '').toLowerCase();
                const lab = (p.laboratorio || '').toLowerCase();
                return name.includes(term) || code.includes(term) || bar.includes(term) || lab.includes(term);
            });
        }

        updateKPIs(filtered);

        const totalItems = filtered.length;
        if (totalItems === 0) {
            showEmpty();
            document.getElementById('searchCount').textContent = term ? `— 0 resultados` : '';
            return;
        }

        // Pagination calculations
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        if (currentPage > totalPages) {
            currentPage = Math.max(1, totalPages);
        }

        const start = (currentPage - 1) * itemsPerPage;
        const paginatedItems = filtered.slice(start, start + itemsPerPage);

        if (currentViewMode === 'consolidated') {
            renderConsolidatedTable(paginatedItems, currentBranches);
        } else {
            renderSingleBranchTable(paginatedItems);
        }

        updateResultsCount(totalItems);
        renderPaginationControls(totalItems);

        document.getElementById('searchCount').textContent = term ? `— ${totalItems} resultados` : '';
    }

    function renderPaginationControls(totalItems) {
        const totalPages = Math.ceil(totalItems / itemsPerPage);
        const container = document.getElementById('paginationContainer');
        
        if (totalPages <= 1) {
            // Draw simple indicator but hide complex buttons if only 1 page
            container.style.display = 'flex';
            const start = (currentPage - 1) * itemsPerPage + 1;
            const end = Math.min(currentPage * itemsPerPage, totalItems);
            document.getElementById('pagStart').textContent = start;
            document.getElementById('pagEnd').textContent = end;
            document.getElementById('pagTotal').textContent = totalItems;
            document.getElementById('paginationButtons').innerHTML = '';
            return;
        }
        
        container.style.display = 'flex';
        
        const start = (currentPage - 1) * itemsPerPage + 1;
        const end = Math.min(currentPage * itemsPerPage, totalItems);
        document.getElementById('pagStart').textContent = start;
        document.getElementById('pagEnd').textContent = end;
        document.getElementById('pagTotal').textContent = totalItems;
        
        const btnContainer = document.getElementById('paginationButtons');
        let html = '';
        
        // First & Prev buttons
        html += `<button class="btn-page" onclick="goToPage(1)" ${currentPage === 1 ? 'disabled' : ''} title="Primera página"><i class="bi bi-chevron-double-left"></i></button>`;
        html += `<button class="btn-page" onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''} title="Página anterior"><i class="bi bi-chevron-left"></i></button>`;
        
        // Page numbers
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);
        
        if (currentPage <= 3) {
            endPage = Math.min(totalPages, 5);
        }
        if (currentPage >= totalPages - 2) {
            startPage = Math.max(1, totalPages - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            html += `<button class="btn-page ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
        }
        
        // Next & Last buttons
        html += `<button class="btn-page" onclick="goToPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''} title="Siguiente página"><i class="bi bi-chevron-right"></i></button>`;
        html += `<button class="btn-page" onclick="goToPage(${totalPages})" ${currentPage === totalPages ? 'disabled' : ''} title="Última página"><i class="bi bi-chevron-double-right"></i></button>`;
        
        btnContainer.innerHTML = html;
    }

    function goToPage(page) {
        currentPage = page;
        applySearchFilter();
        document.getElementById('resultsPanel').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function changePageSize(size) {
        itemsPerPage = parseInt(size);
        currentPage = 1;
        applySearchFilter();
    }

    function clearSearch() {
        document.getElementById('searchBox').value = '';
        applySearchFilter();
    }

    function renderConsolidatedTable(products, branchList) {
        const header = document.getElementById('tableHeader');
        const body = document.getElementById('tableBody');

        let headHtml = `
            <th>Código</th>
            <th>Producto</th>
            <th>Laboratorio</th>
            <th>Categoría</th>
        `;

        branchList.forEach(b => {
            headHtml += `<th style="text-align: center; border-left: 1px solid var(--border); border-right: 1px solid var(--border);">${escapeHtml(b.nombre)}</th>`;
        });

        headHtml += `<th style="text-align: center; background: rgba(124, 58, 237, 0.08); width: 96px;">Total</th>`;
        headHtml += `<th style="text-align: center; width: 80px;">Acción</th>`;

        header.innerHTML = headHtml;

        let bodyHtml = '';
        products.forEach(p => {
            const urgentStyle = p.es_urgente ? 'background: rgba(239, 68, 68, 0.04); border-left: 3px solid var(--danger);' : '';
            
            bodyHtml += `<tr style="${urgentStyle}">`;
            bodyHtml += `<td style="color: var(--text-secondary); font-weight: 500;">${escapeHtml(p.codigo_interno || '-')}</td>`;
            bodyHtml += `<td style="font-weight: 600; color: var(--text-primary);">`;
            if (p.es_urgente) {
                bodyHtml += `<span class="urgent-pulse badge-premium badge-soft-danger" style="font-size: 8px; padding: 2px 4px; border-radius: 4px; margin-right: 6px;">URGENTE</span>`;
            }
            bodyHtml += `${escapeHtml(p.nombre_comercial)}</td>`;
            bodyHtml += `<td style="color: var(--text-secondary);">${escapeHtml(p.laboratorio || '-')}</td>`;
            bodyHtml += `<td style="color: var(--text-secondary);">${escapeHtml(p.categoria || 'Sin categoría')}</td>`;

            const totalPresentations = {};

            branchList.forEach(b => {
                const bData = p.sucursales[b.id];
                if (!bData || !bData.presentaciones) {
                    bodyHtml += `<td style="text-align: center; color: var(--text-muted);">-</td>`;
                } else {
                    const parts = [];
                    for (const [pres, qty] of Object.entries(bData.presentaciones)) {
                        if (qty > 0) {
                            parts.push(`${qty} ${pres.toLowerCase()}`);
                            totalPresentations[pres] = (totalPresentations[pres] || 0) + parseInt(qty);
                        }
                    }
                    if (parts.length > 0) {
                        bodyHtml += `<td style="text-align: center; font-weight: bold; color: var(--accent-color); background: rgba(210, 200, 221, 0.04); border-left: 1px solid var(--border); border-right: 1px solid var(--border);">${parts.join(' + ')}</td>`;
                    } else {
                        bodyHtml += `<td style="text-align: center; color: var(--text-muted);">-</td>`;
                    }
                }
            });

            const totalParts = [];
            for (const [pres, qty] of Object.entries(totalPresentations)) {
                if (qty > 0) totalParts.push(`${qty} ${pres.toLowerCase()}`);
            }
            const totalDisplay = totalParts.length > 0 ? totalParts.join(' + ') : '0';

            bodyHtml += `<td style="text-align: center; font-weight: bold; color: var(--success); background: rgba(34, 197, 94, 0.06);">${totalDisplay}</td>`;
            bodyHtml += `<td style="text-align: center;">
                <button onclick="deleteProductOrder(${p.producto_id}, 0, '${escapeHtml(p.nombre_comercial).replace(/'/g, "\\'")}')" class="btn-action-delete" title="Eliminar">
                    <i class="bi bi-trash-fill"></i>
                </button>
            </td>`;
            bodyHtml += '</tr>';
        });

        body.innerHTML = bodyHtml;
    }

    function renderSingleBranchTable(products) {
        const header = document.getElementById('tableHeader');
        const body = document.getElementById('tableBody');

        header.innerHTML = `
            <th>Código</th>
            <th>Producto</th>
            <th>Laboratorio</th>
            <th>Categoría</th>
            <th style="text-align: center;">Cantidad</th>
            <th>Presentación</th>
            <th>Sucursal</th>
            <th>Fecha</th>
            <th style="text-align: center;">Acción</th>
        `;

        let bodyHtml = '';
        products.forEach(p => {
            const urgentStyle = p.es_urgente ? 'background: rgba(239, 68, 68, 0.04); border-left: 3px solid var(--danger);' : '';
            const dateStr = new Date(p.fecha_pedido).toLocaleDateString('es-GT');

            bodyHtml += `<tr style="${urgentStyle}">`;
            bodyHtml += `<td style="color: var(--text-secondary); font-weight: 500;">${escapeHtml(p.codigo_interno || '-')}</td>`;
            bodyHtml += `<td style="font-weight: 600; color: var(--text-primary);">`;
            if (p.es_urgente) {
                bodyHtml += `<span class="urgent-pulse badge-premium badge-soft-danger" style="font-size: 8px; padding: 2px 4px; border-radius: 4px; margin-right: 6px;">URGENTE</span>`;
            }
            bodyHtml += `${escapeHtml(p.nombre_comercial)}</td>`;
            bodyHtml += `<td style="color: var(--text-secondary);">${escapeHtml(p.laboratorio || '-')}</td>`;
            bodyHtml += `<td style="color: var(--text-secondary);">${escapeHtml(p.categoria || 'Sin categoría')}</td>`;
            bodyHtml += `<td style="text-align: center; font-weight: bold; color: var(--accent-color);">${p.cantidad_solicitada}</td>`;
            bodyHtml += `<td style="color: var(--text-secondary); font-weight: 500;">${escapeHtml(p.presentacion_solicitada)}</td>`;
            bodyHtml += `<td style="color: var(--text-secondary);">${escapeHtml(p.sucursal_nombre)}</td>`;
            bodyHtml += `<td style="color: var(--text-muted); font-weight: 500;">${dateStr}</td>`;
            bodyHtml += `<td style="text-align: center;">
                <button onclick="deleteProductOrder(${p.producto_id}, ${p.sucursal_id}, '${escapeHtml(p.nombre_comercial).replace(/'/g, "\\'")}')" class="btn-action-delete" title="Eliminar">
                    <i class="bi bi-trash-fill"></i>
                </button>
            </td>`;
            bodyHtml += '</tr>';
        });

        body.innerHTML = bodyHtml;
    }

    function deleteProductOrder(productId, sucursalId, productName) {
        let msg = '';
        if (currentViewMode === 'consolidated' && sucursalId === 0) {
            msg = `Se eliminarán TODOS los pedidos de "${productName}" en TODAS las sucursales según los filtros de búsqueda.`;
        } else {
            const bName = branches.find(b => b.id == sucursalId)?.nombre || 'la sucursal';
            msg = `Se eliminarán los pedidos de "${productName}" en ${bName}.`;
        }

        Swal.fire({
            title: '¿Confirmar eliminación?',
            text: msg,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#475569',
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar',
            background: '#1e293b',
            color: '#f1f5f9'
        }).then(async (result) => {
            if (result.isConfirmed) {
                try {
                    const response = await fetch(API_BASE + 'delete_admin_order.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            producto_id: productId,
                            sucursal_id: sucursalId,
                            ...currentFilters
                        })
                    });
                    const data = await response.json();
                    if (data.success) {
                        Swal.fire({
                            title: '¡Eliminado!',
                            text: data.message || 'El pedido ha sido eliminado.',
                            icon: 'success',
                            background: '#1e293b',
                            color: '#f1f5f9'
                        });
                        loadOrders();
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: data.error || 'No se pudo eliminar',
                            icon: 'error',
                            background: '#1e293b',
                            color: '#f1f5f9'
                        });
                    }
                } catch(err) {
                    console.error(err);
                    Swal.fire({
                        title: 'Error',
                        text: 'Fallo al eliminar el pedido',
                        icon: 'error',
                        background: '#1e293b',
                        color: '#f1f5f9'
                    });
                }
            }
        });
    }

    function exportToExcel() {
        const params = new URLSearchParams();
        if (currentFilters.sucursal_id > 0) params.append('sucursal_id', currentFilters.sucursal_id);
        if (currentFilters.laboratorio) params.append('laboratorio', currentFilters.laboratorio);
        if (currentFilters.categoria_id > 0) params.append('categoria_id', currentFilters.categoria_id);
        if (currentFilters.fecha_inicio) params.append('fecha_inicio', currentFilters.fecha_inicio);
        if (currentFilters.fecha_fin) params.append('fecha_fin', currentFilters.fecha_fin);
        if (currentFilters.es_urgente) params.append('es_urgente', '1');
        if (searchTerm) params.append('search', searchTerm);

        window.open(API_BASE + 'export_admin_orders.php?' + params.toString(), '_blank');
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
</script>

<?php
renderFooter();
?>
