<?php
// 1. CONFIGURACIÓN Y CODIFICACIÓN
header('Content-Type: text/html; charset=utf-8');
session_start();

if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso Denegado");
}

// Variables de Configuración Dinámica
$prefijo = isset($IDU) ? $IDU : ($_SESSION['IDU'] ?? '101'); 
$nombre_bd = "MS_Datos";

$tb_cat = $prefijo . "-Productos_Catalogo"; 
$tb_inv = $prefijo . "-Productos_Inventario"; 
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    /* --- ESTILOS GENERALES Y DASHBOARD --- */
    body { background-color: #f4f7f6; }
    
    /* Métricas Superiores */
    .card-metric {
        border: none; border-radius: 12px; transition: transform 0.2s;
        background: white; box-shadow: 0 4px 6px rgba(0,0,0,0.05);
    }
    .card-metric:hover { transform: translateY(-3px); }

    /* Tabla Estilizada */
    .table-inv thead th {
        font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1px;
        color: #6c757d; border-bottom: 2px solid #e9ecef; background: #f8f9fa;
    }
    .stock-pill { padding: 4px 10px; border-radius: 20px; font-weight: 700; font-size: 0.85rem; }
    .stock-ok { background: #d1fae5; color: #065f46; }
    .stock-low { background: #fee2e2; color: #991b1b; }

    /* --- MODAL WIDESCREEN (98% Ancho) --- */
    .modal-fullscreen { padding-right: 0 !important; }
    .modal-fullscreen .modal-dialog {
        width: 98%; max-width: 98%; margin: 10px auto; height: 95%;
    }
    .modal-fullscreen .modal-content {
        height: 100%; border-radius: 8px; border: none; box-shadow: 0 0 20px rgba(0,0,0,0.2);
    }
    
    /* Tarjetas internas del modal */
    .card-control {
        background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; height: 100%;
    }
    .card-control-header {
        background: #f8fafc; padding: 10px 15px; border-bottom: 1px solid #e2e8f0;
        font-weight: 700; color: #475569; text-transform: uppercase; font-size: 0.8rem; letter-spacing: 0.5px;
    }
    
    /* Inputs "Hero" (Gigantes) */
    .input-hero { font-size: 1.4rem; font-weight: 800; height: 50px; }
</style>

<div class="container-fluid p-3">
    
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card card-metric p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted text-uppercase font-weight-bold">Valor Inventario (Costo)</small>
                        <h3 class="mb-0 text-dark font-weight-bold" id="kpi_valor_total">$0.00</h3>
                    </div>
                    <div class="icon-shape bg-light text-primary rounded-circle p-3"><i class="fas fa-sack-dollar fa-2x"></i></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card card-metric p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted text-uppercase font-weight-bold">Items Bajos de Stock</small>
                        <h3 class="mb-0 text-danger font-weight-bold" id="kpi_bajos">0</h3>
                    </div>
                    <div class="icon-shape bg-light text-danger rounded-circle p-3"><i class="fas fa-exclamation-triangle fa-2x"></i></div>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card card-metric p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <small class="text-muted text-uppercase font-weight-bold">Total Productos</small>
                        <h3 class="mb-0 text-dark font-weight-bold" id="kpi_total_items">0</h3>
                    </div>
                    <div class="icon-shape bg-light text-info rounded-circle p-3"><i class="fas fa-boxes fa-2x"></i></div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0 rounded-3">
        <div class="card-header bg-white py-3">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="mb-0 font-weight-bold text-dark"><i class="fas fa-warehouse mr-2"></i>Gestor de Inventario</h5>
                    <small class="text-muted">Sucursal General (Matriz - IDS: 1)</small>
                </div>
                <div class="col-md-6">
                    <div class="d-flex justify-content-end gap-2">
                         <div class="input-group" style="width: 350px;">
                            <span class="input-group-text bg-white border-right-0"><i class="fas fa-search text-muted"></i></span>
                            <input type="text" id="buscador" class="form-control border-left-0 pl-0" placeholder="Buscar SKU, Nombre...">
                             <button class="btn btn-success text-white shadow-sm mr-1" onclick="exportarExcel()"> <i class="fas fa-file-excel mr-1"></i>  </button>
                            <button class="btn btn-dark ml-2 rounded" onclick="cargarInventario()"><i class="fas fa-sync-alt"></i></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle table-inv mb-0">
                <thead>
                    <tr>
                        <th width="60" class="pl-4">Img</th>
                        <th>Producto / SKU</th>
                        <th>Ubicación</th>
                        <th class="text-center">Existencia</th>
                        <th class="text-right">Costo Unit.</th>
                        <th class="text-right">P. Público</th>
                        <th class="text-center">Margen</th>
                        <th class="text-right pr-4">Acción</th>
                    </tr>
                </thead>
                <tbody id="tabla_body"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade modal-fullscreen" id="modalEdicion" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-dark text-white py-2 align-items-center">
                <div class="d-flex align-items-center">
                    <div class="bg-success rounded-circle p-2 mr-3"><i class="fas fa-sliders-h"></i></div>
                    <div>
                        <h5 class="modal-title font-weight-bold mb-0">Gestión de Inventario & Precios</h5>
                        <small class="opacity-75" id="lbl_producto_nombre">Editando: ---</small>
                    </div>
                </div>
                <div>
                    <button type="button" class="btn btn-outline-light btn-sm mr-2" data-dismiss="modal" onclick="$('#modalEdicion').modal('hide')">Cancelar</button>
                    <button type="button" class="btn btn-success btn-sm px-4 font-weight-bold shadow" onclick="guardarCambios()">
                        <i class="fas fa-save mr-1"></i> GUARDAR CAMBIOS
                    </button>
                </div>
            </div>
            
            <div class="modal-body bg-light p-3" style="overflow-y: auto;">
                <form id="formInv">
                    <input type="hidden" id="inv_id"> 
                    
                    <div class="card shadow-sm border-0 mb-3">
                        <div class="card-body p-3">
                            <div class="row align-items-end">
                                <div class="col-lg-3 col-md-6 mb-2">
                                    <label class="text-muted small font-weight-bold text-uppercase">Costo Compra</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-white border-right-0"><i class="fas fa-tag text-muted"></i></span>
                                        <input type="number" step="0.01" class="form-control input-hero border-left-0 text-muted" id="costo_promedio" oninput="calcularMargen()" placeholder="0.00">
                                    </div>
                                </div>
                                <div class="col-lg-3 col-md-6 mb-2">
                                    <label class="text-success small font-weight-bold text-uppercase">Precio Público (Venta)</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-success text-white border-0">$</span>
                                        <input type="number" step="0.01" class="form-control input-hero border-success text-success" id="precio_venta" oninput="calcularMargen()" placeholder="0.00">
                                    </div>
                                </div>
                                <div class="col-lg-2 col-md-4 mb-2">
                                    <div class="p-2 border rounded bg-white text-center">
                                        <small class="d-block text-muted text-uppercase" style="font-size:0.7rem;">Margen Bruto</small>
                                        <span id="lbl_margen" class="font-weight-bold" style="font-size: 1.5rem;">0%</span>
                                    </div>
                                </div>
                                <div class="col-lg-4 col-md-8 mb-2">
                                    <label class="text-primary small font-weight-bold text-uppercase">Existencia Física Total</label>
                                    <div class="input-group">
                                        <input type="number" step="0.01" class="form-control input-hero border-primary text-primary font-weight-bold" id="existencia">
                                        <span class="input-group-text bg-primary text-white font-weight-bold" id="lbl_unidad" style="min-width: 60px;">Pza</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-4 col-md-12 mb-3">
                            <div class="card-control">
                                <div class="card-control-header"><i class="fas fa-tags mr-2 text-info"></i>Precios Alternativos</div>
                                <div class="card-body">
                                    <div class="form-group row mb-2">
                                        <label class="col-sm-5 col-form-label col-form-label-sm">Precio Mayoreo</label>
                                        <div class="col-sm-7">
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text bg-light">$</span>
                                                <input type="number" step="0.01" class="form-control font-weight-bold" id="precio_mayoreo">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="form-group row mb-2">
                                        <label class="col-sm-5 col-form-label col-form-label-sm text-info">Precio Web</label>
                                        <div class="col-sm-7">
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text bg-info text-white border-0"><i class="fas fa-globe"></i></span>
                                                <input type="number" step="0.01" class="form-control border-info" id="precio_web">
                                            </div>
                                        </div>
                                    </div>
                                    <hr>
                                    <div class="form-group row mb-0">
                                        <label class="col-sm-5 col-form-label col-form-label-sm">Impuesto (IVA) %</label>
                                        <div class="col-sm-7">
                                            <div class="input-group input-group-sm">
                                                <input type="number" step="0.01" class="form-control" id="impuesto_porcentaje">
                                                <span class="input-group-text">%</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-4 col-md-12 mb-3">
                            <div class="card-control">
                                <div class="card-control-header"><i class="fas fa-list-ol mr-2 text-warning"></i>Listas Especiales (1-5)</div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php for($i=1; $i<=5; $i++): ?>
                                        <div class="col-6 mb-2">
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text border-0 bg-light text-muted small" style="width: 30px;"><?php echo $i; ?></span>
                                                <input type="number" step="0.01" class="form-control" id="Precio_<?php echo $i; ?>" placeholder="$0.00">
                                            </div>
                                        </div>
                                        <?php endfor; ?>
                                        <div class="col-12 text-center mt-2">
                                            <small class="text-muted" style="font-size: 0.7rem;">Use estas listas para distribuidores o clientes VIP.</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-4 col-md-12 mb-3">
                            <div class="card-control">
                                <div class="card-control-header"><i class="fas fa-truck-loading mr-2 text-secondary"></i>Logística & Ubicación</div>
                                <div class="card-body">
                                    <div class="form-group mb-2">
                                         <div class="alert alert-light border small text-center mb-0 p-1">
                                             <i class="fas fa-building mr-1"></i> Sucursal General (IDS: 1)
                                         </div>
                                    </div>
                                    <div class="form-group mb-3">
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text bg-light" style="width: 100px;">Ubicación</span>
                                            <input type="text" class="form-control" id="ubicacion_fisica" placeholder="Pasillo/Estante">
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-6">
                                            <label class="small text-muted mb-0">Stock Mínimo</label>
                                            <input type="number" class="form-control form-control-sm border-warning" id="stock_minimo">
                                        </div>
                                        <div class="col-6">
                                            <label class="small text-muted mb-0">Stock Máximo</label>
                                            <input type="number" class="form-control form-control-sm border-info" id="stock_maximo">
                                        </div>
                                    </div>
                                    <div class="mt-3 text-right">
                                        <small class="text-danger font-weight-bold"><i class="fas fa-lock mr-1"></i>Comprometido: <span id="lbl_comprometido">0</span></small>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div> 
                </form>
            </div>
        </div>
    </div>
</div>



<script>
    // Variables de entorno para JS
    const DB = "<?php echo $nombre_bd; ?>";
    const TB_INV = "<?php echo $tb_inv; ?>";
    const TB_CAT = "<?php echo $tb_cat; ?>";
    
    document.addEventListener('DOMContentLoaded', () => {
        cargarInventario();
        // Filtro rápido de tabla
        document.getElementById('buscador').addEventListener('keyup', function(e) {
            const term = e.target.value.toLowerCase();
            document.querySelectorAll('#tabla_body tr').forEach(row => {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(term) ? '' : 'none';
            });
        });
    });

    // --- 1. CARGAR DATOS (JOIN CATALOGO + INVENTARIO) ---
    function cargarInventario() {
        const tbody = document.getElementById('tabla_body');
        tbody.innerHTML = '<tr><td colspan="8" class="text-center p-5"><i class="fas fa-circle-notch fa-spin fa-2x text-muted"></i></td></tr>';

        // JOIN IMPORTANTE: I.sku = C.sku (Conecta el catalogo)
        // FILTRO: I.IDS = 1 (Solo Sucursal General)
        const sql = `
            SELECT I.*, C.nombre, C.imagen, C.unidad_medida, C.controlar_stock, C.tipo_item
            FROM \`${TB_INV}\` I
            INNER JOIN \`${TB_CAT}\` C ON I.sku = C.sku
            WHERE I.IDS = 1
            ORDER BY I.existencia ASC LIMIT 200
        `;

        fetch('../librerias/AJAX/Select.php', {
            method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `sql=${encodeURIComponent(sql)}&db=${DB}`
        })
        .then(r => r.json())
        .then(res => {
            tbody.innerHTML = '';
            let totalValor = 0, totalItems = 0, bajosStock = 0;

            if(res.data && Array.isArray(res.data) && res.data.length > 0) {
                res.data.forEach(row => {
                    const controlaStock = parseInt(row.controlar_stock || 1); 
                    const costo = parseFloat(row.costo_promedio || 0);
                    const exist = parseFloat(row.existencia || 0);
                    const precio = parseFloat(row.precio_venta || 0);
                    const min = parseFloat(row.stock_minimo || 0);
                    
                    totalValor += (costo * exist); 
                    totalItems++;

                    if(controlaStock === 1 && exist <= min) {
                        bajosStock++;
                    }

                    const margen = precio > 0 ? ((precio - costo) / precio * 100).toFixed(1) : 0;
                    const img = (row.imagen && row.imagen.length > 3) ? row.imagen : 'https://via.placeholder.com/40';
                    
                    let stockHTML = '';
                    if(controlaStock === 0) {
                        stockHTML = `<span class="badge bg-info text-white shadow-sm" style="font-size:0.9rem"><i class="fas fa-infinity mr-1"></i> Ilimitado</span>`;
                    } else {
                        const stockClass = exist <= min ? 'stock-low' : 'stock-ok';
                        const stockIcon = exist <= min ? '<i class="fas fa-arrow-down mr-1"></i>' : '';
                        stockHTML = `<span class="stock-pill ${stockClass}">${stockIcon}${exist} ${row.unidad_medida}</span>`;
                    }

                    tbody.innerHTML += `
                        <tr>
                            <td class="pl-4"><img src="${img}" class="rounded shadow-sm" width="40" height="40" style="object-fit:contain;"></td>
                            <td>
                                <div class="font-weight-bold text-dark">${row.nombre}</div>
                                <small class="text-muted font-monospace"><i class="fas fa-barcode mr-1"></i>${row.sku}</small>
                                ${row.tipo_item === 'servicio' ? '<span class="badge badge-light border ml-1">Servicio</span>' : ''}
                            </td>
                            <td>
                                <div class="small text-dark"><i class="fas fa-map-pin text-muted mr-1"></i>${row.ubicacion_fisica || '--'}</div>
                            </td>
                            <td class="text-center">${stockHTML}</td>
                            <td class="text-right text-muted small">$${costo.toFixed(2)}</td>
                            <td class="text-right font-weight-bold text-dark">$${precio.toFixed(2)}</td>
                            <td class="text-center"><small class="badge ${margen > 30 ? 'badge-light text-success' : 'badge-light text-danger'}">${margen}%</small></td>
                            <td class="text-right pr-4">
                                <button class="btn btn-sm btn-outline-dark rounded-circle" style="width:32px;height:32px" onclick='abrirEditor(${JSON.stringify(row)})'><i class="fas fa-pen"></i></button>
                            </td>
                        </tr>
                    `;
                });
                
                document.getElementById('kpi_valor_total').innerText = '$' + totalValor.toLocaleString('en-US', {minimumFractionDigits: 2});
                document.getElementById('kpi_bajos').innerText = bajosStock; 
                document.getElementById('kpi_total_items').innerText = totalItems;
            } else {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted py-4">No hay datos en Sucursal General (IDS 1).</td></tr>';
            }
        });
    }

    // --- 2. ABRIR EDITOR ---
    function abrirEditor(data) {
        const controlaStock = parseInt(data.controlar_stock || 1);
        const setVal = (id, val) => document.getElementById(id).value = val || 0;
        const setTxt = (id, val) => document.getElementById(id).value = val || '';
        const disable = (id, status) => document.getElementById(id).disabled = status;

        document.getElementById('inv_id').value = data.IDI; // Llave primaria
        document.getElementById('lbl_producto_nombre').innerText = `SKU: ${data.sku} - ${data.nombre}`;
        document.getElementById('lbl_unidad').innerText = data.unidad_medida || 'Pza';
        document.getElementById('lbl_comprometido').innerText = data.comprometido || 0;

        const isUnlimited = (controlaStock === 0);
        
        setVal('existencia', isUnlimited ? 999999 : data.existencia); 
        setVal('stock_minimo', isUnlimited ? 0 : data.stock_minimo);
        setVal('stock_maximo', isUnlimited ? 0 : data.stock_maximo);
        
        disable('existencia', isUnlimited);
        disable('stock_minimo', isUnlimited);
        disable('stock_maximo', isUnlimited);

        if(isUnlimited) {
            document.getElementById('existencia').type = 'text'; 
            document.getElementById('existencia').value = "♾️ Ilimitado"; 
        } else {
            document.getElementById('existencia').type = 'number';
            document.getElementById('existencia').value = data.existencia;
        }

        setTxt('ubicacion_fisica', data.ubicacion_fisica);
        setVal('costo_promedio', data.costo_promedio);
        setVal('precio_venta', data.precio_venta);
        setVal('precio_mayoreo', data.precio_mayoreo);
        setVal('precio_web', data.precio_web);
        setVal('impuesto_porcentaje', data.impuesto_porcentaje);

        for(let i=1; i<=5; i++) setVal(`Precio_${i}`, data[`Precio_${i}`]);

        calcularMargen();
        $('#modalEdicion').modal('show');
    }

    // --- 3. CÁLCULO MARGEN EN TIEMPO REAL ---
    function calcularMargen() {
        const costo = parseFloat(document.getElementById('costo_promedio').value) || 0;
        const precio = parseFloat(document.getElementById('precio_venta').value) || 0;
        const lbl = document.getElementById('lbl_margen');

        if(precio > 0 && costo >= 0) {
            const margen = ((precio - costo) / precio) * 100;
            lbl.innerText = margen.toFixed(1) + "%";
            lbl.className = 'font-weight-bold';
            lbl.style.color = margen < 15 ? '#ef4444' : (margen < 30 ? '#f59e0b' : '#10b981');
        } else {
            lbl.innerText = "0%";
            lbl.style.color = '#ef4444';
        }
    }

    // --- 4. GUARDAR CAMBIOS (UPDATE) ---
    function guardarCambios() {
        const id = document.getElementById('inv_id').value;
        const existenciaInput = document.getElementById('existencia');
        
        let existVal = existenciaInput.value;
        let minVal = document.getElementById('stock_minimo').value;
        let maxVal = document.getElementById('stock_maximo').value;

        // Si es infinito, enviamos 0 para no romper la BD decimal
        if(existenciaInput.disabled) {
            existVal = 0; minVal = 0; maxVal = 0;
        }

        const d = {
            exist: existVal, min: minVal, max: maxVal,
            ubic: document.getElementById('ubicacion_fisica').value,
            costo: document.getElementById('costo_promedio').value,
            pv: document.getElementById('precio_venta').value,
            pm: document.getElementById('precio_mayoreo').value,
            pw: document.getElementById('precio_web').value,
            imp: document.getElementById('impuesto_porcentaje').value,
            p1: document.getElementById('Precio_1').value,
            p2: document.getElementById('Precio_2').value,
            p3: document.getElementById('Precio_3').value,
            p4: document.getElementById('Precio_4').value,
            p5: document.getElementById('Precio_5').value
        };

        let sql = "";
        
        // Actualizamos usando IDI
        sql = `UPDATE \`${TB_INV}\` SET 
            existencia='${d.exist}', stock_minimo='${d.min}', stock_maximo='${d.max}', 
            ubicacion_fisica='${d.ubic}', 
            costo_promedio='${d.costo}', precio_venta='${d.pv}', precio_mayoreo='${d.pm}', precio_web='${d.pw}', 
            Precio_1='${d.p1}', Precio_2='${d.p2}', Precio_3='${d.p3}', Precio_4='${d.p4}', Precio_5='${d.p5}', 
            impuesto_porcentaje='${d.imp}' 
            WHERE IDI = ${id}`;

        fetch('../librerias/AJAX/Execute.php', {
            method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `sql=${encodeURIComponent(sql)}&db=${DB}`
        })
        .then(r => r.json())
        .then(res => {
            if(res.error) Swal.fire('Error', res.error, 'error');
            else {
                Swal.fire({icon: 'success', title: 'Inventario Actualizado', toast: true, position: 'top-end', showConfirmButton: false, timer: 1500});
                $('#modalEdicion').modal('hide');
                cargarInventario();
            }
        });
    }

    // --- 5. EXPORTAR A EXCEL (Ajustado) ---
    function exportarExcel() {
        Swal.fire({
            title: 'Generando Reporte...',
            text: 'Obteniendo datos de Sucursal General.',
            allowOutsideClick: false,
            didOpen: () => { Swal.showLoading(); }
        });

        // JOIN necesario para tener el nombre del producto
        const sql = `
            SELECT I.*, C.nombre, C.unidad_medida, C.controlar_stock 
            FROM \`${TB_INV}\` I 
            INNER JOIN \`${TB_CAT}\` C ON I.sku = C.sku 
            WHERE I.IDS = 1 
            ORDER BY C.nombre ASC
        `;

        fetch('../librerias/AJAX/Select.php', {
            method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `sql=${encodeURIComponent(sql)}&db=${DB}`
        })
        .then(r => r.json())
        .then(res => {
            if(!res.data || res.data.length === 0) {
                Swal.fire('Sin datos', 'No hay nada que exportar.', 'warning');
                return;
            }

            let tablaHTML = `
                <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
                <head><meta charset="UTF-8"></head><body>
                <table border="1">
                    <thead>
                        <tr style="background-color: #4CAF50; color: white;">
                            <th>SKU</th><th>PRODUCTO</th><th>UBICACION</th><th>COSTO</th><th>VENTA</th><th>MARGEN %</th><th>EXISTENCIA</th><th>VALOR TOTAL</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            res.data.forEach(row => {
                const costo = parseFloat(row.costo_promedio || 0);
                const precio = parseFloat(row.precio_venta || 0);
                const exist = parseFloat(row.existencia || 0);
                const margen = precio > 0 ? ((precio - costo) / precio * 100).toFixed(2) : 0;
                
                const valorTotal = (parseInt(row.controlar_stock) === 1) ? (costo * exist) : 0;
                const existTxt = (parseInt(row.controlar_stock) === 1) ? exist : 'ILIMITADO';

                tablaHTML += `
                    <tr>
                        <td style="mso-number-format:'\@'">${row.sku}</td>
                        <td>${row.nombre}</td>
                        <td>${row.ubicacion_fisica}</td>
                        <td style="mso-number-format:'0.00'">${costo}</td>
                        <td style="mso-number-format:'0.00'">${precio}</td>
                        <td style="mso-number-format:'0.00%'">${margen}%</td>
                        <td>${existTxt}</td>
                        <td style="mso-number-format:'0.00'">${valorTotal}</td>
                    </tr>
                `;
            });

            tablaHTML += `</tbody></table></body></html>`;

            const blob = new Blob([tablaHTML], { type: 'application/vnd.ms-excel' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `Inventario_General_${new Date().toISOString().slice(0,10)}.xls`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            Swal.close();
        });
    }
</script>