<?php
require_once __DIR__ . '/../../includes/layout.php';
$version = '20260520';

$pdo = getDBConnection();
$sucursales = [];
try {
    $sucursales = $pdo->query("SELECT id, nombre FROM sucursales ORDER BY id")->fetchAll();
} catch (Exception $e) {
    // Fail silently
}

renderHeader('Kardex de Productos', 'inventario');
?>

<style>
.kardex-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}
.report-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 1.5rem;
}
.report-header h1 {
    font-size: 1.75rem;
    font-weight: 800;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.report-header h1 small {
    font-size: 0.875rem;
    font-weight: 400;
    color: var(--text-secondary);
    margin-left: 0.5rem;
}

/* Elevated Search Bar & Autocomplete suggestions */
.search-container {
    position: relative;
    margin-bottom: 1.25rem;
}
.search-input {
    width: 100%;
    padding: 0.85rem 1rem 0.85rem 2.75rem;
    font-size: 1.05rem;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text-primary);
    border-radius: var(--radius-sm);
    outline: none;
    transition: border-color var(--transition), box-shadow var(--transition);
    box-sizing: border-box;
}
.search-input:focus {
    border-color: var(--accent-color);
    box-shadow: var(--focus-ring);
}
.search-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-secondary);
    font-size: 1.1rem;
    pointer-events: none;
}
.search-results {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--surface-elevated);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    z-index: 100;
    display: none;
    max-height: 300px;
    overflow-y: auto;
    box-shadow: var(--shadow-lg);
    margin-top: 0.25rem;
}
.search-item {
    padding: 0.75rem 1rem;
    border-bottom: 1px solid var(--border);
    cursor: pointer;
    color: var(--text-primary);
    transition: background var(--transition);
}
.search-item:hover {
    background: var(--surface-hover);
}
.search-item:last-child {
    border-bottom: none;
}

/* Local Filters card */
.filters-card {
    background: var(--surface-elevated);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.25rem 1.5rem;
    margin-bottom: 1.5rem;
}
.filters-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 1.25rem;
    align-items: flex-end;
}
.filter-group {
    display: flex;
    flex-direction: column;
    gap: 0.35rem;
}
.filter-label {
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: var(--text-secondary);
}
.filter-select {
    min-width: 220px;
    padding: 0.6rem 0.85rem;
    border-radius: var(--radius-sm);
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text-primary);
    font-size: 0.875rem;
    outline: none;
    cursor: pointer;
    transition: all var(--transition);
}
.filter-select:focus {
    border-color: var(--accent-color);
    box-shadow: var(--focus-ring);
}
.filter-select:disabled {
    opacity: 0.65;
    cursor: not-allowed;
}

/* Premium Badges */
.badge {
    display: inline-flex;
    align-items: center;
    padding: 0.25rem 0.6rem;
    border-radius: 6px;
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.025em;
}
.badge-soft-success {
    background: rgba(34, 197, 94, 0.1);
    color: var(--success);
    border: 1px solid rgba(34, 197, 94, 0.2);
}
.badge-soft-danger {
    background: rgba(239, 68, 68, 0.1);
    color: var(--danger);
    border: 1px solid rgba(239, 68, 68, 0.2);
}
.badge-soft-muted {
    background: var(--surface-hover);
    color: var(--text-secondary);
    border: 1px solid var(--border);
}

.table-premium td.num {
    text-align: right;
    font-variant-numeric: tabular-nums;
}
.text-green { color: var(--success) !important; }
.text-red { color: var(--danger) !important; }
.text-muted { color: var(--text-muted) !important; }
</style>

