<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Ajustes de Inventario', 'ajustes_inventario');
?>
<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<style>
.aj-wrap { max-width: 1400px; margin: 0 auto; padding: 1.5rem; }
.aj-header { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1.5rem; }
.aj-header h1 { font-size: 1.5rem; font-weight: 800; margin: 0; display: flex; align-items: center; gap: 0.5rem; }

.aj-tabs { display: flex; gap: 0.5rem; border-bottom: 2px solid var(--border-color); margin-bottom: 1.5rem; }
.aj-tab { padding: 0.6rem 1.25rem; font-size: 0.85rem; font-weight: 600; border: none; background: transparent; color: var(--text-secondary); cursor: pointer; border-radius: 0.75rem 0.75rem 0 0; transition: all 0.2s; }
.aj-tab:hover { color: var(--text-primary); background: rgba(0,0,0,0.02); }
.aj-tab.active { color: var(--accent-color); background: var(--surface-card); box-shadow: 0 -2px 0 var(--accent-color); }

.aj-panel { display: none; }
.aj-panel.active { display: block; }
.aj-card { background: var(--surface-card); border: 1px solid var(--border-color); border-radius: 1rem; padding: 1.5rem; }
.aj-card-title { font-size: 0.9rem; font-weight: 700; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }

.aj-search input, .aj-search select { width: 100%; padding: 0.6rem 0.75rem; border-radius: 0.75rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); font-size: 0.875rem; box-sizing: border-box; }
.aj-search input:focus, .aj-search select:focus { outline: none; border-color: var(--accent-color); }

.aj-result-item { padding: 0.75rem; border-radius: 0.75rem; cursor: pointer; border: 1px solid transparent; transition: all 0.15s; margin-bottom: 0.35rem; }
.aj-result-item:hover { background: rgba(0,0,0,0.03); border-color: var(--border-color); }

.aj-preview { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 0.75rem; padding: 0.75rem 1rem; font-size: 0.85rem; }
.aj-preview.resta { background: #fef2f2; border-color: #fecaca; }
.aj-preview .dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 0.5rem; }

.aj-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1.25rem; }
.aj-form label { font-size: 0.75rem; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; display: block; margin-bottom: 0.3rem; }
.aj-form input, .aj-form select, .aj-form textarea { width: 100%; padding: 0.6rem 0.75rem; border-radius: 0.75rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); font-size: 0.875rem; box-sizing: border-box; }
.aj-form textarea { resize: vertical; }

.stock-info { display: flex; gap: 1.5rem; margin: 0.75rem 0; font-size: 0.8rem; }
.stock-info span { color: var(--text-secondary); }
.stock-info strong { color: var(--text-primary); }

.hist-filters { display: flex; flex-wrap: wrap; gap: 0.75rem; align-items: center; margin-bottom: 1rem; }
.hist-filters select, .hist-filters input { padding: 0.45rem 0.75rem; border-radius: 0.65rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); font-size: 0.8rem; }
.hist-filters input[type=date] { width: 140px; }

.aj-table-wrap { overflow-x: auto; }
.aj-table-wrap table { width: 100%; border-collapse: collapse; min-width: 700px; }
.aj-table-wrap th { padding: 0.65rem 0.75rem; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-secondary); border-bottom: 2px solid var(--border-color); text-align: left; white-space: nowrap; }
.aj-table-wrap td { padding: 0.6rem 0.75rem; font-size: 0.8rem; border-bottom: 1px solid var(--border-color); vertical-align: middle; }
.aj-table-wrap tr:hover { background: rgba(0,0,0,0.02); }

.badge-ajuste { display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.2rem 0.6rem; border-radius: 1rem; font-size: 0.65rem; font-weight: 700; white-space: nowrap; }
.aj-pag { display: flex; justify-content: center; gap: 0.35rem; margin-top: 1rem; }
.aj-pag button { padding: 0.35rem 0.7rem; font-size: 0.75rem; border-radius: 0.5rem; border: 1px solid var(--border-color); background: var(--surface-card); color: var(--text-primary); cursor: pointer; }
.aj-pag button.active { background: var(--accent-color); color: white; border-color: var(--accent-color); }

