// Admin Panel JavaScript
// Handles multi-branch order viewing and Excel export

const API_BASE = 'api/';

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

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

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    loadBranches();
    loadCategories();
    setupEventListeners();
    // Load all orders by default
    loadOrders();
});

// Setup event listeners
function setupEventListeners() {
    document.getElementById('applyFiltersBtn').addEventListener('click', applyFilters);
    document.getElementById('resetFiltersBtn').addEventListener('click', resetFilters);
    document.getElementById('exportExcelBtn').addEventListener('click', exportToExcel);

    // Delete modal listeners
    document.getElementById('cancelDeleteBtn').addEventListener('click', closeDeleteModal);
    document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDelete);
}

// Load branches for dropdown
async function loadBranches() {
    try {
        const response = await fetch(API_BASE + 'get_branches.php');
        const data = await response.json();

        if (data.success) {
            branches = data.data;
            const select = document.getElementById('branchFilter');

            data.data.forEach(branch => {
                const option = document.createElement('option');
                option.value = branch.id;
                option.textContent = branch.nombre;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error loading branches:', error);
        showToast('Error', 'No se pudieron cargar las sucursales', 'error');
    }
}

// Load categories for dropdown
async function loadCategories() {
    try {
        const response = await fetch(API_BASE + 'get_filters.php');
        const data = await response.json();

        if (data.success && data.data.categorias) {
            const select = document.getElementById('catFilter');

            data.data.categorias.forEach(cat => {
                const option = document.createElement('option');
                option.value = cat.id;
                option.textContent = cat.nombre;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error loading categories:', error);
    }
}

// Apply filters and reload orders
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();
}

// Reset filters
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;

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

    loadOrders();
}

// Load orders from API
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 response = await fetch(API_BASE + 'get_admin_orders.php?' + params.toString());
        const data = await response.json();

        if (data.success) {
            currentData = data.data;
            currentViewMode = data.view_mode;

            if (data.view_mode === 'consolidated') {
                renderConsolidatedTable(data.data, data.branches);
            } else {
                renderSingleBranchTable(data.data);
            }

            updateResultsCount(data.data.length);
        } else {
            showToast('Error', data.error || 'Error al cargar pedidos', 'error');
            showEmpty();
        }
    } catch (error) {
        console.error('Error loading orders:', error);
        showToast('Error', 'Error de conexión', 'error');
        showEmpty();
    } finally {
        showLoading(false);
    }
}

// Render consolidated table (all branches)
function renderConsolidatedTable(products, branchList) {
    if (!products || products.length === 0) {
        showEmpty();
        return;
    }

    const tableHeader = document.getElementById('tableHeader');
    const tableBody = document.getElementById('tableBody');

    // Build header
    let headerHTML = `
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Código</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Producto</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Laboratorio</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Categoría</th>
    `;

    // Add branch columns
    branchList.forEach(branch => {
        headerHTML += `<th class="px-2 py-2 text-center text-xs font-bold uppercase tracking-wider">${escapeHtml(branch.nombre)}</th>`;
    });

    headerHTML += `<th class="px-2 py-2 text-center text-xs font-bold uppercase tracking-wider bg-blue-700">Total</th>`;
    headerHTML += `<th class="px-2 py-2 text-center text-xs font-bold uppercase tracking-wider">Acciones</th>`;

    tableHeader.innerHTML = headerHTML;

    // Build body
    let bodyHTML = '';

    products.forEach(product => {
        const urgentClass = product.es_urgente ? 'bg-red-50 border-l-4 border-red-500' : '';

        bodyHTML += `<tr class="hover:bg-slate-50 transition-colors ${urgentClass}">`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-700">${escapeHtml(product.codigo_interno || '-')}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs font-medium text-slate-900">`;

        if (product.es_urgente) {
            bodyHTML += `<span class="inline-block px-1 py-0.5 bg-red-100 text-red-700 text-xs font-bold rounded mr-1 urgent-badge">URG</span>`;
        }

        bodyHTML += `${escapeHtml(product.nombre_comercial)}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-600">${escapeHtml(product.laboratorio || '-')}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-600">${escapeHtml(product.categoria || 'Sin categoría')}</td>`;

        // Track total presentations across all branches
        const totalPresentations = {};

        // Add quantities for each branch
        branchList.forEach(branch => {
            const branchData = product.sucursales[branch.id];

            if (!branchData || !branchData.presentaciones) {
                bodyHTML += `<td class="px-2 py-2 text-xs text-center text-slate-300">-</td>`;
            } else {
                // Combine presentations for this branch
                const parts = [];
                for (const [pres, qty] of Object.entries(branchData.presentaciones)) {
                    if (qty > 0) {
                        parts.push(`${qty} ${pres.toLowerCase()}`);

                        // Add to total
                        if (!totalPresentations[pres]) {
                            totalPresentations[pres] = 0;
                        }
                        totalPresentations[pres] += parseInt(qty);
                    }
                }

                if (parts.length > 0) {
                    bodyHTML += `<td class="px-2 py-2 text-xs font-semibold text-center text-blue-700">${parts.join(' + ')}</td>`;
                } else {
                    bodyHTML += `<td class="px-2 py-2 text-xs text-center text-slate-300">-</td>`;
                }
            }
        });

        // Total column - combine all presentations
        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 class="px-2 py-2 text-xs font-bold text-center text-blue-900 bg-blue-50">${totalDisplay}</td>`;

        // Actions column - delete button
        bodyHTML += `<td class="px-2 py-2 text-center">`;
        bodyHTML += `<button onclick="showDeleteModal(${product.producto_id}, 0, '${escapeHtml(product.nombre_comercial).replace(/'/g, "\\'")}')"`;
        bodyHTML += ` class="inline-flex items-center justify-center w-8 h-8 bg-red-100 hover:bg-red-200 text-red-600 rounded-lg transition-all" title="Eliminar producto">`;
        bodyHTML += `<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">`;
        bodyHTML += `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>`;
        bodyHTML += `</svg></button></td>`;

        bodyHTML += `</tr>`;
    });

    tableBody.innerHTML = bodyHTML;

    document.getElementById('tableContainer').classList.remove('hidden');
    document.getElementById('emptyState').classList.add('hidden');
}

// Render single branch table
function renderSingleBranchTable(products) {
    if (!products || products.length === 0) {
        showEmpty();
        return;
    }

    const tableHeader = document.getElementById('tableHeader');
    const tableBody = document.getElementById('tableBody');

    // Build header
    tableHeader.innerHTML = `
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Código</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Producto</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Laboratorio</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Categoría</th>
        <th class="px-2 py-2 text-center text-xs font-bold uppercase tracking-wider">Cantidad</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Presentación</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Sucursal</th>
        <th class="px-2 py-2 text-left text-xs font-bold uppercase tracking-wider">Fecha</th>
        <th class="px-2 py-2 text-center text-xs font-bold uppercase tracking-wider">Acciones</th>
    `;

    // Build body
    let bodyHTML = '';

    products.forEach(product => {
        const urgentClass = product.es_urgente ? 'bg-red-50 border-l-4 border-red-500' : '';
        const fecha = new Date(product.fecha_pedido).toLocaleDateString('es-GT');

        bodyHTML += `<tr class="hover:bg-slate-50 transition-colors ${urgentClass}">`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-700">${escapeHtml(product.codigo_interno || '-')}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs font-medium text-slate-900">`;

        if (product.es_urgente) {
            bodyHTML += `<span class="inline-block px-1 py-0.5 bg-red-100 text-red-700 text-xs font-bold rounded mr-1 urgent-badge">URG</span>`;
        }

        bodyHTML += `${escapeHtml(product.nombre_comercial)}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-600">${escapeHtml(product.laboratorio || '-')}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-600">${escapeHtml(product.categoria || 'Sin categoría')}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs font-semibold text-center text-blue-700">${product.cantidad_solicitada}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-600">${escapeHtml(product.presentacion_solicitada)}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-600">${escapeHtml(product.sucursal_nombre)}</td>`;
        bodyHTML += `<td class="px-2 py-2 text-xs text-slate-500">${fecha}</td>`;

        // Actions column - delete button
        bodyHTML += `<td class="px-2 py-2 text-center">`;
        bodyHTML += `<button onclick="showDeleteModal(${product.producto_id}, ${product.sucursal_id}, '${escapeHtml(product.nombre_comercial).replace(/'/g, "\\'")}')"`;
        bodyHTML += ` class="inline-flex items-center justify-center w-8 h-8 bg-red-100 hover:bg-red-200 text-red-600 rounded-lg transition-all" title="Eliminar producto">`;
        bodyHTML += `<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">`;
        bodyHTML += `<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>`;
        bodyHTML += `</svg></button></td>`;

        bodyHTML += `</tr>`;
    });

    tableBody.innerHTML = bodyHTML;

    document.getElementById('tableContainer').classList.remove('hidden');
    document.getElementById('emptyState').classList.add('hidden');
}

// Export to Excel
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');
    }

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

    showToast('Éxito', 'Exportando a Excel...', 'success');
}

