<div class="card-custom">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-boxes me-2"></i>Inventario Farmacéutico</h4>
        <button class="btn btn-primary rounded-pill shadow-sm" onclick="openProductModal()">
            <i class="fas fa-plus"></i> Nuevo Producto
        </button>
    </div>

    <div class="input-group mb-3 shadow-sm">
        <span class="input-group-text bg-white border-end-0"><i class="fas fa-search text-muted"></i></span>
        <input type="text" id="filter-prod" class="form-control border-start-0" placeholder="Buscar por nombre, principio activo o código..." onkeyup="filterTable()">
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle" id="table-prods">
            <thead class="table-light">
                <tr>
                    <th>Producto</th>
                    <th>Laboratorio</th>
                    <th>Precios (U / B / C)</th>
                    <th>Ubicación</th>
                    <th>Stock</th>
                    <th class="text-end">Acción</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                if(!isset($conn)) require_once 'db.php';
                $r = $conn->query("SELECT * FROM productos ORDER BY id_producto DESC LIMIT 50"); 
                if($r): while($d = $r->fetch_assoc()): 
                    $precios = "<b>U: {$moneda}{$d['precio_venta']}</b>";
                    if($d['precio_blister'] > 0) $precios .= "<br><small class='text-muted'>B: {$moneda}{$d['precio_blister']}</small>";
                    if($d['precio_caja'] > 0) $precios .= "<br><small class='text-muted'>C: {$moneda}{$d['precio_caja']}</small>";
                ?>
                <tr>
                    <td>
                        <div class="fw-bold text-dark"><?php echo $d['nombre']; ?></div>
                        <small class="text-primary d-block"><?php echo $d['principio_activo']; ?></small>
                        <small class="text-secondary" style="font-size: 0.75rem;"><i class="fas fa-barcode"></i> <?php echo $d['codigo_barras']; ?></small>
                    </td>
                    <td><?php echo $d['laboratorio']; ?></td>
                    <td><?php echo $precios; ?></td>
                    <td><span class="badge bg-light text-dark border"><?php echo $d['ubicacion']; ?></span></td>
                    <td>
                        <span id="row-stock-<?php echo $d['id_producto']; ?>" class="badge <?php echo $d['stock'] < 5 ? 'bg-danger' : 'bg-success'; ?> rounded-pill" style="font-size:1em;">
                            <?php echo $d['stock']; ?>
                        </span>
                    </td>
                    <td class="text-end">
                        <button class="btn btn-sm btn-outline-primary" onclick='editProd(<?php echo json_encode($d); ?>)' title="Editar"><i class="fas fa-edit"></i></button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteProd(<?php echo $d['id_producto']; ?>)" title="Eliminar"><i class="fas fa-trash"></i></button>
                    </td>
                </tr>
                <?php endwhile; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modalProd" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-lg">
        <form id="formProd" class="modal-content" onsubmit="saveProduct(event)">
            <input type="hidden" name="id_producto" id="prod-id">
            <input type="hidden" name="camera_data" id="camera-data">
            
            <div class="modal-header bg-primary text-white py-2">
                <h6 class="modal-title fw-bold">Gestión de Medicamento</h6>
                <button type="button" class="btn-close btn-close-white" onclick="closeModal()"></button>
            </div>
            
            <div class="modal-body bg-light p-0">
                <ul class="nav nav-tabs nav-justified" id="prodTabs" role="tablist">
                    <li class="nav-item"><button class="nav-link active fw-bold rounded-0" id="t1" data-bs-toggle="tab" data-bs-target="#p1" type="button">1. Datos Generales</button></li>
                    <li class="nav-item"><button class="nav-link fw-bold rounded-0" id="t2" data-bs-toggle="tab" data-bs-target="#p2" type="button">2. Precios y Presentación</button></li>
                    <li class="nav-item"><button class="nav-link fw-bold rounded-0" id="t3" data-bs-toggle="tab" data-bs-target="#p3" type="button" onclick="loadLotesTab()">3. Lotes y Vencimientos</button></li>
                </ul>

                <div class="tab-content p-3">
                    <div class="tab-pane fade show active" id="p1">
                        <div class="row g-2 align-items-end mb-3">
                            <div class="col-md-5">
                                <label class="fw-bold small text-primary">Código de Barras (*)</label>
                                <div class="input-group input-group-sm">
                                    <input name="cb" id="prod-cb" class="form-control fw-bold" placeholder="Escanea o escribe..." required>
                                    <button type="button" class="btn btn-outline-secondary" onclick="generateBarcode()" title="Generar"><i class="fas fa-magic"></i></button>
                                    <button type="button" class="btn btn-outline-primary" onclick="startScanner()" title="Escanear con Cámara"><i class="fas fa-barcode"></i></button>
                                </div>
                                <div id="reader-container" class="mt-2 border border-primary bg-dark" style="display:none; position:relative;">
                                    <div id="reader-prod" style="width: 100%;"></div>
                                    <button type="button" class="btn btn-danger btn-sm w-100" onclick="stopScanner()">Detener Cámara</button>
                                </div>
                            </div>
                            <div class="col-md-7">
                                <label class="fw-bold small text-primary">Nombre Comercial (*)</label>
                                <input name="n" id="prod-n" class="form-control form-control-sm fw-bold" placeholder="Ej: Amoxicilina 500mg" required>
                            </div>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-md-6"><label class="fw-bold small">Principio Activo</label><input name="pa" id="prod-pa" class="form-control form-control-sm"></div>
                            <div class="col-md-6">
                                <label class="fw-bold small">Laboratorio</label>
                                <div class="input-group input-group-sm">
                                    <select name="laboratorio" id="lab-select" class="form-select"><option value="">-- Seleccione --</option></select>
                                    <button type="button" class="btn btn-info text-white" onclick="openLabManager()"><i class="fas fa-cog"></i></button>
                                </div>
                            </div>
                        </div>
                        <div class="row g-2">
                             <div class="col-md-4"><label class="fw-bold small">Cod. DIGEMID</label><input name="codigo_digemid" id="prod-digemid" class="form-control form-control-sm text-uppercase"></div>
                             <div class="col-md-4"><label class="fw-bold small">Ubicación</label><input name="ubicacion" id="prod-ubic" class="form-control form-control-sm" placeholder="Ej: Anaquel A1"></div>
                             <div class="col-md-4"><label class="fw-bold small">Presentación</label><input name="presentacion" id="prod-pres" class="form-control form-control-sm" placeholder="Ej: Jarabe, Tableta"></div>
                        </div>
                        <div class="row g-2 mt-2">
                            <div class="col-md-12"><label class="fw-bold small">Acción Terapéutica</label><input name="accion_terapeutica" id="prod-accion" class="form-control form-control-sm"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="p2">
                        <div class="alert alert-info py-1 small mb-3"><i class="fas fa-info-circle"></i> Define los precios para cada presentación.</div>
                        
                        <div class="card p-2 mb-2 border-primary bg-primary bg-opacity-10">
                            <div class="row g-2 align-items-center">
                                <div class="col-md-4 text-end"><span class="fw-bold text-primary">POR UNIDAD (Base)</span></div>
                                <div class="col-md-4"><div class="input-group input-group-sm"><span class="input-group-text">Costo</span><input type="number" step="0.01" name="pc" id="prod-pc" class="form-control" placeholder="0.00"></div></div>
                                <div class="col-md-4"><div class="input-group input-group-sm"><span class="input-group-text bg-success text-white">Venta</span><input type="number" step="0.01" name="pv" id="prod-pv" class="form-control fw-bold border-success" placeholder="0.00" required></div></div>
                            </div>
                        </div>

                        <div class="card p-2 mb-2 border-secondary">
                            <div class="row g-2 align-items-center">
                                <div class="col-md-4 text-end"><span class="fw-bold text-secondary">POR BLISTER</span></div>
                                <div class="col-md-4"><div class="input-group input-group-sm"><span class="input-group-text">Unid. x Blister</span><input type="number" name="c_blister" id="prod-c-blister" class="form-control" value="10"></div></div>
                                <div class="col-md-4"><div class="input-group input-group-sm"><span class="input-group-text">Precio Venta</span><input type="number" step="0.01" name="p_blister" id="prod-p-blister" class="form-control fw-bold" placeholder="0.00"></div></div>
                            </div>
                        </div>

                        <div class="card p-2 mb-3 border-secondary">
                            <div class="row g-2 align-items-center">
                                <div class="col-md-4 text-end"><span class="fw-bold text-secondary">POR CAJA</span></div>
                                <div class="col-md-4"><div class="input-group input-group-sm"><span class="input-group-text">Unid. x Caja</span><input type="number" name="c_caja" id="prod-c-caja" class="form-control" value="100"></div></div>
                                <div class="col-md-4"><div class="input-group input-group-sm"><span class="input-group-text">Precio Venta</span><input type="number" step="0.01" name="p_caja" id="prod-p-caja" class="form-control fw-bold" placeholder="0.00"></div></div>
                            </div>
                        </div>
                        
                        <div class="row g-2 align-items-end">
                             <div class="col-md-6">
                                 <label class="fw-bold small text-danger">Stock Total (Automático)</label>
                                 <input type="number" name="s" id="prod-s" class="form-control fw-bold bg-secondary bg-opacity-10" placeholder="0" readonly>
                                 <small class="text-muted" style="font-size:10px">Se suma automáticamente al agregar lotes.</small>
                             </div>
                             <div class="col-md-6">
                                 <label class="fw-bold small">Fotografía</label>
                                 <div class="d-flex gap-1">
                                     <button type="button" class="btn btn-outline-primary w-100 btn-sm" onclick="openCameraModal()"><i class="fas fa-camera"></i> Foto</button>
                                     <input type="file" name="img" class="form-control form-control-sm" style="width:100px">
                                 </div>
                                 <div id="preview-container" class="mt-1 d-none text-center">
                                     <img id="preview-img" src="" style="height:50px; border-radius:5px; border:1px solid #ccc">
                                     <button type="button" class="btn btn-xs btn-danger" onclick="clearPhoto()">X</button>
                                 </div>
                             </div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="p3">
                        <div class="card p-3 border-warning border-opacity-25 bg-warning bg-opacity-10 mb-3">
                            <h6 class="fw-bold text-dark mb-2">Ingresar Nuevo Lote</h6>
                            <div class="row g-2 align-items-end">
                                <div class="col-md-4"><label class="small fw-bold">N° Lote</label><input type="text" id="lote_cod" class="form-control form-control-sm fw-bold" placeholder="Ej. L-2025"></div>
                                <div class="col-md-4"><label class="small fw-bold">Vence</label><input type="date" id="lote_venc" class="form-control form-control-sm"></div>
                                <div class="col-md-2"><label class="small fw-bold">Cant.</label><input type="number" id="lote_cant" class="form-control form-control-sm fw-bold" placeholder="0"></div>
                                <div class="col-md-2"><button type="button" class="btn btn-sm btn-dark w-100 fw-bold" onclick="saveLoteManual()">AGREGAR</button></div>
                            </div>
                        </div>
                        <h6 class="fw-bold small text-muted">Historial de Lotes Activos</h6>
                        <div class="table-responsive border bg-white" style="max-height: 200px;">
                            <table class="table table-sm table-striped mb-0">
                                <thead class="table-light sticky-top"><tr><th>Lote</th><th>Vencimiento</th><th>Stock</th><th></th></tr></thead>
                                <tbody id="lista-lotes"><tr><td colspan="4" class="text-center text-muted small">Selecciona un producto guardado.</td></tr></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer py-2 bg-light">
                <button type="button" class="btn btn-secondary btn-sm" onclick="closeModal()">Cancelar</button>
                <button type="submit" class="btn btn-primary btn-sm fw-bold px-4">GUARDAR PRODUCTO</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="modalCamara" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark text-white">
            <div class="modal-header border-0 py-2"><h6 class="m-0">Tomar Foto</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-0 text-center position-relative">
                <video id="video-cam" style="width:100%; height:300px; object-fit:cover;" autoplay playsinline></video>
                <canvas id="canvas-cam" style="display:none"></canvas>
            </div>
            <div class="modal-footer border-0 justify-content-center">
                <button type="button" class="btn btn-primary rounded-circle" onclick="takeSnapshot()" style="width:60px; height:60px; border:4px solid white"><i class="fas fa-camera fa-lg"></i></button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalLabManager" tabindex="-1" style="z-index: 1060;">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-light">
            <div class="modal-header bg-info text-white py-2">
                <h6 class="modal-title fw-bold">Gestión de Laboratorios</h6>
                <button type="button" class="btn-close" onclick="closeLabManager()"></button>
            </div>
            <div class="modal-body p-3">
                <div class="card mb-3 p-3 border-0 shadow-sm">
                    <form id="formLab">
                        <input type="hidden" id="lab_id" name="id_lab">
                        <div class="row g-2 align-items-end">
                            <div class="col-md-2"><label class="small fw-bold">Código</label><input type="text" id="lab_cod" name="cod" class="form-control form-control-sm"></div>
                            <div class="col-md-6"><label class="small fw-bold text-primary">Descripción (*)</label><input type="text" id="lab_desc" name="desc" class="form-control form-control-sm fw-bold" required></div>
                            <div class="col-md-2"><label class="small fw-bold">Abrev.</label><input type="text" id="lab_abbr" name="abbr" class="form-control form-control-sm"></div>
                            <div class="col-md-2"><button type="submit" class="btn btn-sm btn-primary w-100">Guardar</button></div>
                        </div>
                    </form>
                </div>
                <div class="card shadow-sm border-0" style="max-height:300px;overflow-y:auto;">
                    <table class="table table-sm table-hover mb-0 align-middle">
                        <thead class="table-light sticky-top">
                            <tr><th>Código</th><th>Descripción</th><th>Abrev.</th><th class="text-end">Acción</th></tr>
                        </thead>
                        <tbody id="labListBody" class="small bg-white"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let modalProdInstance;
    let html5QrCode; 
    let streamCam = null; 
    let modalLab;

    // --- FUNCIONES DEL PRODUCTO ---
    function openProductModal() {
        document.getElementById('formProd').reset();
        document.getElementById('prod-id').value = ''; 
        document.getElementById('prod-s').readOnly = false;
        clearPhoto();
        loadLabsIntoSelect();
        new bootstrap.Tab(document.querySelector('#t1')).show();
        if(!modalProdInstance) modalProdInstance = new bootstrap.Modal(document.getElementById('modalProd'));
        modalProdInstance.show();
        setTimeout(() => document.getElementById('prod-cb').focus(), 500);
    }

    function closeModal() {
        if(modalProdInstance) modalProdInstance.hide();
        stopScanner();
    }

    function editProd(d) {
        document.getElementById('formProd').reset();
        clearPhoto();
        loadLabsIntoSelect();
        
        document.getElementById('prod-s').readOnly = true;

        document.getElementById('prod-id').value = d.id_producto;
        document.getElementById('prod-cb').value = d.codigo_barras;
        document.getElementById('prod-n').value = d.nombre;
        document.getElementById('prod-pa').value = d.principio_activo;
        document.getElementById('lab-select').value = d.laboratorio;
        document.getElementById('prod-digemid').value = d.codigo_digemid || '';
        document.getElementById('prod-ubic').value = d.ubicacion || '';
        document.getElementById('prod-pres').value = d.presentacion || '';
        document.getElementById('prod-accion').value = d.accion_terapeutica || '';
        document.getElementById('prod-pc').value = d.precio_costo;
        document.getElementById('prod-pv').value = d.precio_venta;
        document.getElementById('prod-s').value = d.stock;
        document.getElementById('prod-p-blister').value = d.precio_blister > 0 ? d.precio_blister : '';
        document.getElementById('prod-c-blister').value = d.cantidad_blister || 10;
        document.getElementById('prod-p-caja').value = d.precio_caja > 0 ? d.precio_caja : '';
        document.getElementById('prod-c-caja').value = d.cantidad_caja || 100;

        if(!modalProdInstance) modalProdInstance = new bootstrap.Modal(document.getElementById('modalProd'));
        modalProdInstance.show();
    }

    function saveProduct(e) {
        e.preventDefault();
        let fd = new FormData(document.getElementById('formProd'));
        
        fetch('api.php?task=save_producto', {method: 'POST', body: fd})
        .then(r => r.json())
        .then(res => {
            if(res.success) {
                Swal.fire('Guardado', '', 'success').then(() => location.reload());
            } else if (res.is_duplicate) {
                Swal.fire({
                    title: 'Producto Existente', 
                    text: 'El código ya existe. ¿Deseas editarlo?', 
                    showCancelButton: true
                }).then(r => {
                    if(r.isConfirmed) {
                        fetch('api.php?task=search_products&term='+encodeURIComponent(fd.get('cb')))
                        .then(rr => rr.json())
                        .then(d => {
                            if(d.length > 0) {
                                editProd(d[0]);
                                new bootstrap.Tab(document.querySelector('#t3')).show(); 
                                loadLotesTab();
                            }
                        });
                    }
                });
            } else {
                Swal.fire('Error', res.error, 'error');
            }
        })
        .catch(err => Swal.fire('Error de Red', 'Revisa la conexión', 'error'));
    }

    function deleteProd(id) { 
        Swal.fire({
            title: '¿Eliminar producto?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar'
        }).then((result) => {
            if (result.isConfirmed) {
                let fd = new FormData(); fd.append('id', id); 
                fetch('api.php?task=delete_product', {method:'POST', body:fd})
                .then(r=>r.json()).then(res=>{ if(res.success) location.reload(); }); 
            }
        });
    }

    function filterTable() { 
        let txt = document.getElementById('filter-prod').value.toLowerCase(); 
        document.querySelectorAll('#table-prods tbody tr').forEach(r => { 
            r.style.display = r.innerText.toLowerCase().includes(txt) ? '' : 'none'; 
        }); 
    }

    // --- FUNCIONES DE LOTES Y STOCK DINÁMICO ---
    function saveLoteManual() {
        let pid = document.getElementById('prod-id').value;
        let cod = document.getElementById('lote_cod').value;
        let ven = document.getElementById('lote_venc').value;
        let can = parseFloat(document.getElementById('lote_cant').value);

        if(!pid) return Swal.fire('Aviso', 'Guarda el producto primero para habilitar lotes.', 'warning');
        if(!cod || !ven || isNaN(can)) return Swal.fire('Falta Datos', 'Completa todos los campos del lote.', 'warning');

        let fd = new FormData();
        fd.append('id_producto', pid);
        fd.append('codigo_lote', cod);
        fd.append('fecha_vencimiento', ven);
        fd.append('cantidad', can);

        fetch('api.php?task=save_lote_manual', {method:'POST', body:fd})
        .then(r => r.json())
        .then(res => {
            if(res.success) {
                loadLotesTab();
                
                // Actualización visual inmediata del Stock
                let inputStock = document.getElementById('prod-s');
                let currentStock = parseFloat(inputStock.value) || 0;
                inputStock.value = currentStock + can; 
                
                document.getElementById('lote_cod').value = '';
                document.getElementById('lote_cant').value = '';
                Swal.fire({toast:true, position:'top-end', icon:'success', title:'Lote guardado', showConfirmButton:false, timer:1500});
            } else {
                Swal.fire('Error', res.error, 'error');
            }
        }).catch(err => console.error(err));
    }

    function loadLotesTab() {
        let pid = document.getElementById('prod-id').value;
        if(!pid) return;
        fetch('api.php?task=get_lotes_producto&id='+pid)
        .then(r => r.json())
        .then(data => {
            let h = '';
            if(data.length === 0) h = '<tr><td colspan="4" class="text-center text-muted">Sin lotes activos</td></tr>';
            data.forEach(l => {
                let color = (new Date(l.fecha_vencimiento) < new Date()) ? 'text-danger fw-bold' : 'text-dark';
                h += `<tr>
                    <td class="${color}">${l.codigo_lote}</td>
                    <td>${l.fecha_vencimiento}</td>
                    <td class="fw-bold">${l.stock_actual}</td>
                    <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger py-0" onclick="delLote(${l.id_lote}, ${l.stock_actual})">&times;</button></td>
                </tr>`;
            });
            document.getElementById('lista-lotes').innerHTML = h;
        });
    }

    function delLote(id, cantidadLote) {
        Swal.fire({
            title: '¿Eliminar este lote?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar'
        }).then((result) => {
            if(result.isConfirmed) {
                let fd = new FormData(); fd.append('id_lote', id);
                fetch('api.php?task=delete_lote', {method:'POST', body:fd}).then(r=>r.json()).then(res=>{ 
                    if(res.success) {
                        loadLotesTab();
                        // Actualización visual inmediata (resta de stock)
                        let inputStock = document.getElementById('prod-s');
                        let currentStock = parseFloat(inputStock.value) || 0;
                        inputStock.value = Math.max(0, currentStock - parseFloat(cantidadLote));
                        Swal.fire({toast:true, position:'top-end', icon:'success', title:'Lote eliminado', showConfirmButton:false, timer:1500});
                    } else {
                        Swal.fire('Error', res.error, 'error');
                    }
                });
            }
        });
    }

    // --- FUNCIONES DEL GESTOR DE LABORATORIOS (REPARADAS) ---
    function openLabManager() { 
        if(!modalLab) modalLab = new bootstrap.Modal(document.getElementById('modalLabManager')); 
        loadLabList(); 
        modalLab.show(); 
    }
    
    function closeLabManager() { 
        modalLab.hide(); 
        loadLabsIntoSelect(); 
    }

    function loadLabsIntoSelect() { 
        fetch('api.php?task=get_labs').then(r => r.json()).then(labs => { 
            let s = document.getElementById('lab-select'); 
            let current = s.value; // Guardar valor seleccionado
            s.innerHTML = '<option value="">-- Seleccione --</option>'; 
            labs.forEach(l => { 
                s.innerHTML += `<option value="${l.descripcion}">${l.descripcion}</option>`; 
            }); 
            if(current) s.value = current; // Restaurar selección
        }); 
    }

    function loadLabList() { 
        fetch('api.php?task=get_labs').then(r => r.json()).then(labs => { 
            let h = ''; 
            labs.forEach(l => { 
                h += `<tr>
                    <td>${l.codigo || '-'}</td>
                    <td class="fw-bold text-dark">${l.descripcion}</td>
                    <td>${l.abreviatura || '-'}</td>
                    <td class="text-end"><button type="button" class="btn btn-sm btn-outline-danger" onclick="delLab(${l.id_laboratorio})"><i class="fas fa-trash"></i></button></td>
                </tr>`; 
            }); 
            document.getElementById('labListBody').innerHTML = h; 
        }); 
    }

    document.getElementById('formLab').addEventListener('submit', function(e) { 
        e.preventDefault(); 
        fetch('api.php?task=save_lab', {method:'POST', body: new FormData(this)})
        .then(r=>r.json())
        .then(res => { 
            if(res.success) { 
                this.reset(); 
                loadLabList(); 
                loadLabsIntoSelect();
                Swal.fire({toast:true, position:'top-end', icon:'success', title:'Laboratorio Guardado', showConfirmButton:false, timer:1500});
            } else {
                Swal.fire('Error', res.error, 'error');
            }
        }); 
    });

    function delLab(id_laboratorio) { 
        Swal.fire({
            title: '¿Eliminar Laboratorio?',
            text: "Se ocultará de las opciones disponibles.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Sí, eliminar'
        }).then((result) => {
            if (result.isConfirmed) {
                let fd = new FormData();
                fd.append('id_laboratorio', id_laboratorio);
                fetch('api.php?task=delete_lab', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(res => {
                    if(res.success) {
                        Swal.fire('Eliminado', '', 'success');
                        loadLabList();
                        loadLabsIntoSelect();
                    } else {
                        Swal.fire('Error', res.error, 'error');
                    }
                }).catch(err => Swal.fire('Error', 'Problema de conexión', 'error'));
            }
        });
    }

    // --- CÁMARA ESCÁNER & FOTO ---
    function startScanner() {
        const container = document.getElementById('reader-container');
        container.style.display = 'block';
        if (!html5QrCode) html5QrCode = new Html5Qrcode("reader-prod");
        Html5Qrcode.getCameras().then(devices => {
            if (devices && devices.length) {
                var cameraId = devices[0].id;
                if (devices.length > 1) cameraId = devices[devices.length - 1].id; 
                html5QrCode.start(cameraId, { fps: 10, qrbox: 250 }, (decodedText) => { document.getElementById('prod-cb').value = decodedText; stopScanner(); if(navigator.vibrate) navigator.vibrate(200); }, () => { }).catch(err => { alert("Error cámara: " + err); container.style.display = 'none'; });
            } else { alert("Sin cámara"); container.style.display = 'none'; }
        }).catch(err => { alert("Sin permisos"); container.style.display = 'none'; });
    }

    function stopScanner() { if (html5QrCode && html5QrCode.isScanning) { html5QrCode.stop().then(() => { document.getElementById('reader-container').style.display = 'none'; html5QrCode.clear(); }); } else { document.getElementById('reader-container').style.display = 'none'; } }
    function openCameraModal() { new bootstrap.Modal(document.getElementById('modalCamara')).show(); const video = document.getElementById('video-cam'); navigator.mediaDevices.getUserMedia({ video: true }).then(s => { streamCam = s; video.srcObject = s; }).catch(e => Swal.fire('Error', 'No se detectó cámara.', 'error')); }
    function takeSnapshot() { const v = document.getElementById('video-cam'); const c = document.getElementById('canvas-cam'); c.width = v.videoWidth; c.height = v.videoHeight; c.getContext('2d').drawImage(v, 0, 0); let d = c.toDataURL('image/jpeg'); document.getElementById('camera-data').value = d; document.getElementById('preview-img').src = d; document.getElementById('preview-container').classList.remove('d-none'); bootstrap.Modal.getInstance(document.getElementById('modalCamara')).hide(); if(streamCam) streamCam.getTracks().forEach(t => t.stop()); }
    function clearPhoto() { document.getElementById('camera-data').value = ''; document.getElementById('preview-container').classList.add('d-none'); }
    function generateBarcode() { fetch('api.php?task=generate_barcode').then(r=>r.json()).then(d => document.getElementById('prod-cb').value = d.code); }
</script>