.modal-overlay { display: none; position: fixed; inset: 0; z-index: 1000; background: rgba(0,0,0,0.5); backdrop-filter: blur(4px); align-items: center; justify-content: center; }
.modal-overlay.open { display: flex; }
.modal-content { background: var(--surface-card); border-radius: 1.5rem; width: 95%; max-width: 460px; max-height: 90vh; overflow: auto; padding: 1.5rem; box-shadow: 0 25px 50px rgba(0,0,0,0.25); }
.modal-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1rem; }
.modal-header h3 { font-size: 1.1rem; font-weight: 700; margin: 0; }
.modal-close { background: none; border: none; font-size: 1.25rem; cursor: pointer; color: var(--text-secondary); padding: 0.25rem; line-height: 1; }

@media (max-width: 768px) { .aj-grid-2 { grid-template-columns: 1fr; } .aj-wrap { padding: 1rem; } }

@keyframes fadeSlideIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
.aj-panel.active { animation: fadeSlideIn 0.25s ease-out; }
</style>

<div class="aj-wrap">
    <div class="aj-header">
        <h1><i class="bi bi-sliders2"></i> Ajustes de Inventario</h1>
        <span style="font-size:0.8rem;color:var(--text-secondary)">Mermas, robos, vencimientos, correcciones y sobrantes</span>
    </div>

    <!-- Tabs -->
    <div class="aj-tabs">
        <button class="aj-tab active" data-tab="registrar" onclick="cambiarTab('registrar')"><i class="bi bi-pencil-square"></i> Registrar Ajuste</button>
        <button class="aj-tab" data-tab="historial" onclick="cambiarTab('historial')"><i class="bi bi-clock-history"></i> Historial</button>
    </div>

    <!-- Panel: Registrar -->
    <div class="aj-panel active" id="panel-registrar">
        <div class="aj-grid-2">
            <!-- Buscar producto -->
            <div class="aj-card">
                <div class="aj-card-title"><i class="bi bi-search" style="color:var(--accent-color)"></i> Buscar Producto</div>
                <div class="aj-search">
                    <select id="ajSucursal" class="mb-2" onchange="buscarProdAjuste()">
                        <option value="">Todas las sucursales</option>
                    </select>
                    <input type="text" id="ajBuscar" placeholder="Nombre, código o barra..." oninput="buscarProdAjuste()">
                </div>
                <div id="ajResultados" style="margin-top:0.75rem;max-height:320px;overflow-y:auto"></div>
                <div id="ajEmptyState" class="empty-state" style="display:block">
                    <i class="bi bi-box"></i>
                    <p style="font-size:0.85rem;color:var(--text-secondary)">Busque un producto para ajustar</p>
                </div>
            </div>

            <!-- Formulario ajuste -->
            <div class="aj-card">
                <div class="aj-card-title"><i class="bi bi-tools" style="color:var(--accent-color)"></i> Datos del Ajuste</div>

                <div id="ajNoProducto" class="empty-state" style="padding:2rem 1rem">
                    <i class="bi bi-hand-index" style="font-size:2.5rem"></i>
                    <p style="font-size:0.85rem;color:var(--text-secondary)">Seleccione un producto de la lista</p>
                </div>

                <div id="ajFormContent" style="display:none">
                    <input type="hidden" id="ajProductoId">
                    <input type="hidden" id="ajSucursalId">

                    <div style="background:rgba(0,0,0,0.03);border-radius:0.75rem;padding:0.75rem 1rem;margin-bottom:1rem">
                        <div style="font-weight:700;font-size:0.95rem" id="ajProdNombre">-</div>
                        <div style="font-size:0.75rem;color:var(--text-secondary)" id="ajProdInfo"></div>
                        <div class="stock-info">
                            <span>Stock: <strong id="ajStockActual">0</strong></span>
                            <span>Facturado: <strong id="ajStockFact" style="color:#059669">0</strong></span>
                            <span>No Fact.: <strong id="ajStockNoFact" style="color:#d97706">0</strong></span>
                        </div>
                    </div>

                    <div class="aj-form">
                        <div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;margin-bottom:0.75rem">
                            <div>
                                <label>Tipo de Ajuste</label>
                                <select id="ajTipo" onchange="actualizarPreview()"></select>
                            </div>
                            <div>
                                <label>Cantidad</label>
                                <input type="number" id="ajCantidad" min="1" value="1" oninput="actualizarPreview()">
                            </div>
                        </div>
                        <div style="margin-bottom:0.75rem">
                            <label>Presentación</label>
                            <select id="ajPresentacion">
                                <option value="UNIDAD">UNIDAD</option>
                                <option value="BLISTER">BLISTER</option>
                                <option value="CAJA">CAJA</option>
                            </select>
                        </div>
                        <div style="margin-bottom:0.75rem">
                            <label>Motivo</label>
                            <textarea id="ajMotivo" rows="2" placeholder="Describa el motivo del ajuste..."></textarea>
                        </div>
                    </div>

                    <div id="ajPreview" style="display:none" class="aj-preview"></div>

                    <button onclick="guardarAjuste()" class="btn btn-primary" style="width:100%;margin-top:0.75rem">
                        <i class="bi bi-check2"></i> Registrar Ajuste
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Panel: Historial -->
    <div class="aj-panel" id="panel-historial">
        <div class="aj-card">
            <div class="aj-card-title"><i class="bi bi-clock-history" style="color:var(--accent-color)"></i> Historial de Ajustes</div>
            <div class="hist-filters">
                <select id="histSucursal"><option value="">Todas sucursales</option></select>
                <select id="histTipo"><option value="">Todos tipos</option></select>
                <input type="date" id="histFechaDesde">
                <input type="date" id="histFechaHasta">
                <button onclick="cargarHistorial(1)" class="btn btn-primary btn-sm"><i class="bi bi-search"></i> Buscar</button>
            </div>
            <div class="aj-table-wrap" id="historialTable">
                <div class="empty-state"><i class="bi bi-hourglass-split"></i><p>Cargando...</p></div>
            </div>
            <div class="aj-pag" id="historialPagination"></div>
        </div>
    </div>
