/**
 * Sistema de Pedidos - Sufarma
 * JavaScript Principal
 */

// Estado de la aplicación
const appState = {
    sucursalId: null, // Se cargará desde la API
    usuarioId: null,
    orderItems: [],
    searchTimeout: null,
    historySearchTimeout: null, // Timeout para el filtro de historial
    currentPage: 1,
    totalPages: 1,
    totalProducts: 0,
    productsPerPage: 20,
    currentSearch: ''
};

// Configuración de la API
const API_BASE = 'api/';

// ============================================
// Inicialización
// ============================================

document.addEventListener('DOMContentLoaded', function () {
    loadCurrentBranch(); // Cargar sucursal configurada
    loadUsers();
    // loadOrders() y loadProducts() se llamarán después de obtener la sucursal
    initializeEventListeners();
});

// ============================================
// Event Listeners
// ============================================

function initializeEventListeners() {
    // Búsqueda con debounce (Buscador Principal)
    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', function (e) {
        clearTimeout(appState.searchTimeout);
        const query = e.target.value.trim();

        appState.currentSearch = query;
        appState.currentPage = 1;

        showLoader(true);
        appState.searchTimeout = setTimeout(() => {
            loadProducts();
        }, 300);
    });

    // Selector de usuario
    const usuarioSelect = document.getElementById('usuarioSelect');
    if (usuarioSelect) {
        usuarioSelect.addEventListener('change', function (e) {
            appState.usuarioId = e.target.value;
        });
    }

    // Botón de enviar pedido
    const submitBtn = document.getElementById('submitOrder');
    if (submitBtn) {
        submitBtn.addEventListener('click', submitOrder);
    }

    // Filtros de historial - LABORATORIO (Input con debounce)
    const filterLab = document.getElementById('filterLab');
    if (filterLab) {
        filterLab.addEventListener('input', function () {
            clearTimeout(appState.historySearchTimeout);

            // Recargamos el historial después de 400ms de que el usuario deje de escribir
            appState.historySearchTimeout = setTimeout(() => {
                historyState.currentPage = 1;
                loadOrders();
            }, 400);
        });
    }

    // Filtros de historial - CATEGORIA
    const filterCat = document.getElementById('filterCat');
    if (filterCat) {
        filterCat.addEventListener('change', function () {
            historyState.currentPage = 1;
            loadOrders();
        });
    }

    // Botón de refrescar historial
    const refreshBtn = document.getElementById('refreshHistoryBtn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', async function () {
            // 1. Animación: Hacemos girar el icono
            const icon = this.querySelector('svg');
            if (icon) icon.classList.add('animate-spin');

            // 2. Acción: Recargamos los pedidos
            await loadOrders();

            // 3. Finalizar: Quitamos la animación después de un momento y mostramos mensaje
            setTimeout(() => {
                if (icon) icon.classList.remove('animate-spin');
                showToast('Actualizado', 'Historial recargado correctamente', 'success');
            }, 500);
        });
    }

    // Botón de exportar a Excel
    const exportBtn = document.getElementById('exportExcelBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', function () {
            exportToExcel();
        });
    }

    // NUEVO: Delegación de eventos para el botón ELIMINAR
    // Esto soluciona el problema de que el botón "no haga nada"
    const orderHistoryContainer = document.getElementById('orderHistory');
    if (orderHistoryContainer) {
        orderHistoryContainer.addEventListener('click', function (e) {
            // Buscamos si el clic fue en el botón de eliminar o en el icono dentro de él
            const deleteBtn = e.target.closest('.btn-delete-product');

            if (deleteBtn) {
                // Obtenemos el ID del atributo data-id
                const id = deleteBtn.dataset.id;
                if (id) {
                    deleteOrderDetail(id);
                }
            }
        });
    }
}

// ============================================
// Cargar Datos Iniciales
// ============================================

