<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();
renderHeader('Cuentas por Pagar', 'cuentas_pagar');
?>

<link rel="stylesheet" href="assets/css/bootstrap-icons.min.css">
<script src="assets/js/sweetalert2.min.js"></script>

<style>
.report-wrap {
    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;
    flex-wrap: wrap;
    gap: 1rem;
}
.report-header h1 {
    font-size: 1.75rem;
    font-weight: 800;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

/* Style filters panel to use elevated theme */
.filters-card {
    background: var(--surface-elevated);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.25rem 1.5rem;
}
.filters-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.25rem;
    align-items: 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-input {
    width: 100%;
    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;
    transition: border-color var(--transition), box-shadow var(--transition);
    box-sizing: border-box;
}
.filter-input:focus {
    border-color: var(--accent-color);
    box-shadow: var(--focus-ring);
}
.btn-filter-group {
    display: flex;
    gap: 0.75rem;
    height: 38px;
}
.btn-filter {
    padding: 0.65rem 1.25rem;
    background: var(--accent-color);
    color: var(--primary);
    border: none;
    border-radius: var(--radius-sm);
    font-weight: 700;
    font-size: 0.875rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all var(--transition);
}
.btn-filter:hover {
    opacity: 0.9;
    transform: translateY(-1px);
}
.btn-clear {
    padding: 0.65rem 1.25rem;
    background: transparent;
    color: var(--text-secondary);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    font-weight: 700;
    font-size: 0.875rem;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all var(--transition);
}
.btn-clear:hover {
    background: var(--surface-hover);
    color: var(--text-primary);
}

/* KPI cards */
.kpis-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 1.5rem;
}
.kpi-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.5rem;
    position: relative;
    overflow: hidden;
}
.kpi-card-icon {
    position: absolute;
    right: 1.25rem;
    top: 1.25rem;
    font-size: 2rem;
    opacity: 0.15;
}
.kpi-card-label {
    font-size: 0.75rem;
    text-transform: uppercase;
    font-weight: 700;
    color: var(--text-secondary);
    letter-spacing: 0.05em;
}
.kpi-card-value {
    font-size: 2.25rem;
    font-weight: 800;
    margin-top: 0.5rem;
}
.kpi-card-sub {
    font-size: 0.75rem;
    color: var(--text-muted);
    margin-top: 0.25rem;
    font-weight: 500;
}

/* Row indicator styling */
.vencido {
    border-left: 4px solid var(--danger);
    background: rgba(239, 68, 68, 0.02);
}
.vencido:hover {
    background: rgba(239, 68, 68, 0.04) !important;
}
.por-vencer {
    border-left: 4px solid var(--warning);
    background: rgba(245, 158, 11, 0.01);
}
.por-vencer:hover {
    background: rgba(245, 158, 11, 0.03) !important;
}
.al-dia {
    border-left: 4px solid var(--success);
}