</div>

<!-- Modal Detalle -->
<div class="modal-overlay" id="modalDetalle">
    <div class="modal-content">
        <div class="modal-header">
            <h3><i class="bi bi-info-circle"></i> Detalle del Ajuste</h3>
            <button class="modal-close" onclick="cerrarDetalle()">&times;</button>
        </div>
        <div id="detalleBody" style="font-size:0.9rem;line-height:2"></div>
        <button onclick="cerrarDetalle()" class="btn btn-secondary" style="width:100%;margin-top:1rem">Cerrar</button>
    </div>
</div>

<script src="assets/js/sweetalert2.min.js"></script>
<script>
let tiposAjuste = [];
let sucursales = [];

document.addEventListener('DOMContentLoaded', init);

async function init() {
    const r = await fetch('api/distribucion/index.php?action=sucursales');
    const d = await r.json();
    sucursales = d.data || d;
    let opts = '<option value="">Todas las sucursales</option>';
    sucursales.forEach(s => { opts += `<option value="${s.id}">${s.nombre.replace(/^\([^)]*\)\s*/,'')}</option>`; });
    document.getElementById('ajSucursal').innerHTML = opts;
    document.getElementById('histSucursal').innerHTML = '<option value="">Todas sucursales</option>' + opts;
    syncSucursalSelect('ajSucursal');
    syncSucursalSelect('histSucursal');

    const r2 = await fetch('api/inventario/ajustes/index.php?action=tipos');
    const d2 = await r2.json();
    tiposAjuste = d2.data || [];
    document.getElementById('ajTipo').innerHTML = tiposAjuste.map(t => `<option value="${t.id}" data-color="${t.color}">${t.label}</option>`).join('');
    document.getElementById('histTipo').innerHTML = '<option value="">Todos tipos</option>' + tiposAjuste.map(t => `<option value="${t.id}">${t.label}</option>`).join('');

    const today = new Date();
    document.getElementById('histFechaDesde').value = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
    document.getElementById('histFechaHasta').value = today.toISOString().split('T')[0];

    cargarHistorial(1);
}