// Update results count
function updateResultsCount(count) {
    const countEl = document.getElementById('resultsCount');
    countEl.textContent = `${count} producto${count !== 1 ? 's' : ''}`;
}

// Show loading state
function showLoading(show) {
    const loading = document.getElementById('loadingState');
    const table = document.getElementById('tableContainer');
    const empty = document.getElementById('emptyState');

    if (show) {
        loading.classList.remove('hidden');
        table.classList.add('hidden');
        empty.classList.add('hidden');
    } else {
        loading.classList.add('hidden');
    }
}

// Show empty state
function showEmpty() {
    document.getElementById('tableContainer').classList.add('hidden');
    document.getElementById('emptyState').classList.remove('hidden');
    updateResultsCount(0);
}

// Show toast notification
function showToast(title, message, type = 'info') {
    const toast = document.getElementById('toast');
    const toastTitle = document.getElementById('toastTitle');
    const toastMessage = document.getElementById('toastMessage');
    const toastIcon = document.getElementById('toastIcon');

    const icons = {
        success: '<svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>',
        error: '<svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>',
        info: '<svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>'
    };

    toastIcon.innerHTML = icons[type] || icons.info;
    toastTitle.textContent = title;
    toastMessage.textContent = message;

    toast.classList.remove('translate-y-32');
    setTimeout(() => toast.classList.add('translate-y-32'), 3000);
}