async function loadCurrentBranch() {
    try {
        const response = await fetch(API_BASE + 'get_current_branch.php');
        const data = await response.json();

        if (data.success) {
            appState.sucursalId = data.data.id;

            // Actualizar UI
            const branchNameElement = document.getElementById('branchName');
            if (branchNameElement) {
                branchNameElement.textContent = data.data.nombre;
            }

            // Cargar datos dependientes de la sucursal
            loadOrders();
            loadProducts();
            loadFilters();

        } else {
            showToast('Error', 'No se pudo cargar la configuración de sucursal', 'error');
            console.error('Error config sucursal:', data.error);
        }
    } catch (error) {
        console.error('Error al cargar sucursal:', error);
        showToast('Error', 'Error de conexión al cargar configuración', 'error');
    }
}

async function loadUsers() {
    try {
        const response = await fetch(API_BASE + 'get_users.php');
        const data = await response.json();

        if (data.success) {
            window.cachedUsers = data.data;
        }
    } catch (error) {
        console.error('Error al cargar usuarios:', error);
    }
}

async function loadFilters() {
    try {
        const response = await fetch(API_BASE + 'get_filters.php');
        const data = await response.json();

        if (data.success) {
            // Solo cargamos categorías, el laboratorio ahora es manual
            const filterCat = document.getElementById('filterCat');

            if (filterCat) {
                // Keep first option
                const firstOption = filterCat.options[0];
                filterCat.innerHTML = '';
                filterCat.appendChild(firstOption);

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

// State for product history pagination
const historyState = {
    currentPage: 1,
    totalPages: 1,
    productsPerPage: 15
};

async function loadOrders() {
    try {
        // Ya no enviamos sucursal_id, el backend lo toma de la config
        const page = historyState.currentPage;
        const limit = historyState.productsPerPage;

        // Get filter values
        const lab = document.getElementById('filterLab')?.value || '';
        const cat = document.getElementById('filterCat')?.value || 0;

        const url = `${API_BASE}get_ordered_products.php?page=${page}&limit=${limit}&search=${encodeURIComponent(lab)}&categoria_id=${cat}`;

        const response = await fetch(url);
        const data = await response.json();

        if (data.success) {
            renderProductHistory(data.data, data.pagination);
        }
    } catch (error) {
        console.error('Error al cargar productos pedidos:', error);
    }
}

function renderProductHistory(products, pagination) {
    const container = document.getElementById('orderHistory');

    if (!products || products.length === 0) {
        container.innerHTML = `
            <div class="text-center py-8 text-slate-400">
                <svg class="w-12 h-12 mx-auto mb-3 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                </svg>
                <p class="text-sm font-medium">No hay productos pedidos</p>
            </div>
        `;
        return;
    }

    // Update pagination state
    historyState.totalPages = pagination.total_pages;

    // Header Row
    let html = `
        <div class="grid grid-cols-12 gap-2 px-2 py-2 bg-slate-100 rounded-t-lg border-b border-slate-200 text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">
            <div class="col-span-4">Producto y Laboratorio</div>
            <div class="col-span-2 text-center">Cant.</div>
            <div class="col-span-3">Solicita</div>
            <div class="col-span-2 text-right">Fecha</div>
            <div class="col-span-1 text-center"></div>
        </div>
    `;

    products.forEach(product => {
        const fecha = new Date(product.fecha_pedido);
        const fechaStr = fecha.toLocaleDateString('es-GT', { month: 'short', day: 'numeric' });
        const horaStr = fecha.toLocaleTimeString('es-GT', { hour: '2-digit', minute: '2-digit' });

        html += `
            <div class="border-b border-slate-100 py-2 hover:bg-slate-50 transition-colors text-xs">
                <div class="grid grid-cols-12 gap-2 items-center">
                    <div class="col-span-4 min-w-0">
                        <p class="font-bold text-slate-800 truncate" title="${escapeHtml(product.nombre_comercial)}">
                            ${product.nombre_comercial || 'Sin nombre'}
                        </p>
                        <p class="text-[10px] text-slate-500 truncate">${product.laboratorio || ''}</p>
                        ${product.es_urgente ? '<span class="text-[10px] px-1.5 py-0.5 bg-red-100 text-red-700 rounded font-bold inline-block mt-0.5">Urgente</span>' : ''}
                    </div>

                    <div class="col-span-2 text-center">
                        <span class="font-bold text-indigo-600 text-sm">${product.cantidad_solicitada}</span>
                        <span class="text-[9px] text-slate-500 block">${product.presentacion_solicitada ? product.presentacion_solicitada.substring(0, 3) : ''}</span>
                    </div>

                    <div class="col-span-3 truncate" title="${escapeHtml(product.usuario_nombre)}">
                        ${product.usuario_nombre || 'N/A'}
                    </div>

                    <div class="col-span-2 text-right">
                        <p class="text-slate-700 font-medium">${fechaStr}</p>
                        <p class="text-[9px] text-slate-400">${horaStr}</p>
                    </div>

                    <div class="col-span-1 flex justify-center">
                        <button 
                            data-id="${product.id}"
                            class="btn-delete-product p-1.5 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
                            title="Eliminar del pedido">
                            <svg class="w-4 h-4 pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <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>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        `;
    });

    // Add pagination controls
    if (pagination.total_pages > 1) {
        html += `
            <div class="flex items-center justify-between mt-4 pt-3 border-t border-slate-200">
                <button 
                    onclick="changeHistoryPage(${pagination.current_page - 1})"
                    ${!pagination.has_prev ? 'disabled' : ''}
                    class="px-3 py-1.5 bg-slate-100 text-slate-700 rounded text-xs font-medium hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                    ← Ant
                </button>
                <span class="text-xs text-slate-600">
                    ${pagination.current_page} / ${pagination.total_pages}
                </span>
                <button 
                    onclick="changeHistoryPage(${pagination.current_page + 1})"
                    ${!pagination.has_next ? 'disabled' : ''}
                    class="px-3 py-1.5 bg-slate-100 text-slate-700 rounded text-xs font-medium hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                    Sig →
                </button>
            </div>
        `;
    }

    container.innerHTML = html;
}

function changeHistoryPage(page) {
    if (page < 1 || page > historyState.totalPages) return;
    historyState.currentPage = page;
    loadOrders();
}

/**
 * Eliminar un producto del historial de pedidos
 * @param {number} detalleId ID del registro en detalle_pedidos
 */
async function deleteOrderDetail(detalleId) {
    if (!confirm('¿Estás seguro de que deseas eliminar este producto del pedido?')) {
        return;
    }

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

        const data = await response.json();

        if (data.success) {
            showToast('Eliminado', 'Producto eliminado del pedido', 'success');

            // Recargamos el historial para que desaparezca
            loadOrders();

            // Recargamos los productos en el buscador por si el producto eliminado 
            // estaba visible ahí (para que el botón cambie de "Actualizar" a "Agregar")
            if (appState.currentSearch !== '' || document.getElementById('searchResults').children.length > 0) {
                loadProducts();
            }
        } else {
            showToast('Error', data.error || 'No se pudo eliminar el producto', 'error');
        }
    } catch (error) {
        console.error('Error al eliminar:', error);
        showToast('Error', 'Error de conexión', 'error');
    }
}

/**
 * Exportar historial de pedidos a Excel
 */
function exportToExcel() {
    // Obtener valores de filtros actuales
    const lab = document.getElementById('filterLab')?.value || '';
    const cat = document.getElementById('filterCat')?.value || 0;

    // Construir URL con los mismos filtros que la vista actual
    const url = `${API_BASE}export_orders.php?search=${encodeURIComponent(lab)}&categoria_id=${cat}`;

    // Abrir en nueva ventana para descargar
    window.open(url, '_blank');

    showToast('Exportando', 'Generando archivo Excel...', 'info');
}

// ============================================
// Carga y Búsqueda de Productos con Paginación
// ============================================

async function loadProducts() {
    try {
        // Ya no enviamos sucursal_id
        const search = appState.currentSearch;
        const page = appState.currentPage;
        const limit = appState.productsPerPage;

        const url = `${API_BASE}get_all_products.php?page=${page}&limit=${limit}&search=${encodeURIComponent(search)}`;

        const response = await fetch(url);
        const data = await response.json();

        showLoader(false);

        if (data.success) {
            // Update pagination state
            appState.totalPages = data.pagination.total_pages;
            appState.totalProducts = data.pagination.total_products;

            // Render products
            renderSearchResults(data.data);

            // Render pagination controls
            renderPagination(data.pagination);
        } else {
            showToast('Error', data.error || 'Error al cargar productos', 'error');
        }
    } catch (error) {
        showLoader(false);
        console.error('Error al cargar productos:', error);
        showToast('Error', 'Error al cargar productos', 'error');
    }
}

function renderPagination(pagination) {
    const container = document.getElementById('paginationControls');
    if (!container) return;

    const { current_page, total_pages, showing_from, showing_to, total_products, has_prev, has_next } = pagination;

    let html = `
        <div class="flex items-center justify-between px-6 py-4 bg-white border-t-2 border-slate-200">
            <div class="text-sm text-slate-600">
                Mostrando <span class="font-semibold">${showing_from}-${showing_to}</span> de <span class="font-semibold">${total_products}</span> productos
            </div>
            
            <div class="flex items-center gap-2">
                <button 
                    onclick="changePage(${current_page - 1})"
                    ${!has_prev ? 'disabled' : ''}
                    class="px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
                >
                    ← Anterior
                </button>
                
                <div class="flex items-center gap-1">
    `;

    // Page numbers
    const maxButtons = 5;
    let startPage = Math.max(1, current_page - Math.floor(maxButtons / 2));
    let endPage = Math.min(total_pages, startPage + maxButtons - 1);

    if (endPage - startPage < maxButtons - 1) {
        startPage = Math.max(1, endPage - maxButtons + 1);
    }

    if (startPage > 1) {
        html += `<button onclick="changePage(1)" class="px-3 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 transition-colors">1</button>`;
        if (startPage > 2) {
            html += `<span class="px-2 text-slate-400">...</span>`;
        }
    }

    for (let i = startPage; i <= endPage; i++) {
        const isActive = i === current_page;
        html += `
            <button 
                onclick="changePage(${i})"
                class="px-3 py-2 ${isActive ? 'bg-indigo-600 text-white' : 'bg-slate-100 text-slate-700 hover:bg-slate-200'} rounded-lg transition-colors font-medium"
            >
                ${i}
            </button>
        `;
    }

    if (endPage < total_pages) {
        if (endPage < total_pages - 1) {
            html += `<span class="px-2 text-slate-400">...</span>`;
        }
        html += `<button onclick="changePage(${total_pages})" class="px-3 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 transition-colors">${total_pages}</button>`;
    }

    html += `
                </div>
                
                <button 
                    onclick="changePage(${current_page + 1})"
                    ${!has_next ? 'disabled' : ''}
                    class="px-4 py-2 bg-slate-100 text-slate-700 rounded-lg hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium"
                >
                    Siguiente →
                </button>
            </div>
            
            <select 
                onchange="changePerPage(parseInt(this.value))"
                class="px-3 py-2 bg-slate-100 border-2 border-slate-200 rounded-lg focus:border-indigo-500 focus:ring-2 focus:ring-indigo-100 transition-all outline-none text-sm"
            >
                <option value="20" ${appState.productsPerPage === 20 ? 'selected' : ''}>20 por página</option>
                <option value="50" ${appState.productsPerPage === 50 ? 'selected' : ''}>50 por página</option>
                <option value="100" ${appState.productsPerPage === 100 ? 'selected' : ''}>100 por página</option>
            </select>
        </div>
    `;

    container.innerHTML = html;
}

function changePage(page) {
    if (page < 1 || page > appState.totalPages) return;
    appState.currentPage = page;
    loadProducts();
    // Scroll to top of results
    document.getElementById('searchResults').scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function changePerPage(perPage) {
    appState.productsPerPage = perPage;
    appState.currentPage = 1; // Reset to first page
    loadProducts();
}

function renderSearchResults(products) {
    const container = document.getElementById('searchResults');
    container.innerHTML = '';

    if (products.length === 0) {
        container.innerHTML = `
            <div class="text-center py-8 text-slate-400">
                <p class="font-medium">No se encontraron productos</p>
                <p class="text-sm mt-1">Intenta con otro término de búsqueda</p>
            </div>
        `;
        return;
    }

    // Header Row
    const headerHtml = `
        <div class="grid grid-cols-12 gap-2 px-3 py-2 bg-slate-100 rounded-t-lg border-b border-slate-200 text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2">
            <div class="col-span-3">Producto</div>
            <div class="col-span-1 text-center">Prioridad</div>
            <div class="col-span-1">Exist</div>
            <div class="col-span-1">Pres</div>
            <div class="col-span-1">Requerido</div>
            <div class="col-span-1">Pres</div>
            <div class="col-span-2">Quien Solicita</div>
            <div class="col-span-1">Acción</div>
        </div>
    `;

    container.innerHTML = headerHtml;

    products.forEach(product => {
        container.appendChild(createProductCard(product));
    });
}

function createProductCard(product) {
    const isOrdered = !!product.detalle_id;

    const div = document.createElement('div');
    div.className = `product-row bg-white border ${isOrdered ? 'border-orange-300 bg-orange-50' : 'border-slate-200'} rounded-lg p-3 hover:shadow-md transition-all duration-200`;
    div.dataset.productId = product.id;
    if (isOrdered) {
        div.dataset.detalleId = product.detalle_id;
    }

    // Get users list for selector
    const usersHtml = `
        <option value="">Seleccionar...</option>
        ${window.cachedUsers ? window.cachedUsers.map(user =>
        `<option value="${user.id}" ${isOrdered && product.pedido_usuario_id == user.id ? 'selected' : ''}>${user.nombre}</option>`
    ).join('') : ''}
    `;

    div.innerHTML = `
        <div class="grid grid-cols-12 gap-2 items-center text-sm">
            <div class="col-span-3">
                <div class="flex items-center gap-2">
                    ${isOrdered ? '<span class="flex-shrink-0 w-2 h-2 bg-orange-500 rounded-full" title="Ya en pedido"></span>' : ''}
                    <div class="min-w-0">
                        <h4 class="font-bold text-slate-800 truncate" title="${escapeHtml(product.NombreComercial)}">${product.NombreComercial || 'Sin nombre'}</h4>
                        <p class="text-xs text-slate-600 truncate">${product.laboratorio || ''}</p>
                        <div class="flex gap-1 mt-1">
                            ${product.CodigoInterno ? `<span class="text-[10px] px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded font-mono">INT:${product.CodigoInterno}</span>` : ''}
                            ${product.CodigoBarra ? `<span class="text-[10px] px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded font-mono">BAR:${product.CodigoBarra}</span>` : ''}
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-span-1 flex justify-center">
                <label class="toggle-switch-small cursor-pointer" title="Marcar como urgente">
                    <input type="checkbox" class="urgente-checkbox" ${isOrdered && product.pedido_urgente == 1 ? 'checked' : ''}>
                    <span class="toggle-slider-small"></span>
                </label>
            </div>

            <div class="col-span-1">
                <input type="number" min="0" 
                    value="${isOrdered ? product.pedido_existencia : 0}"
                    class="existencia-input w-full px-2 py-1 text-xs border border-slate-200 rounded focus:border-blue-500 focus:ring-1 focus:ring-blue-100 outline-none"
                    placeholder="Exist.">
            </div>

            <div class="col-span-1">
                <select class="presentacion-actual-select w-full px-2 py-1 text-xs border border-slate-200 rounded focus:border-blue-500 focus:ring-1 focus:ring-blue-100 outline-none">
                    ${['UNIDAD', 'BLISTER', 'CAJA', 'BOTE', 'PAQUETE'].map(pres =>
        `<option value="${pres}" ${isOrdered && product.pedido_pres_actual === pres ? 'selected' : ''}>${pres.substring(0, 3)}</option>`
    ).join('')}
                </select>
            </div>

            <div class="col-span-1">
                <input type="number" min="1" 
                    value="${isOrdered ? product.pedido_cantidad : 1}"
                    class="cantidad-input w-full px-2 py-1 text-xs border-2 border-indigo-200 rounded focus:border-indigo-500 focus:ring-1 focus:ring-indigo-100 outline-none font-semibold"
                    placeholder="Cant.">
            </div>

            <div class="col-span-1">
                <select class="presentacion-solicitada-select w-full px-2 py-1 text-xs border border-slate-200 rounded focus:border-indigo-500 focus:ring-1 focus:ring-indigo-100 outline-none">
                    ${['UNIDAD', 'BLISTER', 'CAJA', 'BOTE', 'PAQUETE'].map(pres =>
        `<option value="${pres}" ${isOrdered && product.pedido_pres_solicitada === pres ? 'selected' : ''}>${pres.substring(0, 3)}</option>`
    ).join('')}
                </select>
            </div>

            <div class="col-span-2">
                <select class="usuario-select w-full px-2 py-1 text-xs border border-slate-200 rounded focus:border-blue-500 focus:ring-1 focus:ring-blue-100 outline-none">
                    ${usersHtml}
                </select>
            </div>

            <div class="col-span-2">
                ${isOrdered ? `
                    <div class="flex gap-1">
                        <button 
                            onclick="updateProductInOrder(${product.detalle_id}, ${product.id})"
                            class="flex-1 px-3 py-1.5 bg-gradient-to-r from-orange-500 to-orange-600 text-white text-xs font-bold rounded-lg hover:shadow-md transition-all duration-200"
                        >
                            Actualizar
                        </button>
                        <button 
                            onclick="deleteOrderDetail(${product.detalle_id})"
                            class="px-2 py-1.5 bg-gradient-to-r from-red-500 to-red-600 text-white rounded-lg hover:shadow-md transition-all duration-200"
                            title="Eliminar del pedido"
                        >
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <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>
                            </svg>
                        </button>
                    </div>
                ` : `
                    <button 
                        onclick="addProductToOrder(${product.id}, '${escapeHtml(product.NombreComercial)}', '${escapeHtml(product.laboratorio)}', '${escapeHtml(product.CodigoInterno)}', '${escapeHtml(product.CodigoBarra)}')"
                        class="w-full px-3 py-1.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-xs font-bold rounded-lg hover:shadow-md transition-all duration-200"
                    >
                        + Agregar
                    </button>
                `}
            </div>
        </div>
    `;

    return div;
}

// ============================================
// Gestión del Pedido
// ============================================

async function addProductToOrder(productId, nombre, laboratorio, codigoInterno, codigoBarra) {
    // Get current values from the row
    const row = document.querySelector(`[data-product-id="${productId}"]`);
    if (!row) return;

    const urgente = row.querySelector('.urgente-checkbox').checked ? 1 : 0;
    const existenciaActual = parseInt(row.querySelector('.existencia-input').value) || 0;
    const presentacionActual = row.querySelector('.presentacion-actual-select').value;
    const cantidadSolicitada = parseInt(row.querySelector('.cantidad-input').value) || 1;
    const presentacionSolicitada = row.querySelector('.presentacion-solicitada-select').value;
    const usuarioId = row.querySelector('.usuario-select').value;

    // Validate user selection
    if (!usuarioId) {
        showToast('Error', 'Debe seleccionar un usuario para este producto', 'error');
        return;
    }

    // Disable button to prevent double submit
    const btn = row.querySelector('button');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="animate-spin inline-block w-3 h-3 border-2 border-white border-t-transparent rounded-full mr-1"></span> Guardando...';

    // Prepare data for immediate save
    const orderData = {
        usuario_id: usuarioId,
        observaciones: '', // Observaciones opcionales por producto no están en UI, se envía vacío
        productos: [{
            producto_id: productId,
            nombre_comercial: nombre,
            laboratorio: laboratorio,
            codigo_interno: codigoInterno,
            codigo_barra: codigoBarra,
            es_urgente: urgente,
            existencia_actual: existenciaActual,
            presentacion_actual: presentacionActual,
            cantidad_solicitada: cantidadSolicitada,
            presentacion_solicitada: presentacionSolicitada
        }]
    };

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

        const data = await response.json();

        if (data.success) {
            showToast('Éxito', 'Producto guardado correctamente', 'success');

            // Reload history to show the new order
            loadOrders();

            // Optional: Reset inputs or give visual feedback
            row.querySelector('.cantidad-input').value = 1;

        } else {
            showToast('Error', data.error || 'Error al guardar el pedido', 'error');
        }

    } catch (error) {
        console.error('Error al enviar pedido:', error);
        showToast('Error', 'Error de conexión al guardar', 'error');
    } finally {
        // Re-enable button
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}

async function updateProductInOrder(detalleId, productId) {
    // Get current values from the row
    const row = document.querySelector(`[data-product-id="${productId}"]`);
    if (!row) return;

    const urgente = row.querySelector('.urgente-checkbox').checked ? 1 : 0;
    const existenciaActual = parseInt(row.querySelector('.existencia-input').value) || 0;
    const presentacionActual = row.querySelector('.presentacion-actual-select').value;
    const cantidadSolicitada = parseInt(row.querySelector('.cantidad-input').value) || 1;
    const presentacionSolicitada = row.querySelector('.presentacion-solicitada-select').value;
    const usuarioId = row.querySelector('.usuario-select').value;

    // Validate user selection
    if (!usuarioId) {
        showToast('Error', 'Debe seleccionar un usuario', 'error');
        return;
    }

    // Disable button
    const btn = row.querySelector('button');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="animate-spin inline-block w-3 h-3 border-2 border-white border-t-transparent rounded-full mr-1"></span> ...';

    const updateData = {
        detalle_id: detalleId,
        usuario_id: usuarioId,
        es_urgente: urgente,
        existencia_actual: existenciaActual,
        presentacion_actual: presentacionActual,
        cantidad_solicitada: cantidadSolicitada,
        presentacion_solicitada: presentacionSolicitada
    };

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

        const data = await response.json();

        if (data.success) {
            showToast('Éxito', 'Pedido actualizado correctamente', 'success');
            loadOrders(); // Reload history
        } else {
            showToast('Error', data.error || 'Error al actualizar', 'error');
        }

    } catch (error) {
        console.error('Error al actualizar:', error);
        showToast('Error', 'Error de conexión', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}

function removeProductFromOrder(productId) {
    const index = appState.orderItems.findIndex(item => item.producto_id === productId);
    if (index !== -1) {
        appState.orderItems.splice(index, 1);

        // Re-render products to update button
        const query = appState.currentSearch;
        if (query || appState.currentPage) {
            loadProducts();
        }

        updateItemCount();
        updateOrderActionsVisibility();
        showToast('Éxito', 'Producto eliminado del pedido', 'success');
    }
}

// ============================================
// Utilidades
// ============================================

function showLoader(show) {
    const loader = document.getElementById('searchLoader');
    if (show) {
        loader.classList.remove('hidden');
    } else {
        loader.classList.add('hidden');
    }
}

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');

    // Iconos según tipo
    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>',
        warning: '<svg class="w-6 h-6 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></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;

    // Mostrar toast
    toast.style.transform = 'translateY(0)';

    // Ocultar después de 3 segundos
    setTimeout(() => {
        toast.style.transform = 'translateY(8rem)';
    }, 3000);
}

function escapeHtml(text) {
    if (!text) return '';
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, m => map[m]);
}