function cambiarTab(tab) {
    document.querySelectorAll('.aj-tab').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
    document.querySelectorAll('.aj-panel').forEach(p => p.classList.remove('active'));
    document.getElementById('panel-' + tab).classList.add('active');
}

let timeoutBusq = null;
function buscarProdAjuste() {
    clearTimeout(timeoutBusq);
    timeoutBusq = setTimeout(async () => {
        const q = document.getElementById('ajBuscar').value.trim();
        const suc = document.getElementById('ajSucursal').value;
        const cont = document.getElementById('ajResultados');
        document.getElementById('ajEmptyState').style.display = 'none';
        if (q.length < 2) { cont.innerHTML = ''; document.getElementById('ajEmptyState').style.display = 'block'; return; }
        try {
            const r = await fetch(`api/inventario/ajustes/index.php?action=productos_buscar&q=${encodeURIComponent(q)}&sucursal_id=${suc}`);
            const d = await r.json();
            const prods = d.data || [];
            if (!prods.length) { cont.innerHTML = '<p style="text-align:center;padding:1rem;color:var(--text-secondary);font-size:0.85rem">Sin resultados</p>'; return; }
            cont.innerHTML = prods.map(p => `<div class="aj-result-item" onclick="seleccionarProd(${p.id},'${esc(p.producto)}','${esc(p.codigo)}','${esc(p.categoria||'')}',${p.stock_total||0},${p.stock_facturado||0},${p.stock_no_facturado||0},${p.sucursal_id||0})">
                <div style="font-weight:600;font-size:0.9rem">${esc(p.producto)}</div>
                <div style="font-size:0.7rem;color:var(--text-secondary)">${esc(p.codigo)} ${p.categoria?'· '+esc(p.categoria):''} · Stock: <strong>${p.stock_total||0}</strong> ${p.sucursal_nombre?'· '+esc(p.sucursal_nombre):''}</div>
            </div>`).join('');
        } catch(e) {}
    }, 300);
}

function seleccionarProd(id, nombre, codigo, categoria, stock, fact, nofact, sucid) {
    document.getElementById('ajProductoId').value = id;
    document.getElementById('ajSucursalId').value = sucid;
    document.getElementById('ajProdNombre').textContent = nombre;
    document.getElementById('ajProdInfo').textContent = codigo + (categoria ? ' · ' + categoria : '');
    document.getElementById('ajStockActual').textContent = stock;
    document.getElementById('ajStockFact').textContent = fact;
    document.getElementById('ajStockNoFact').textContent = nofact;
    document.getElementById('ajCantidad').value = 1;
    document.getElementById('ajMotivo').value = '';
    document.getElementById('ajNoProducto').style.display = 'none';
    document.getElementById('ajFormContent').style.display = 'block';
    document.getElementById('ajBuscar').value = nombre;
    document.getElementById('ajResultados').innerHTML = '';
    if (sucid) document.getElementById('ajSucursal').value = sucid;
    actualizarPreview();
}

document.getElementById('ajBuscar').addEventListener('input', function() {
    if (this.value !== document.getElementById('ajProdNombre').textContent) {
        document.getElementById('ajFormContent').style.display = 'none';
        document.getElementById('ajNoProducto').style.display = 'block';
    }
});

function actualizarPreview() {
    const tipo = document.getElementById('ajTipo').value;
    const cant = parseInt(document.getElementById('ajCantidad').value) || 0;
    const stock = parseInt(document.getElementById('ajStockActual').textContent) || 0;
    const t = tiposAjuste.find(x => x.id === tipo);
    const el = document.getElementById('ajPreview');
    if (!t || cant <= 0) { el.style.display = 'none'; return; }
    const esResta = ['PERDIDA','DANO','VENCIMIENTO','ROBO','CORRECCION_NEGATIVA'].includes(tipo);
    const nuevoStock = esResta ? Math.max(0, stock - cant) : stock + cant;
    const simbolo = esResta ? '- ' : '+ ';
    const color = esResta ? '#dc2626' : '#16a34a';
    el.className = 'aj-preview' + (esResta ? ' resta' : '');
    el.style.display = 'block';
    el.innerHTML = `<span class="dot" style="background:${t.color}"></span><strong>${t.label}</strong>
        <div style="margin-top:0.35rem;color:var(--text-secondary)">Stock actual: <strong>${stock}</strong> → Ajuste: <strong style="color:${color}">${simbolo}${cant}</strong> → Resultado: <strong>${nuevoStock}</strong></div>`;
}