<div class="kardex-container">
    <div class="filters-card">
        <div class="report-header" style="margin-bottom: 0.75rem;">
            <h1 style="font-size: 1.5rem; font-family: 'League Spartan'; font-weight: 800;"><i class="fas fa-history"></i> Consulta de Kardex</h1>
        </div>
        <p style="color: var(--text-secondary); margin-bottom: 1.25rem; font-size: 0.9rem;">Consulte el historial de movimientos de inventario de un producto seleccionándolo a continuación.</p>
        
        <div class="search-container">
            <span class="search-icon"><i class="fas fa-search"></i></span>
            <input type="text" id="searchInput" class="search-input" placeholder="Escriba código interno o nombre del producto para buscar...">
            <div id="searchResults" class="search-results"></div>
        </div>

        <div class="filters-grid" style="margin-top: 1rem;">
            <div class="filter-group">
                <label class="filter-label">Sucursal</label>
                <select id="sucursalFilter" class="filter-select" onchange="loadKardex()">
                    <option value="0">🌐 Todas las Sucursales</option>
                    <?php foreach ($sucursales as $suc): ?>
                        <option value="<?= (int)$suc['id'] ?>">
                            <?= htmlspecialchars($suc['nombre']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
    </div>

    <div class="glass-card animate-fade-in" id="kardexView" style="display: none;">
        <h3 id="productTitle" style="font-size: 1.25rem; font-family: 'League Spartan'; font-weight: 800; margin-bottom: 1rem; color: var(--text-primary); border-bottom: 1px solid var(--border); padding-bottom: 0.75rem;"></h3>
        <div class="table-wrapper">
            <table class="table-premium">
                <thead>
                    <tr>
                        <th>Fecha</th>
                        <th>Sucursal</th>
                        <th>Tipo de Movimiento</th>
                        <th>Documento / Justificación</th>
                        <th class="num">Cantidad</th>
                        <th class="num">Saldo Restante</th>
                    </tr>
                </thead>
                <tbody id="kardexBody">
                    <!-- Data here -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
let searchTimeout;
let selectedProductId = null;
function esc(t) { if(!t)return''; const d=document.createElement('div'); d.textContent=t; return d.innerHTML; }

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?query=${encodeURIComponent(q)}&limit=20`);
    const data = await res.json();
    const results = document.getElementById('searchResults');
    const prods = data.data?.products || [];
    if(prods.length > 0) {
        let html = '';
        prods.forEach(p => {
            html += `<div class="search-item" onclick="selectProduct(${p.id}, '${esc(p.CodigoInterno)}', '${esc(p.NombreComercial)}')">
                <strong>${esc(p.CodigoInterno)}</strong> - ${esc(p.NombreComercial)}
            </div>`;
        });
        results.innerHTML = html;
        results.style.display = 'block';
    } else {
        results.style.display = 'none';
    }
}

function selectProduct(id, code, name) {
    selectedProductId = id;
    document.getElementById('searchInput').value = `${code} - ${name}`;
    document.getElementById('searchResults').style.display = 'none';
    document.getElementById('productTitle').innerText = `${code} - ${name}`;
    loadKardex();
}

async function loadKardex() {
    if(!selectedProductId) return;
    const suc = document.getElementById('sucursalFilter').value;
    
    document.getElementById('kardexView').style.display = 'block';
    const tbody = document.getElementById('kardexBody');
    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; padding: 2.5rem;" class="text-muted"><i class="fas fa-spinner fa-spin" style="margin-right:0.5rem;"></i> Cargando movimientos...</td></tr>';
    
    try {
        const res = await fetch(`api/inventario/kardex/listar.php?producto_id=${selectedProductId}&sucursal_id=${suc}`);
        const data = await res.json();
        
        if(data.success) {
            let html = '';
            if(data.data.movimientos.length === 0) {
                html = '<tr><td colspan="6" style="text-align:center; padding: 2.5rem;" class="text-muted">No hay movimientos registrados para este producto.</td></tr>';
            } else {
                data.data.movimientos.forEach(m => {
                    let typeClass = '';
                    let cantText = m.cantidad;
                    
                    const movTypes = {
                        ingreso_compra: { label: 'Compra', badge: 'badge-soft-success', sign: '+' },
                        ajuste_auditoria_suma: { label: 'Ajuste (+)', badge: 'badge-soft-success', sign: '+' },
                        traslado_ingreso: { label: 'Entrada Traslado', badge: 'badge-soft-success', sign: '+' },
                        salida_venta: { label: 'Venta', badge: 'badge-soft-danger', sign: '-' },
                        ajuste_auditoria_resta: { label: 'Ajuste (-)', badge: 'badge-soft-danger', sign: '-' },
                        traslado_salida: { label: 'Salida Traslado', badge: 'badge-soft-danger', sign: '-' }
                    };
                    
                    const mov = movTypes[m.tipo_movimiento] || { label: m.tipo_movimiento, badge: 'badge-soft-muted', sign: '' };
                    
                    if(mov.sign === '+') {
                        typeClass = 'text-green font-mono';
                        cantText = '+' + m.cantidad;
                    } else if (mov.sign === '-') {
                        typeClass = 'text-red font-mono';
                        cantText = '-' + Math.abs(m.cantidad);
                    } else {
                        typeClass = 'font-mono';
                    }
                    
                    let ref = m.justificacion || m.referencia_id || '-';
                    let branchName = m.sucursal_nombre ? esc(m.sucursal_nombre.split(' ')[0]) : 'Suc. ' + m.sucursal_id;
                    
                    html += `<tr>
                        <td><strong>${m.fecha_movimiento}</strong></td>
                        <td><strong>${branchName}</strong></td>
                        <td><span class="badge ${mov.badge}">${mov.label}</span></td>
                        <td style="max-width: 350px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${esc(ref)}">${esc(ref)}</td>
                        <td class="num ${typeClass}" style="font-weight: 700;">${cantText}</td>
                        <td class="num font-mono" style="font-weight:700;">${m.saldo_despues}</td>
                    </tr>`;
                });
            }
            tbody.innerHTML = html;
        } else {
            tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;color:red;padding:2rem;">Error: ${esc(data.error)}</td></tr>`;
        }
    } catch(e) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:red;padding:2rem;">Error de red cargando Kardex</td></tr>';
    }
}

// Close autocomplete suggestions when clicking outside
document.addEventListener('click', function(e) {
    if(!e.target.closest('.search-container')) {
        document.getElementById('searchResults').style.display = 'none';
    }
});

document.addEventListener('DOMContentLoaded', function() {
    const activeSuc = getSucursalId();
    const sel = document.getElementById('sucursalFilter');
    if (sel) {
        if (activeSuc > 0) {
            sel.value = activeSuc;
            sel.disabled = true;
        } else {
            sel.value = '0';
            sel.disabled = false;
        }
    }
});
</script>

<?php renderFooter(); ?>