/* Action buttons */
.btn-action-pay {
    background: rgba(34, 197, 94, 0.12);
    color: var(--success);
    border: 1px solid rgba(34, 197, 94, 0.25);
    padding: 0.45rem;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.95rem;
    transition: all var(--transition);
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.btn-action-pay:hover {
    background: rgba(34, 197, 94, 0.2);
    transform: translateY(-1px);
}
.btn-action-history {
    background: rgba(210, 200, 221, 0.12);
    color: var(--accent-color);
    border: 1px solid rgba(210, 200, 221, 0.2);
    padding: 0.45rem;
    border-radius: 8px;
    cursor: pointer;
    font-size: 0.95rem;
    transition: all var(--transition);
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.btn-action-history:hover {
    background: rgba(210, 200, 221, 0.2);
    transform: translateY(-1px);
}

/* Modal local customization */
.modal-form-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1.25rem;
}
.modal-info-box {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 1rem;
    font-size: 0.875rem;
    line-height: 1.6;
}

/* Soft warning badge definition */
.badge-soft-warning {
    background: rgba(245, 158, 11, 0.12);
    color: var(--warning);
    border: 1px solid rgba(245, 158, 11, 0.25);
}

.spinner {
    display: inline-block;
    width: 2rem;
    height: 2rem;
    border: 3px solid rgba(210, 200, 221, 0.15);
    border-radius: 50%;
    border-top-color: var(--accent-color);
    animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<div class="report-wrap">
    <div class="report-header">
        <h1><i class="bi bi-hand-holding-dollar" style="color: var(--accent-color);"></i> Cuentas por Pagar</h1>
    </div>

    <!-- Summary KPIs -->
    <div class="kpis-grid">
        <div class="kpi-card">
            <div class="kpi-card-icon"><i class="bi bi-currency-dollar" style="color: var(--text-primary);"></i></div>
            <div class="kpi-card-label">Total Pendiente</div>
            <div class="kpi-card-value" id="sumTotal">Q0.00</div>
        </div>
        <div class="kpi-card" style="border-color: rgba(239, 68, 68, 0.3);">
            <div class="kpi-card-icon"><i class="bi bi-exclamation-octagon" style="color: var(--danger);"></i></div>
            <div class="kpi-card-label">Vencido</div>
            <div class="kpi-card-value" style="color: var(--danger);" id="sumVencido">Q0.00</div>
            <div class="kpi-card-sub" style="color: var(--danger);" id="sumVencidoCount">0 facturas</div>
        </div>
        <div class="kpi-card" style="border-color: rgba(245, 158, 11, 0.3);">
            <div class="kpi-card-icon"><i class="bi bi-hourglass-split" style="color: var(--warning);"></i></div>
            <div class="kpi-card-label">Por Vencer</div>
            <div class="kpi-card-value" style="color: var(--warning);" id="sumPorVencer">Q0.00</div>
        </div>
        <div class="kpi-card" style="border-color: rgba(34, 197, 94, 0.3);">
            <div class="kpi-card-icon"><i class="bi bi-check-circle" style="color: var(--success);"></i></div>
            <div class="kpi-card-label">Pagadas</div>
            <div class="kpi-card-value" style="color: var(--success);" id="sumPagadas">Q0.00</div>
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="filters-card">
        <div class="filters-grid">
            <div class="filter-group">
                <label class="filter-label">Proveedor</label>
                <select id="filtroProveedor" class="filter-input">
                    <option value="0">Todos</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">Estado</label>
                <select id="filtroEstado" class="filter-input">
                    <option value="">Todos</option>
                    <option value="pendiente">Pendiente</option>
                    <option value="parcial">Parcial</option>
                    <option value="pagada">Pagada</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">Buscar</label>
                <input type="text" id="filtroSearch" placeholder="Factura o proveedor..." class="filter-input">
            </div>
            <div class="filter-group">
                <label class="filter-label">Venc. Desde</label>
                <input type="date" id="filtroVencDesde" class="filter-input">
            </div>
            <div class="filter-group">
                <label class="filter-label">Venc. Hasta</label>
                <input type="date" id="filtroVencHasta" class="filter-input">
            </div>
        </div>
        <div class="btn-filter-group" style="margin-top: 1.25rem;">
            <button onclick="cargarCuentas()" class="btn-filter">
                <i class="bi bi-search"></i> Filtrar
            </button>
            <button onclick="limpiarFiltros()" class="btn-clear">
                <i class="bi bi-arrow-counterclockwise"></i> Limpiar
            </button>
        </div>
    </div>

    <!-- Table -->
    <div class="table-wrapper">
        <div id="loader" class="hidden" style="text-align: center; padding: 3rem;">
            <div class="spinner"></div>
        </div>
        <div id="tableContainer">
            <table class="table-premium">
                <thead>
                    <tr>
                        <th>Proveedor</th>
                        <th>Factura</th>
                        <th>Fecha</th>
                        <th>Vencimiento</th>
                        <th style="text-align: right;">Total</th>
                        <th style="text-align: right;">Saldo</th>
                        <th style="text-align: center;">Estado</th>
                        <th style="text-align: center;">Acciones</th>
                    </tr>
                </thead>
                <tbody id="cuentasBody"></tbody>
            </table>
        </div>
        <div id="emptyState" class="hidden" style="text-align: center; padding: 3rem; color: var(--text-muted);">
            <i class="bi bi-inbox" style="font-size: 2rem; display: block; margin-bottom: 0.5rem;"></i>
            No se encontraron cuentas para los filtros seleccionados.
        </div>
    </div>
</div>

<!-- Modal Registrar Pago -->
<div id="modalAbono" class="modal-overlay hidden" onclick="if(event.target===this)cerrarModalAbono()">
    <div class="modal-container" style="max-width: 500px;" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h2>Registrar Pago</h2>
            <button onclick="cerrarModalAbono()" class="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="abonoCuentaId">
            <div id="abonoInfo" class="modal-info-box" style="margin-bottom: 1.25rem;"></div>
            <div class="modal-form-grid">
                <div class="filter-group">
                    <label class="filter-label">Monto a Pagar *</label>
                    <input type="number" step="0.01" id="abonoMonto" class="filter-input" style="font-weight: 700; font-size: 1.1rem; border-color: var(--border-dark);">
                </div>
                <div class="filter-group">
                    <label class="filter-label">Fecha de Pago *</label>
                    <input type="date" id="abonoFecha" class="filter-input">
                </div>
                <div class="filter-group">
                    <label class="filter-label">Tipo de Pago</label>
                    <select id="abonoTipo" class="filter-input">
                        <option value="efectivo">Efectivo</option>
                        <option value="transferencia">Transferencia</option>
                        <option value="cheque">Cheque</option>
                        <option value="tarjeta">Tarjeta</option>
                        <option value="otros">Otros</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label class="filter-label">Referencia</label>
                    <input type="text" id="abonoReferencia" class="filter-input" placeholder="Ej: No. de transferencia">
                </div>
                <div class="filter-group">
                    <label class="filter-label">Notas</label>
                    <textarea id="abonoNotas" rows="2" class="filter-input" style="resize: none;" placeholder="Comentarios adicionales..."></textarea>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button onclick="cerrarModalAbono()" class="btn-clear">Cancelar</button>
            <button onclick="guardarAbono()" id="btnGuardarAbono" class="btn-filter" style="background: var(--success); color: white;">
                <i class="bi bi-check2"></i> Registrar Pago
            </button>
        </div>
    </div>
</div>

<!-- Modal Historial de Pagos -->
<div id="modalHistorial" class="modal-overlay hidden" onclick="if(event.target===this)cerrarModalHistorial()">
    <div class="modal-container" style="max-width: 750px;" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h2 id="historialTitle">Historial de Pagos</h2>
            <button onclick="cerrarModalHistorial()" class="modal-close">&times;</button>
        </div>
        <div class="modal-body" style="padding-top: 1rem;">
            <div id="historialContent">
                <div style="text-align: center; padding: 2rem; color: var(--text-muted);">Cargando...</div>
            </div>
        </div>
        <div class="modal-footer">
            <button onclick="cerrarModalHistorial()" class="btn-clear">Cerrar</button>
        </div>
    </div>
</div>

<script>
let proveedores = [];

async function cargarProveedores() {
    try {
        const res = await fetch('api/proveedores/listar.php?activo=0');
        const data = await res.json();
        if (data.success) {
            proveedores = data.data;
            const sel = document.getElementById('filtroProveedor');
            data.data.forEach(p => { 
                const o = document.createElement('option'); 
                o.value = p.id; 
                o.textContent = p.nombre; 
                sel.appendChild(o); 
            });
        }
    } catch(e) { console.error(e); }
}

async function cargarCuentas() {
    const p = new URLSearchParams();
    const pid = parseInt(document.getElementById('filtroProveedor').value);
    if (pid > 0) p.append('proveedor_id', pid);
    const est = document.getElementById('filtroEstado').value;
    if (est) p.append('estado', est);
    const s = document.getElementById('filtroSearch').value.trim();
    if (s) p.append('search', s);
    const vd = document.getElementById('filtroVencDesde').value;
    if (vd) p.append('venc_desde', vd);
    const vh = document.getElementById('filtroVencHasta').value;
    if (vh) p.append('venc_hasta', vh);

    l(true); tc(true); es(true);
    try {
        const res = await fetch('api/cuentas_pagar/listar.php?' + p.toString());
        const data = await res.json();
        l(false);
        if (data.success) {
            const r = data.data.resumen, cuentas = data.data.cuentas;
            const hoy = new Date().toISOString().slice(0,10);
            document.getElementById('sumTotal').textContent = 'Q ' + r.total_pendiente.toFixed(2);
            document.getElementById('sumVencido').textContent = 'Q ' + r.total_vencido.toFixed(2);
            document.getElementById('sumVencidoCount').textContent = r.count_vencido + ' factura(s)';
            let pv = 0, pg = 0;
            cuentas.forEach(c => { 
                if(c.estado==='pagada') pg+=parseFloat(c.total_factura); 
                else if(c.estado!=='anulada'&&c.fecha_vencimiento&&c.fecha_vencimiento>=hoy) pv+=parseFloat(c.saldo_pendiente); 
            });
            document.getElementById('sumPorVencer').textContent = 'Q ' + pv.toFixed(2);
            document.getElementById('sumPagadas').textContent = 'Q ' + pg.toFixed(2);
            
            if (cuentas.length > 0) {
                document.getElementById('cuentasBody').innerHTML = cuentas.map(c => {
                    const venc = c.fecha_vencimiento && c.fecha_vencimiento < hoy && c.estado!=='pagada' && c.estado!=='anulada';
                    const pv3 = !venc && c.fecha_vencimiento && c.fecha_vencimiento>=hoy && c.estado!=='pagada' && c.estado!=='anulada';
                    const rc = venc ? 'vencido' : (pv3 ? 'por-vencer' : 'al-dia');
                    
                    const badge = c.estado==='pagada' 
                        ? '<span class="badge-premium badge-soft-success">PAGADA</span>' 
                        : c.estado==='parcial' 
                        ? '<span class="badge-premium badge-soft-warning">PARCIAL</span>' 
                        : c.estado==='anulada' 
                        ? '<span class="badge-premium badge-soft-muted">ANULADA</span>' 
                        : '<span class="badge-premium badge-soft-danger">PENDIENTE</span>';
                        
                    const dv = venc ? Math.floor((new Date()-new Date(c.fecha_vencimiento))/(1000*60*60*24)) : 0;
                    
                    return '<tr class="'+rc+'">' +
                        '<td style="font-weight:600; color:var(--text-primary);">' + esc(c.proveedor_nombre) + '</td>' +
                        '<td style="font-weight:500;">' + esc(c.numero_factura||'-') + '</td>' +
                        '<td>' + c.fecha_compra + '</td>' +
                        '<td class="' + (venc ? 'text-rose-400 font-bold' : '') + '">' + 
                            (c.fecha_vencimiento||'-') + (venc ? ' ('+dv+'d)' : '') + 
                        '</td>' +
                        '<td style="text-align:right; font-weight: 500;">Q ' + parseFloat(c.total_factura).toFixed(2) + '</td>' +
                        '<td style="text-align:right; font-weight:700; color: ' + (parseFloat(c.saldo_pendiente)>0 ? 'var(--danger)' : 'var(--success)') + ';">Q ' + parseFloat(c.saldo_pendiente).toFixed(2) + '</td>' +
                        '<td style="text-align:center;">' + badge + '</td>' +
                        '<td style="text-align:center; white-space:nowrap;">' + 
                            '<div style="display:inline-flex; gap:0.35rem; justify-content:center; align-items:center;">' +
                                (c.estado!=='pagada'&&c.estado!=='anulada' ? '<button onclick="abrirModalAbono('+c.id+',\''+escAttr(c.proveedor_nombre)+'\',\''+escAttr(c.numero_factura||'Sin factura')+'\','+c.saldo_pendiente+')" class="btn-action-pay" title="Pagar"><i class="bi bi-cash-coin"></i></button>' : '') + 
                                '<button onclick="verHistorial('+c.id+',\''+escAttr(c.proveedor_nombre)+'\')" class="btn-action-history" title="Historial"><i class="bi bi-clock-history"></i></button>' + 
                            '</div>' +
                        '</td>' +
                    '</tr>';
                }).join('');
                tc(false);
            } else { es(false); }
        } else { es(false); }
    } catch(e) { l(false); es(false); console.error(e); }
}

function l(s) { document.getElementById('loader').classList.toggle('hidden', !s); }
function tc(s) { document.getElementById('tableContainer').classList.toggle('hidden', s); }
function es(s) { document.getElementById('emptyState').classList.toggle('hidden', s); }

function limpiarFiltros() {
    document.getElementById('filtroProveedor').value = '0';
    document.getElementById('filtroEstado').value = '';
    document.getElementById('filtroSearch').value = '';
    document.getElementById('filtroVencDesde').value = '';
    document.getElementById('filtroVencHasta').value = '';
    cargarCuentas();
}

function abrirModalAbono(id, prov, fac, saldo) {
    document.getElementById('abonoCuentaId').value = id;
    document.getElementById('abonoInfo').innerHTML = '<strong>Proveedor:</strong> '+esc(prov)+'<br><strong>Factura:</strong> '+esc(fac)+'<br><strong>Saldo pendiente:</strong> Q '+parseFloat(saldo).toFixed(2);
    document.getElementById('abonoMonto').value = parseFloat(saldo).toFixed(2);
    document.getElementById('abonoFecha').value = new Date().toISOString().slice(0,10);
    document.getElementById('abonoTipo').value = 'efectivo';
    document.getElementById('abonoReferencia').value = '';
    document.getElementById('abonoNotas').value = '';
    document.getElementById('modalAbono').classList.remove('hidden');
    setTimeout(()=>document.getElementById('abonoMonto').focus(),100);
}

function cerrarModalAbono() { document.getElementById('modalAbono').classList.add('hidden'); }

async function guardarAbono() {
    const id = document.getElementById('abonoCuentaId').value;
    const monto = parseFloat(document.getElementById('abonoMonto').value);
    const fecha = document.getElementById('abonoFecha').value;
    if (!monto||monto<=0) { Swal.fire({icon:'warning',title:'Monto inválido',background:'#052137',color:'#ffffff'}); return; }
    if (!fecha) { Swal.fire({icon:'warning',title:'Fecha requerida',background:'#052137',color:'#ffffff'}); return; }
    const btn = document.getElementById('btnGuardarAbono');
    btn.disabled = true; btn.innerHTML = '<span class="inline-block animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></span>';
    try {
        const res = await fetch('api/cuentas_pagar/registrar_abono.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({
                cuenta_pagar_id:parseInt(id),
                monto_abono:monto,
                fecha_pago:fecha,
                tipo_pago:document.getElementById('abonoTipo').value,
                referencia_pago:document.getElementById('abonoReferencia').value.trim()||null,
                notas:document.getElementById('abonoNotas').value.trim()||null
            })
        });
        const data = await res.json();
        if (data.success) { 
            Swal.fire({icon:'success',title:'Pago registrado',toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#052137',color:'#ffffff'}); 
            cerrarModalAbono(); 
            cargarCuentas(); 
        } else { 
            Swal.fire({icon:'error',title:'Error',text:data.message,background:'#052137',color:'#ffffff'}); 
        }
    } catch(e) { 
        Swal.fire({icon:'error',title:'Error',text:'Fallo de red',background:'#052137',color:'#ffffff'}); 
    } finally { 
        btn.disabled = false; 
        btn.innerHTML = '<i class="bi bi-check2"></i> Registrar Pago'; 
    }
}

function cerrarModalHistorial() { document.getElementById('modalHistorial').classList.add('hidden'); }

async function verHistorial(cuentaId, proveedor) {
    document.getElementById('historialTitle').textContent = 'Historial de Pagos - ' + proveedor;
    document.getElementById('historialContent').innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--text-muted);"><div class="spinner" style="width:1.5rem; height:1.5rem; border-width:2px;"></div></div>';
    document.getElementById('modalHistorial').classList.remove('hidden');
    try {
        const res = await fetch('api/cuentas_pagar/historial_abonos.php?cuenta_pagar_id='+cuentaId);
        const data = await res.json();
        if (data.success) {
            const abonos = data.data.abonos, total = parseFloat(data.data.total_abonado);
            let html = '<div style="font-size:0.875rem; color:var(--text-secondary); margin-bottom:1rem; font-weight:600;">Total abonado: <span style="color:var(--success); font-weight:800;">Q '+total.toFixed(2)+'</span> | '+abonos.length+' pago(s)</div>';
            if (abonos.length===0) {
                html += '<div style="text-align: center; padding: 2rem; color: var(--text-muted);">No hay pagos registrados</div>';
            } else {
                html += '<div class="table-wrapper"><table class="table-premium"><thead><tr><th>Fecha</th><th>Monto</th><th>Tipo</th><th>Referencia</th><th>Notas</th></tr></thead><tbody>';
                abonos.forEach(a => {
                    const tl = {efectivo:'Efectivo',transferencia:'Transferencia',cheque:'Cheque',tarjeta:'Tarjeta',otros:'Otros'}[a.tipo_pago]||a.tipo_pago;
                    const bc = a.tipo_pago==='efectivo'
                        ? 'badge-soft-success'
                        : a.tipo_pago==='transferencia'
                        ? 'badge-soft-primary'
                        : a.tipo_pago==='cheque'
                        ? 'badge-soft-warning'
                        : 'badge-soft-muted';
                    html += '<tr>' +
                        '<td style="font-weight: 500;">'+a.fecha_pago+'</td>' +
                        '<td style="font-weight:700; color:var(--text-primary);">Q '+parseFloat(a.monto_abono).toFixed(2)+'</td>' +
                        '<td><span class="badge-premium '+bc+'">'+tl+'</span></td>' +
                        '<td>'+esc(a.referencia_pago||'-')+'</td>' +
                        '<td>'+esc(a.notas||'-')+'</td>' +
                    '</tr>';
                });
                html += '</tbody></table></div>';
            }
            document.getElementById('historialContent').innerHTML = html;
        } else { 
            document.getElementById('historialContent').innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--danger); font-weight:600;">Error al cargar historial</div>'; 
        }
    } catch(e) { 
        document.getElementById('historialContent').innerHTML = '<div style="text-align: center; padding: 2rem; color: var(--danger); font-weight:600;">Error de conexión</div>'; 
    }
}

function esc(t) { if(!t)return''; const d=document.createElement('div'); d.textContent=t; return d.innerHTML; }
function escAttr(t) { if(!t)return''; return esc(t).replace(/'/g,"\\'"); }

['filtroProveedor','filtroEstado','filtroVencDesde','filtroVencHasta'].forEach(id => { 
    document.getElementById(id).addEventListener('change', cargarCuentas); 
});
document.getElementById('filtroSearch').addEventListener('input', cargarCuentas);

cargarProveedores();
cargarCuentas();
</script>

<?php renderFooter(); ?>