async function guardarAjuste() {
    const pid = document.getElementById('ajProductoId').value;
    const tipo = document.getElementById('ajTipo').value;
    const cant = parseInt(document.getElementById('ajCantidad').value) || 0;
    const motivo = document.getElementById('ajMotivo').value.trim();
    const sid = document.getElementById('ajSucursalId').value || 1;
    const pres = document.getElementById('ajPresentacion').value;
    if (!pid) return Swal.fire('Error', 'Seleccione un producto', 'error');
    if (!tipo) return Swal.fire('Error', 'Seleccione tipo de ajuste', 'error');
    if (cant <= 0) return Swal.fire('Error', 'Cantidad debe ser mayor a 0', 'error');
    if (!motivo) return Swal.fire('Error', 'Describa el motivo del ajuste', 'error');

    try {
        const r = await fetch('api/inventario/ajustes/index.php?action=crear', {
            method: 'POST', headers: {'Content-Type':'application/json'},
            body: JSON.stringify({producto_id: pid, sucursal_id: sid, tipo_ajuste: tipo, cantidad: cant, motivo, presentacion: pres})
        });
        const res = await r.json();
        if (res.success) {
            const t = tiposAjuste.find(x => x.id === tipo);
            Swal.fire({
                title: 'Ajuste Registrado',
                html: `<div style="text-align:left;font-size:0.85rem">
                    <p><span style="color:var(--text-secondary)">Tipo:</span> ${t?.label||tipo}</p>
                    <p><span style="color:var(--text-secondary)">Cantidad:</span> <strong style="color:${res.data.cantidad_ajustada>0?'#16a34a':'#dc2626'}">${res.data.cantidad_ajustada>0?'+':''}${res.data.cantidad_ajustada}</strong></p>
                    <p><span style="color:var(--text-secondary)">Stock:</span> ${res.data.stock_anterior} → <strong>${res.data.stock_nuevo}</strong></p>
                </div>`,
                icon: 'success', confirmButtonColor: 'var(--accent-color)'
            });
            document.getElementById('ajFormContent').style.display = 'none';
            document.getElementById('ajNoProducto').style.display = 'block';
            document.getElementById('ajBuscar').value = '';
            document.getElementById('ajResultados').innerHTML = '';
            cargarHistorial(1);
        } else Swal.fire('Error', res.error || 'Error al guardar', 'error');
    } catch(e) { Swal.fire('Error', e.message, 'error'); }
}

