<?php
require_once __DIR__ . '/../../includes/layout.php';
$version = '20260520';
renderHeader('Auditoría de Inventario', 'inventario');
?>

<style>
.auditoria-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 1.5rem;
}
.glass-card {
    background: var(--surface-card);
    border: 1px solid var(--border-color);
    border-radius: 1rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
}
.search-container { position: relative; margin-bottom: 1.5rem; }
.search-input {
    width: 100%;
    padding: 1rem 1rem 1rem 3rem;
    font-size: 1.1rem;
    border: 2px solid var(--border-color);
    border-radius: 0.75rem;
}
.search-icon { position: absolute; left: 1rem; top: 1rem; color: var(--text-secondary); }
.search-results {
    position: absolute; top: 100%; left: 0; right: 0; background: white;
    border: 1px solid var(--border-color); border-radius: 0.75rem; z-index: 50; display: none;
    max-height: 300px; overflow-y: auto;
}
.search-item { padding: 1rem; border-bottom: 1px solid var(--border-color); cursor: pointer; }
.search-item:hover { background: #f8fafc; }

.form-group { margin-bottom: 1rem; display: flex; flex-direction: column; gap: 0.4rem; }
.modern-input { padding: 0.75rem; border: 1px solid var(--border-color); border-radius: 0.5rem; font-size: 1rem; }
.btn-primary { width: 100%; padding: 1rem; background: var(--primary-color); color: white; border: none; border-radius: 0.75rem; font-size: 1.1rem; font-weight: bold; cursor: pointer; }
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
</style>

<div class="auditoria-container">
    <div class="glass-card">
        <h2><i class="fas fa-clipboard-check"></i> Ajuste Manual de Inventario</h2>
        <p style="color: var(--text-secondary); margin-bottom: 1.5rem;">Modifique el stock por razones de auditoría, mermas, caducidad o sobrantes.</p>
        
        <div class="search-container">
            <span class="search-icon">🔍</span>
            <input type="text" id="searchInput" class="search-input" placeholder="Buscar producto...">
            <div id="searchResults" class="search-results"></div>
        </div>

        <div id="adjustmentForm" style="display: none;">
            <div style="background: #f1f5f9; padding: 1rem; border-radius: 0.5rem; margin-bottom: 1.5rem;">
                <strong>Producto:</strong> <span id="lblProduct" style="color: var(--primary-color);"></span><br>
                <strong>Stock Actual (En sistema):</strong> <span id="lblStock" style="font-weight:bold; font-size: 1.2rem;">0</span>
            </div>

            <div class="form-group">
                <label>Sucursal</label>
                <select id="sucursalId" class="modern-input">
                    <option value="1">Bodega Central (1)</option>
                    <!-- Aquí se pueden cargar dinámicamente -->
                </select>
            </div>

            <div class="form-group">
                <label>Cantidad FÍSICA REAL (Conteo final)</label>
                <input type="number" id="cantFisica" class="modern-input" min="0" placeholder="Ej: 50" required>
            </div>

            <div class="form-group">
                <label>Motivo / Justificación</label>
                <input type="text" id="justificacion" class="modern-input" placeholder="Ej: Merma por caducidad, Inventario físico 2026..." required>
            </div>

            <button id="btnGuardar" class="btn-primary" onclick="guardarAjuste()">Guardar Ajuste</button>
        </div>
    </div>
</div>

<script>
let searchTimeout;
let selectedProduct = null;

document.getElementById('searchInput').addEventListener('input', (e) => {
    clearTimeout(searchTimeout);
    const q = e.target.value.trim();
    if(q.length < 2) {
        document.getElementById('searchResults').style.display = 'none';
        return;
    }
    searchTimeout = setTimeout(() => searchProducts(q), 300);
});

async function searchProducts(q) {
    const res = await fetch(`api/inventario/productos/buscar.php?q=${encodeURIComponent(q)}`);
    const data = await res.json();
    const results = document.getElementById('searchResults');
    if(data.success && data.data.length > 0) {
        let html = '';
        data.data.forEach(p => {
            html += `<div class="search-item" onclick='selectProduct(${JSON.stringify(p).replace(/'/g, "&#39;")})'>
                <strong>${p.CodigoInterno}</strong> - ${p.NombreComercial}
            </div>`;
        });
        results.innerHTML = html;
        results.style.display = 'block';
    }
}

async function selectProduct(p) {
    selectedProduct = p;
    document.getElementById('searchInput').value = `${p.CodigoInterno} - ${p.NombreComercial}`;
    document.getElementById('searchResults').style.display = 'none';
    document.getElementById('lblProduct').innerText = `${p.CodigoInterno} - ${p.NombreComercial}`;
    
    // Obtener stock
    const res = await fetch(`api/inventario/kardex/listar.php?producto_id=${p.id}&sucursal_id=1`);
    const data = await res.json();
    let currStock = 0;
    if(data.success && data.data.movimientos.length > 0) {
        currStock = data.data.movimientos[0].saldo_despues;
    }
    
    document.getElementById('lblStock').innerText = currStock;
    document.getElementById('adjustmentForm').style.display = 'block';
}

async function guardarAjuste() {
    const suc = document.getElementById('sucursalId').value;
    const fis = document.getElementById('cantFisica').value;
    const jus = document.getElementById('justificacion').value.trim();
    
    if(fis === '' || jus === '') {
        alert("Ingrese la cantidad física y la justificación.");
        return;
    }
    
    if(fis < 0) {
        alert("La cantidad no puede ser negativa.");
        return;
    }

    const btn = document.getElementById('btnGuardar');
    btn.disabled = true;
    btn.innerText = "Guardando...";
    
    try {
        const res = await fetch('api/inventario/auditoria/registrar.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                producto_id: selectedProduct.id,
                sucursal_id: suc,
                cantidad_fisica: fis,
                justificacion: jus
            })
        });
        const data = await res.json();
        
        if(data.success) {
            alert(data.data);
            document.getElementById('adjustmentForm').style.display = 'none';
            document.getElementById('searchInput').value = '';
            selectedProduct = null;
        } else {
            alert("Error: " + data.error);
        }
    } catch(e) {
        alert("Error de conexión");
    } finally {
        btn.disabled = false;
        btn.innerText = "Guardar Ajuste";
    }
}
</script>

<?php renderFooter(); ?>

