<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reporte de Inventario por Lotes</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        :root {
            --background: 0 0% 100%;
            --foreground: 222.2 84% 4.9%;
            --primary: 222.2 47.4% 11.2%;
            --primary-foreground: 210 40% 98%;
            --border: 214.3 31.8% 91.4%;
            --input: 214.3 31.8% 91.4%;
            --ring: 222.2 84% 4.9%;
            --radius: 0.5rem;
        }
        body { background-color: hsl(var(--background)); color: hsl(var(--foreground)); font-family: Arial, sans-serif; }
        .shad-input { border: 1px solid hsl(var(--input)); background-color: hsl(var(--background)); border-radius: var(--radius); padding: 0.5rem 0.75rem; font-size: 0.875rem; }
        .shad-button { display: inline-flex; align-items: center; justify-content: center; border-radius: var(--radius); padding: 0.5rem 1rem; font-size: 0.875rem; font-weight: 500; transition: all 150ms; }
        .shad-button-primary { background-color: hsl(var(--primary)); color: hsl(var(--primary-foreground)); }
        .shad-button-primary:hover { background-color: hsl(var(--primary) / 0.9); }
        .shad-table { width: 100%; caption-side: bottom; font-size: 0.875rem; }
        .shad-table th { text-align: left; padding: 0.75rem; border-bottom: 1px solid hsl(var(--border)); font-weight: 500; white-space: nowrap; }
        .shad-table td { padding: 0.75rem; border-bottom: 1px solid hsl(var(--border)); white-space: nowrap; }
        .shad-table td.stock-col { text-align: center; font-weight: 500; }
    </style>
</head>
<body class="p-6 md:p-10">

    <div class="max-w-full mx-auto">
        <h1 class="text-3xl font-bold mb-6">Reporte de Inventario Pivotado por Sucursal</h1>
        
        <form id="filter-form" class="flex flex-col md:flex-row gap-4 mb-6 p-4 border rounded-lg">
            <div class="flex-1">
                <label for="fecha_inicio" class="block text-sm font-medium mb-1">Creación Lote (Desde):</label>
                <input type="date" id="fecha_inicio" name="fecha_inicio" class="shad-input w-full">
            </div>
            <div class="flex-1">
                <label for="fecha_fin" class="block text-sm font-medium mb-1">Creación Lote (Hasta):</label>
                <input type="date" id="fecha_fin" name="fecha_fin" class="shad-input w-full">
            </div>
            <div class="flex items-end gap-2">
                <button type="submit" class="shad-button shad-button-primary w-full md:w-auto">
                    <i data-lucide="filter" class="w-4 h-4 mr-2"></i>
                    Filtrar
                </button>
                <button type="button" id="export-btn" class="shad-button shad-button-primary w-full md:w-auto" style="background-color: #1D6F42; color: white;">
                    <i data-lucide="file-down" class="w-4 h-4 mr-2"></i>
                    Exportar a Excel
                </button>
            </div>
        </form>

        <div class="border rounded-lg overflow-x-auto">
            <table class="shad-table" id="results-table">
                <thead class="bg-gray-50">
                    </thead>
                <tbody>
                    <tr>
                        <td colspan="10" class="text-center text-gray-500 py-12">Use los filtros para cargar los datos.</td>
                    </tr>
                </tbody>
            </table>
            <div id="loading" class="text-center py-12 text-gray-500 hidden">
                <i data-lucide="loader-2" class="w-8 h-8 mx-auto animate-spin"></i>
                <p>Cargando...</p>
            </div>
        </div>
    </div>

    <script>
        lucide.createIcons();

        const form = document.getElementById('filter-form');
        const exportBtn = document.getElementById('export-btn');
        const table = document.getElementById('results-table');
        const tableHead = table.querySelector('thead');
        const tableBody = table.querySelector('tbody');
        const loading = document.getElementById('loading');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(form);
            const params = new URLSearchParams(formData);
            
            tableHead.innerHTML = ''; // Limpiar cabeceras
            tableBody.innerHTML = ''; // Limpiar cuerpo
            loading.classList.remove('hidden');

            try {
                const response = await fetch(`api.php?${params.toString()}`);
                const result = await response.json();
                loading.classList.add('hidden');

                if (result.success && result.data.length > 0) {
                    
                    // 1. Construir Cabeceras Dinámicas
                    const headerRow = document.createElement('tr');
                    const staticHeaders = [
                        'Cod. Interno', 'Nombre Comercial', 'Laboratorio', 'Lote', 
                        'Se Factura?', 'Fecha Creación', 'Presentación', 
                        'Costo Unidad', 'Costo Unidad S/IVA'
                    ];
                    
                    staticHeaders.forEach(text => {
                        const th = document.createElement('th');
                        th.textContent = text;
                        headerRow.appendChild(th);
                    });
                    
                    // Añadir cabeceras de sucursales
                    result.sucursales.forEach(sucursalName => {
                        const th = document.createElement('th');
                        th.textContent = sucursalName;
                        th.classList.add('stock-col'); // Para centrar
                        headerRow.appendChild(th);
                    });
                    
                    // Añadir cabecera de Total
                    const thTotal = document.createElement('th');
                    thTotal.textContent = 'Stock Total';
                    thTotal.classList.add('stock-col');
                    headerRow.appendChild(thTotal);
                    
                    tableHead.appendChild(headerRow);

                    // 2. Construir Filas de Datos
                    result.data.forEach(row => {
                        const tr = document.createElement('tr');
                        
                        // Añadir celdas estáticas
                        tr.innerHTML = `
                            <td>${row.CodigoInterno || ''}</td>
                            <td>${row.NombreComercial}</td>
                            <td>${row.laboratorio || ''}</td>
                            <td>${row.codigo_lote}</td>
                            <td>${row.sefactura_texto}</td>
                            <td>${row.fechacreacion}</td>
                            <td>${row.presentacion}</td>
                            <td>${row.CostoUnidad || '0.00'}</td>
                            <td>${row.CostoUnidadSinIva || '0.00'}</td>
                        `;
                        
                        // Añadir celdas de stock de sucursal (en el orden correcto)
                        result.sucursales.forEach(sucursalName => {
                            const td = document.createElement('td');
                            td.textContent = row[sucursalName] || 0; // Usar el nombre de la sucursal como clave
                            td.classList.add('stock-col');
                            tr.appendChild(td);
                        });
                        
                        // Añadir celda de Total
                        const tdTotal = document.createElement('td');
                        tdTotal.textContent = row.StockTotal;
                        tdTotal.classList.add('stock-col');
                        tr.appendChild(tdTotal);
                        
                        tableBody.appendChild(tr);
                    });

                } else if (result.success) {
                    tableHead.innerHTML = '';
                    tableBody.innerHTML = '<tr><td colspan="10" class="text-center text-gray-500 py-12">No se encontraron resultados.</td></tr>';
                } else {
                    tableHead.innerHTML = '';
                    tableBody.innerHTML = `<tr><td colspan="10" class="text-center text-red-500 py-12">Error: ${result.message}</td></tr>`;
                }
            } catch (error) {
                loading.classList.add('hidden');
                tableHead.innerHTML = '';
                tableBody.innerHTML = `<tr><td colspan="10" class="text-center text-red-500 py-12">Error de conexión con la API.</td></tr>`;
                console.error('Error fetching data:', error);
            }
        });

        exportBtn.addEventListener('click', () => {
            const formData = new FormData(form);
            const params = new URLSearchParams(formData);
            window.location.href = `export.php?${params.toString()}`;
        });
    </script>
</body>
</html>