async function cargarHistorial(page) {
    const params = new URLSearchParams({action:'listar', page: page || 1});
    const suc = document.getElementById('histSucursal').value;
    const tipo = document.getElementById('histTipo').value;
    if (suc) params.set('sucursal_id', suc);
    if (tipo) params.set('tipo', tipo);
    if (document.getElementById('histFechaDesde').value) params.set('fecha_desde', document.getElementById('histFechaDesde').value);
    if (document.getElementById('histFechaHasta').value) params.set('fecha_hasta', document.getElementById('histFechaHasta').value);

    try {
        const r = await fetch(`api/inventario/ajustes/index.php?${params}`);
        const d = await r.json();
        if (!d.success) { document.getElementById('historialTable').innerHTML = `<p style="color:#dc2626">${d.error}</p>`; return; }

        const data = d.data.data || [];
        const total = d.data.total || 0;
        const pages = d.data.pages || 1;

        if (!data.length) {
            document.getElementById('historialTable').innerHTML = '<div class="empty-state"><i class="bi bi-inbox"></i><p>No hay ajustes registrados</p></div>';
            document.getElementById('historialPagination').innerHTML = '';
            return;
        }

        let html = `<table><thead><tr>
            <th>#</th><th>Fecha</th><th>Producto</th><th>Sucursal</th><th>Tipo</th><th style="text-align:right">Cantidad</th><th>Motivo</th><th style="text-align:center">Ver</th>
        </tr></thead><tbody>`;

        data.forEach(a => {
            const t = tiposAjuste.find(x => x.id === a.tipo_ajuste) || {label:a.tipo_ajuste, color:'#94a3b8'};
            const esPos = a.cantidad_ajustada > 0;
            html += `<tr>
                <td style="font-family:monospace;color:var(--text-secondary)">${a.id}</td>
                <td>${a.fecha_ajuste||''}</td>
                <td><strong>${esc(a.producto)}</strong><br><span style="font-size:0.7rem;color:var(--text-secondary)">${esc(a.codigo||'')}</span></td>
                <td>${esc(a.sucursal||'')}</td>
                <td><span class="badge-ajuste" style="background:${t.color}22;color:${t.color}">${t.label}</span></td>
                <td style="text-align:right;font-weight:700;color:${esPos?'#16a34a':'#dc2626'}">${esPos?'+':''}${a.cantidad_ajustada}</td>
                <td style="max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-secondary)">${esc(a.motivo||'')}</td>
                <td style="text-align:center"><button onclick='verDetalle(${a.id})' class="btn btn-secondary btn-sm" style="padding:0.25rem 0.6rem;font-size:0.7rem"><i class="bi bi-eye"></i></button></td>
            </tr>`;
        });
        html += '</tbody></table>';
        document.getElementById('historialTable').innerHTML = html;

        let pag = '';
        for (let i=1; i<=pages; i++) {
            pag += `<button onclick="cargarHistorial(${i})" class="${i===(page||1)?'active':''}">${i}</button>`;
        }
        document.getElementById('historialPagination').innerHTML = pag;
    } catch(e) { console.error(e); }
}

async function verDetalle(id) {
    try {
        const r = await fetch(`api/inventario/ajustes/index.php?action=detalle&id=${id}`);
        const d = await r.json();
        if (!d.success) return Swal.fire('Error', d.error, 'error');
        const a = d.data;
        const t = tiposAjuste.find(x => x.id === a.tipo_ajuste) || {label:a.tipo_ajuste, color:'#94a3b8'};
        const esPos = a.cantidad_ajustada > 0;
        document.getElementById('detalleBody').innerHTML = `
            <div style="display:flex;align-items:center;gap:0.5rem;padding-bottom:0.5rem;border-bottom:1px solid var(--border-color);margin-bottom:0.5rem">
                <span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${t.color}"></span>
                <strong>${t.label}</strong>
            </div>
            <p><span style="color:var(--text-secondary)">Producto:</span> ${esc(a.producto)} <span style="color:var(--text-secondary);font-size:0.8rem">${esc(a.codigo||'')}</span></p>
            <p><span style="color:var(--text-secondary)">Sucursal:</span> ${esc(a.sucursal||'')}</p>
            <p><span style="color:var(--text-secondary)">Cantidad:</span> <strong style="color:${esPos?'#16a34a':'#dc2626'}">${esPos?'+':''}${a.cantidad_ajustada}</strong></p>
            <p><span style="color:var(--text-secondary)">Presentación:</span> ${a.presentacion||'UNIDAD'}</p>
            <p><span style="color:var(--text-secondary)">Costo ref.:</span> Q${parseFloat(a.costo_unitario_referencia||0).toFixed(4)}</p>
            <p><span style="color:var(--text-secondary)">Motivo:</span> ${esc(a.motivo||'')}</p>
            <p><span style="color:var(--text-secondary)">Usuario:</span> ${esc(a.usuario||'N/A')}</p>
            <p><span style="color:var(--text-secondary)">Autorizado por:</span> ${esc(a.autorizado_por_nombre||'N/A')}</p>
            <p><span style="color:var(--text-secondary)">Fecha:</span> ${a.fecha_ajuste||''}</p>`;
        document.getElementById('modalDetalle').classList.add('open');
    } catch(e) { Swal.fire('Error', e.message, 'error'); }
}

function cerrarDetalle() { document.getElementById('modalDetalle').classList.remove('open'); }

function esc(s) { if (!s) return '-'; const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
</script>
<?php renderFooter(); ?>