// Escape HTML to prevent XSS
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Delete functionality
function showDeleteModal(productoId, sucursalId, productName) {
    pendingDeleteProduct = {
        producto_id: productoId,
        sucursal_id: sucursalId,
        nombre: productName
    };

    document.getElementById('deleteProductName').textContent = productName;

    // Show different info based on view mode
    if (currentViewMode === 'consolidated' && sucursalId === 0) {
        document.getElementById('deleteProductInfo').textContent =
            'Se eliminarán TODOS los pedidos de este producto en TODAS las sucursales que cumplan con los filtros actuales.';
    } else if (sucursalId > 0) {
        const branchName = branches.find(b => b.id == sucursalId)?.nombre || 'la sucursal seleccionada';
        document.getElementById('deleteProductInfo').textContent =
            `Se eliminarán los pedidos de este producto en ${branchName}.`;
    } else {
        document.getElementById('deleteProductInfo').textContent =
            'Se eliminarán los pedidos de este producto según los filtros actuales.';
    }

    document.getElementById('deleteModal').classList.remove('hidden');
}

function closeDeleteModal() {
    document.getElementById('deleteModal').classList.add('hidden');
    pendingDeleteProduct = null;
}

async function confirmDelete() {
    if (!pendingDeleteProduct) return;

    try {
        // Prepare request data
        const requestData = {
            producto_id: pendingDeleteProduct.producto_id,
            sucursal_id: pendingDeleteProduct.sucursal_id,
            ...currentFilters // Include current filters for precise deletion
        };

        const response = await fetch(API_BASE + 'delete_admin_order.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });

        const data = await response.json();

        if (data.success) {
            showToast('Éxito', data.message || 'Producto eliminado correctamente', 'success');
            closeDeleteModal();
            // Reload orders to reflect changes
            loadOrders();
        } else {
            showToast('Error', data.error || 'No se pudo eliminar el producto', 'error');
        }
    } catch (error) {
        console.error('Error deleting product:', error);
        showToast('Error', 'Error de conexión al eliminar', 'error');
    }
}
