<?php
require_once __DIR__ . '/../../includes/layout.php';
$pdo = getDBConnection();

$sucursales = [];
try {
    $sucursales = $pdo->query("SELECT id, nombre FROM sucursales ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

renderHeader('Gastos Operativos', 'gastos_operativos');
?>

<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;
}
.header-actions {
    display: flex;
    gap: 0.75rem;
}

/* 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(180px, 1fr));
    gap: 1.25rem;
    align-items: end;
}
.filters-grid-row2 {
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 1.25rem;
    align-items: end;
    margin-top: 1.25rem;
}
.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;
}

/* Breakdown Grid */
.breakdown-card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 1.5rem;
}
.breakdown-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
    gap: 1rem;
    margin-top: 1rem;
}
.breakdown-item {
    background: var(--surface-elevated);
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 0.75rem 1rem;
}
.breakdown-item-name {
    font-size: 0.75rem;
    color: var(--text-muted);
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}
.breakdown-item-value {
    font-size: 1.15rem;
    font-weight: 700;
    color: var(--text-primary);
    margin-top: 0.25rem;
}

/* Action buttons */
.btn-action-delete {
    background: rgba(239, 68, 68, 0.12);
    color: var(--danger);
    border: 1px solid rgba(239, 68, 68, 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-delete:hover {
    background: rgba(239, 68, 68, 0.2);
    transform: translateY(-1px);
}
.btn-action-edit {
    background: rgba(124, 58, 237, 0.12);
    color: #a78bfa;
    border: 1px solid rgba(124, 58, 237, 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-edit:hover {
    background: rgba(124, 58, 237, 0.2);
    transform: translateY(-1px);
}
#grupoDiaPago {
    display: flex;
}
#grupoDiaPago.hidden {
    display: none !important;
}

/* Modals layout styles */
.modal-form-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 1.25rem;
}
.modal-form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

/* Soft badges */
.badge-soft-warning {
    background: rgba(245, 158, 11, 0.12);
    color: var(--warning);
    border: 1px solid rgba(245, 158, 11, 0.25);
}
.badge-soft-info {
    background: rgba(124, 58, 237, 0.12);
    color: #a78bfa;
    border: 1px solid rgba(124, 58, 237, 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-chart-line" style="color: var(--accent-color);"></i> Gastos Operativos</h1>
        <div class="header-actions">
            <button onclick="abrirModalCategoria()" class="btn-clear">
                <i class="bi bi-tags"></i> Categorías
            </button>
            <button onclick="abrirModalGasto()" class="btn-filter" style="background: var(--danger); color: white;">
                <i class="bi bi-plus-circle"></i> Nuevo Gasto
            </button>
        </div>
    </div>

    <!-- Summary KPIs -->
    <div class="kpis-grid">
        <div class="kpi-card">
            <div class="kpi-card-icon"><i class="bi bi-wallet" style="color: var(--text-primary);"></i></div>
            <div class="kpi-card-label">Total Gastos</div>
            <div class="kpi-card-value" id="sumTotal">Q0.00</div>
        </div>
        <div class="kpi-card" style="border-color: rgba(245, 158, 11, 0.3);">
            <div class="kpi-card-icon"><i class="bi bi-calendar-event" style="color: var(--warning);"></i></div>
            <div class="kpi-card-label">Este Mes</div>
            <div class="kpi-card-value" style="color: var(--warning);" id="sumMes">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-clock-history" style="color: var(--danger);"></i></div>
            <div class="kpi-card-label">Hoy</div>
            <div class="kpi-card-value" style="color: var(--danger);" id="sumHoy">Q0.00</div>
        </div>
        <div class="kpi-card" style="border-color: rgba(30, 58, 95, 0.3);">
            <div class="kpi-card-icon"><i class="bi bi-list-check" style="color: #a78bfa;"></i></div>
            <div class="kpi-card-label">Registros</div>
            <div class="kpi-card-value" style="color: #a78bfa;" id="sumCount">0</div>
        </div>
    </div>

    <!-- Category Breakdown Card -->
    <div class="breakdown-card">
        <h3 style="font-size: 0.875rem; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin: 0;">Desglose por Categoría</h3>
        <div id="categoriaBreakdown" class="breakdown-grid">
            <div style="text-align: center; padding: 1rem; color: var(--text-muted); grid-column: span 5;">Cargando desglose...</div>
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="filters-card">
        <div class="filters-grid">
            <div class="filter-group">
                <label class="filter-label">Categoría</label>
                <select id="filtroCategoria" class="filter-input">
                    <option value="">Todas</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">Forma de Pago</label>
                <select id="filtroPago" class="filter-input">
                    <option value="">Todas</option>
                    <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">Desde</label>
                <input type="date" id="filtroDesde" class="filter-input">
            </div>
            <div class="filter-group">
                <label class="filter-label">Hasta</label>
                <input type="date" id="filtroHasta" class="filter-input">
            </div>
        </div>
        <div class="filters-grid-row2">
            <div class="filter-group" style="flex: 1;">
                <label class="filter-label">Buscar</label>
                <input type="text" id="filtroSearch" placeholder="Descripción, proveedor..." class="filter-input">
            </div>
            <div class="btn-filter-group">
                <button onclick="cargarGastos()" 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>
    </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>Fecha</th>
                        <th>Categoría</th>
                        <th>Descripción</th>
                        <th>Proveedor</th>
                        <th style="text-align: right;">Monto</th>
                        <th style="text-align: center;">Pago</th>
                        <th>Referencia</th>
                        <th style="text-align: center;">Acciones</th>
                    </tr>
                </thead>
                <tbody id="gastosBody"></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 gastos para los filtros seleccionados.
        </div>
    </div>
</div>

<!-- Modal Registrar Gasto -->
<div id="modalGasto" class="modal-overlay hidden" onclick="if(event.target===this)cerrarModalGasto()">
    <div class="modal-container" style="max-width: 550px;" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h2>Nuevo Gasto</h2>
            <button onclick="cerrarModalGasto()" class="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <div class="modal-form-grid">
                <div class="filter-group">
                    <label class="filter-label">Categoría *</label>
                    <select id="gastoCategoria" class="filter-input"></select>
                </div>
                <div class="filter-group">
                    <label class="filter-label">Descripción *</label>
                    <input type="text" id="gastoDescripcion" placeholder="Ej: Pago de luz junio" class="filter-input">
                </div>
                <div class="modal-form-row">
                    <div class="filter-group">
                        <label class="filter-label">Monto (Q) *</label>
                        <input type="number" step="0.01" id="gastoMonto" class="filter-input" style="font-weight: 700; border-color: var(--border-dark);">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">Fecha *</label>
                        <input type="date" id="gastoFecha" class="filter-input">
                    </div>
                </div>
                <div class="modal-form-row">
                    <div class="filter-group">
                        <label class="filter-label">Forma de Pago</label>
                        <select id="gastoFormaPago" 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">Proveedor</label>
                        <input type="text" id="gastoProveedor" placeholder="Nombre o razón social" class="filter-input">
                    </div>
                </div>
                <div class="modal-form-row">
                    <div class="filter-group">
                        <label class="filter-label">Referencia / No. Documento</label>
                        <input type="text" id="gastoReferencia" placeholder="Factura, recibo, boleta..." class="filter-input">
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">Sucursal *</label>
                        <select id="gastoSucursal" class="filter-input">
                            <?php foreach ($sucursales as $s): ?>
                                <option value="<?= $s['id'] ?>"><?= htmlspecialchars(preg_replace('/^\([^)]*\)\s*/', '', $s['nombre'])) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="filter-group">
                    <label class="filter-label">Notas</label>
                    <textarea id="gastoNotas" rows="2" class="filter-input" style="resize: none;" placeholder="Comentarios adicionales..."></textarea>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button onclick="cerrarModalGasto()" class="btn-clear">Cancelar</button>
            <button onclick="guardarGasto()" id="btnGuardarGasto" class="btn-filter" style="background: var(--danger); color: white;">
                <i class="bi bi-check2"></i> Registrar Gasto
            </button>
        </div>
    </div>
</div>

<!-- Modal Categorias -->
<div id="modalCategoria" class="modal-overlay hidden" onclick="if(event.target===this)cerrarModalCategoria()">
    <div class="modal-container" style="max-width: 500px;" onclick="event.stopPropagation()">
        <div class="modal-header">
            <h2>Gestionar Categorías</h2>
            <button onclick="cerrarModalCategoria()" class="modal-close">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="editCategoriaId" value="">
            <div style="background: var(--surface-elevated); border: 1px solid var(--border); border-radius: var(--radius); padding: 1rem; margin-bottom: 1.25rem;">
                <h3 id="formCategoriaTitulo" style="font-size: 0.875rem; font-weight: 700; margin-top: 0; margin-bottom: 0.75rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em;">Nueva Categoría</h3>
                <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                    <input type="text" id="nuevaCategoriaNombre" placeholder="Nombre de la categoría" class="filter-input">
                    <div style="display: flex; align-items: center; justify-content: space-between; gap: 1rem;">
                        <label style="display: inline-flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; cursor: pointer; color: var(--text-primary); user-select: none;">
                            <input type="checkbox" id="categoriaEsFija" onchange="toggleDiaPagoInput()" style="accent-color: var(--accent-color); width: 16px; height: 16px;">
                            <span>Fija Mensual</span>
                        </label>
                        <div id="grupoDiaPago" class="hidden" style="align-items: center; gap: 0.5rem;">
                            <span style="font-size: 0.875rem; color: var(--text-secondary);">Día pago:</span>
                            <input type="number" id="categoriaDiaPago" min="1" max="31" class="filter-input" style="width: 75px; padding: 0.35rem 0.5rem; text-align: center;">
                        </div>
                    </div>
                    <div style="display: flex; justify-content: flex-end; gap: 0.5rem; margin-top: 0.25rem;">
                        <button id="btnCancelarEditCategoria" onclick="resetFormCategoria()" class="btn-clear hidden" style="height: 38px; padding: 0.5rem 1rem;">Cancelar</button>
                        <button id="btnGuardarCategoria" onclick="guardarCategoria()" class="btn-filter" style="height: 38px; padding: 0.5rem 1.25rem;">
                            <i class="bi bi-plus-circle"></i> <span id="btnGuardarCategoriaTexto">Agregar</span>
                        </button>
                    </div>
                </div>
            </div>
            <div id="categoriasList" style="max-height: 250px; overflow-y: auto; display: flex; flex-direction: column; gap: 0.5rem;"></div>
        </div>
        <div class="modal-footer">
            <button onclick="cerrarModalCategoria()" class="btn-clear">Cerrar</button>
        </div>
    </div>
</div>

<script>
let categorias = [];

async function cargarCategorias() {
    try {
        const res = await fetch('api/gastos/categorias/listar.php');
        const data = await res.json();
        if (data.success) {
            categorias = data.data;
            const sel = document.getElementById('filtroCategoria');
            const sel2 = document.getElementById('gastoCategoria');
            sel.innerHTML = '<option value="">Todas</option>';
            sel2.innerHTML = '';
            data.data.forEach(c => {
                const o1 = document.createElement('option'); o1.value = c.id; o1.textContent = c.nombre; sel.appendChild(o1);
                const o2 = document.createElement('option'); o2.value = c.id; o2.textContent = c.nombre; sel2.appendChild(o2);
            });
        }
    } catch(e) { console.error(e); }
}

async function cargarGastos() {
    const p = new URLSearchParams();
    const cat = document.getElementById('filtroCategoria').value;
    if (cat) p.append('categoria_id', cat);
    const fp = document.getElementById('filtroPago').value;
    if (fp) p.append('forma_pago', fp);
    const fd = document.getElementById('filtroDesde').value;
    if (fd) p.append('fecha_desde', fd);
    const fh = document.getElementById('filtroHasta').value;
    if (fh) p.append('fecha_hasta', fh);
    const s = document.getElementById('filtroSearch').value.trim();
    if (s) p.append('search', s);

    l(true); tc(true); es(true);
    try {
        const res = await fetch('api/gastos/operativos/listar.php?' + p.toString() + sucursalFilter());
        const data = await res.json();
        l(false);
        if (data.success) {
            const gastos = data.data.gastos;
            const hoy = new Date().toISOString().slice(0,10);
            const mes = hoy.slice(0,7);
            let totalMes = 0, totalHoy = 0;
            gastos.forEach(g => {
                if (g.fecha_gasto >= mes + '-01') totalMes += parseFloat(g.monto);
                if (g.fecha_gasto === hoy) totalHoy += parseFloat(g.monto);
            });
            document.getElementById('sumTotal').textContent = 'Q ' + data.data.total.toFixed(2);
            document.getElementById('sumMes').textContent = 'Q ' + totalMes.toFixed(2);
            document.getElementById('sumHoy').textContent = 'Q ' + totalHoy.toFixed(2);
            document.getElementById('sumCount').textContent = data.data.count;

            // Category breakdown rendering
            const bd = document.getElementById('categoriaBreakdown');
            bd.innerHTML = data.data.por_categoria.map(c =>
                '<div class="breakdown-item">' +
                    '<div class="breakdown-item-name">' + esc(c.categoria_nombre||'Sin categoría') + '</div>' +
                    '<div class="breakdown-item-value">Q ' + parseFloat(c.total).toFixed(2) + '</div>' +
                '</div>'
            ).join('') || '<div style="text-align:center; color:var(--text-muted); font-size:0.875rem; grid-column:span 5;">Sin datos</div>';

            if (gastos.length > 0) {
                const fpLabels = {efectivo:'Efectivo',transferencia:'Transferencia',cheque:'Cheque',tarjeta:'Tarjeta',otros:'Otros'};
                const fpColors = {
                    efectivo: 'badge-soft-success',
                    transferencia: 'badge-soft-primary',
                    cheque: 'badge-soft-warning',
                    tarjeta: 'badge-soft-info',
                    otros: 'badge-soft-muted'
                };
                
                document.getElementById('gastosBody').innerHTML = gastos.map(g =>
                    '<tr>' +
                        '<td style="white-space:nowrap; font-weight:500;">' + g.fecha_gasto + '</td>' +
                        '<td><span class="badge-premium badge-soft-primary">' + esc(g.categoria_nombre) + '</span></td>' +
                        '<td style="font-weight:600; color:var(--text-primary);">' + esc(g.descripcion) + '</td>' +
                        '<td style="color:var(--text-secondary);">' + esc(g.proveedor_nombre||'-') + '</td>' +
                        '<td style="text-align:right; font-weight:700; color:var(--danger);">Q ' + parseFloat(g.monto).toFixed(2) + '</td>' +
                        '<td style="text-align:center;"><span class="badge-premium ' + (fpColors[g.forma_pago]||'badge-soft-muted') + '">' + (fpLabels[g.forma_pago]||g.forma_pago) + '</span></td>' +
                        '<td>' + esc(g.referencia||'-') + '</td>' +
                        '<td style="text-align:center;">' +
                            '<button onclick="eliminarGasto(' + g.id + ')" class="btn-action-delete" title="Eliminar"><i class="bi bi-trash"></i></button>' +
                        '</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('filtroCategoria').value = '';
    document.getElementById('filtroPago').value = '';
    document.getElementById('filtroDesde').value = '';
    document.getElementById('filtroHasta').value = '';
    document.getElementById('filtroSearch').value = '';
    cargarGastos();
}

function abrirModalGasto() {
    document.getElementById('gastoDescripcion').value = '';
    document.getElementById('gastoMonto').value = '';
    document.getElementById('gastoFecha').value = new Date().toISOString().slice(0,10);
    document.getElementById('gastoProveedor').value = '';
    document.getElementById('gastoReferencia').value = '';
    document.getElementById('gastoNotas').value = '';
    document.getElementById('gastoFormaPago').value = 'efectivo';
    
    var activeSuc = getSucursalId();
    var suctSelect = document.getElementById('gastoSucursal');
    if (activeSuc > 0) {
        suctSelect.value = activeSuc;
        suctSelect.disabled = true;
    } else {
        if (suctSelect.options.length > 0) suctSelect.selectedIndex = 0;
        suctSelect.disabled = false;
    }

    if (document.getElementById('gastoCategoria').options.length > 0) {
        document.getElementById('gastoCategoria').selectedIndex = 0;
        document.getElementById('gastoCategoria').dispatchEvent(new Event('change'));
    } else {
        document.getElementById('gastoFecha').readOnly = false;
        document.getElementById('gastoFecha').style.opacity = '1';
    }
    document.getElementById('modalGasto').classList.remove('hidden');
    setTimeout(()=>document.getElementById('gastoDescripcion').focus(),100);
}

function cerrarModalGasto() { document.getElementById('modalGasto').classList.add('hidden'); }

async function guardarGasto() {
    const cat = document.getElementById('gastoCategoria').value;
    const desc = document.getElementById('gastoDescripcion').value.trim();
    const monto = parseFloat(document.getElementById('gastoMonto').value);
    const fecha = document.getElementById('gastoFecha').value;
    if (!cat) { Swal.fire({icon:'warning',title:'Seleccione una categoría',background:'#052137',color:'#ffffff'}); return; }
    if (!desc) { Swal.fire({icon:'warning',title:'Describa el gasto',background:'#052137',color:'#ffffff'}); return; }
    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('btnGuardarGasto');
    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/gastos/operativos/registrar.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({
                categoria_id: parseInt(cat), 
                descripcion: desc, 
                monto, 
                fecha_gasto: fecha,
                forma_pago: document.getElementById('gastoFormaPago').value,
                referencia: document.getElementById('gastoReferencia').value.trim()||null,
                proveedor_nombre: document.getElementById('gastoProveedor').value.trim()||null,
                sucursal_id: parseInt(document.getElementById('gastoSucursal').value),
                notas: document.getElementById('gastoNotas').value.trim()||null
            })
        });
        const data = await res.json();
        if (data.success) { 
            Swal.fire({icon:'success',title:'Gasto registrado',toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#052137',color:'#ffffff'}); 
            cerrarModalGasto(); 
            cargarGastos(); 
        } 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 Gasto'; 
    }
}

async function eliminarGasto(id) {
    const r = await Swal.fire({
        title:'¿Eliminar este gasto?',
        text:'No se podrá recuperar',
        icon:'warning',
        showCancelButton:true,
        confirmButtonText:'Sí, eliminar',
        cancelButtonText:'Cancelar',
        background:'#052137',
        color:'#ffffff',
        confirmButtonColor:'#ef4444'
    });
    if (!r.isConfirmed) return;
    try {
        const res = await fetch('api/gastos/operativos/eliminar.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({id})
        });
        const data = await res.json();
        if (data.success) { 
            Swal.fire({icon:'success',title:'Eliminado',toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#052137',color:'#ffffff'}); 
            cargarGastos(); 
        } 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'}); 
    }
}

function toggleDiaPagoInput() {
    const isFija = document.getElementById('categoriaEsFija').checked;
    const gp = document.getElementById('grupoDiaPago');
    gp.classList.toggle('hidden', !isFija);
}

function resetFormCategoria() {
    document.getElementById('editCategoriaId').value = '';
    document.getElementById('nuevaCategoriaNombre').value = '';
    document.getElementById('categoriaEsFija').checked = false;
    document.getElementById('categoriaDiaPago').value = '';
    toggleDiaPagoInput();
    document.getElementById('formCategoriaTitulo').textContent = 'Nueva Categoría';
    document.getElementById('btnGuardarCategoriaTexto').textContent = 'Agregar';
    document.getElementById('btnCancelarEditCategoria').classList.add('hidden');
}

function editarCategoria(id, nombre, tipo, diaPago) {
    document.getElementById('editCategoriaId').value = id;
    document.getElementById('nuevaCategoriaNombre').value = nombre;
    const esFija = (tipo === 'fija');
    document.getElementById('categoriaEsFija').checked = esFija;
    document.getElementById('categoriaDiaPago').value = diaPago || '';
    toggleDiaPagoInput();
    document.getElementById('formCategoriaTitulo').textContent = 'Editar Categoría';
    document.getElementById('btnGuardarCategoriaTexto').textContent = 'Guardar';
    document.getElementById('btnCancelarEditCategoria').classList.remove('hidden');
}

function abrirModalCategoria() {
    resetFormCategoria();
    cargarModalCategorias();
    document.getElementById('modalCategoria').classList.remove('hidden');
}

function cerrarModalCategoria() { document.getElementById('modalCategoria').classList.add('hidden'); }

async function cargarModalCategorias() {
    try {
        const res = await fetch('api/gastos/categorias/listar.php?activo=1');
        const data = await res.json();
        if (data.success) {
            document.getElementById('categoriasList').innerHTML = data.data.map(c => {
                const badgeClass = c.tipo === 'fija' ? 'badge-soft-warning' : 'badge-soft-info';
                const badgeText = c.tipo === 'fija' ? `Fija (Día ${c.dia_pago})` : 'Variable';
                const escNombre = esc(c.nombre).replace(/'/g, "\\'");
                
                return '<div style="display: flex; justify-content: space-between; align-items: center; background: var(--surface-elevated); border: 1px solid var(--border); border-radius: var(--radius-sm); padding: 0.65rem 1rem;">' +
                    '<div style="display: flex; flex-direction: column; gap: 0.25rem;">' +
                        '<span style="font-size: 0.875rem; color: var(--text-primary); font-weight: 500;">' + esc(c.nombre) + 
                            (c.descripcion ? ' <span style="color: var(--text-muted); font-size: 0.75rem;">(' + esc(c.descripcion) + ')</span>' : '') + 
                        '</span>' +
                        '<div>' +
                            '<span class="badge-premium ' + badgeClass + '" style="font-size: 0.7rem; padding: 0.15rem 0.4rem; border-radius: 4px;">' + badgeText + '</span>' +
                        '</div>' +
                    '</div>' +
                    '<div style="display: flex; gap: 0.35rem;">' +
                        '<button onclick="editarCategoria(' + c.id + ', \'' + escNombre + '\', \'' + c.tipo + '\', ' + (c.dia_pago || 'null') + ')" class="btn-action-edit" title="Editar" style="padding: 0.35rem; border-radius: 6px;"><i class="bi bi-pencil"></i></button>' +
                        '<button onclick="eliminarCategoria(' + c.id + ')" class="btn-action-delete" title="Eliminar" style="padding: 0.35rem; border-radius: 6px;"><i class="bi bi-trash"></i></button>' +
                    '</div>' +
                '</div>';
            }).join('');
        }
    } catch(e) { console.error(e); }
}

async function guardarCategoria() {
    const id = document.getElementById('editCategoriaId').value;
    const nombre = document.getElementById('nuevaCategoriaNombre').value.trim();
    const esFija = document.getElementById('categoriaEsFija').checked;
    const diaPagoVal = document.getElementById('categoriaDiaPago').value;
    
    if (!nombre) { Swal.fire({icon:'warning',title:'Ingrese un nombre',background:'#052137',color:'#ffffff'}); return; }
    
    const payload = {
        nombre: nombre,
        tipo: esFija ? 'fija' : 'variable'
    };
    
    if (esFija) {
        const dia = parseInt(diaPagoVal);
        if (!dia || dia < 1 || dia > 31) {
            Swal.fire({icon:'warning',title:'Día de pago inválido',text:'Debe ser un número entre 1 y 31',background:'#052137',color:'#ffffff'});
            return;
        }
        payload.dia_pago = dia;
    }
    
    let url = 'api/gastos/categorias/crear.php';
    if (id) {
        url = 'api/gastos/categorias/actualizar.php';
        payload.id = parseInt(id);
    }
    
    try {
        const res = await fetch(url, {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify(payload)
        });
        const data = await res.json();
        if (data.success) {
            resetFormCategoria();
            cargarCategorias();
            cargarModalCategorias();
            Swal.fire({icon:'success',title: id ? 'Categoría actualizada' : 'Categoría creada',toast:true,position:'top-end',showConfirmButton:false,timer:1500,background:'#052137',color:'#ffffff'});
        } 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'}); 
    }
}

async function eliminarCategoria(id) {
    const r = await Swal.fire({
        title:'¿Eliminar esta categoría?',
        text:'Solo se podrá eliminar si no tiene gastos asociados.',
        icon:'warning',
        showCancelButton:true,
        confirmButtonText:'Sí, eliminar',
        cancelButtonText:'Cancelar',
        background:'#052137',
        color:'#ffffff',
        confirmButtonColor:'#ef4444'
    });
    if (!r.isConfirmed) return;
    try {
        const res = await fetch('api/gastos/categorias/eliminar.php', {
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({id})
        });
        const data = await res.json();
        if (data.success) { 
            Swal.fire({icon:'success',title:'Categoría eliminada',toast:true,position:'top-end',showConfirmButton:false,timer:2000,background:'#052137',color:'#ffffff'}); 
            cargarCategorias();
            cargarModalCategorias();
        } 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'}); 
    }
}

function esc(t) { if(!t)return''; const d=document.createElement('div'); d.textContent=t; return d.innerHTML; }

document.getElementById('filtroCategoria').addEventListener('change', cargarGastos);
document.getElementById('filtroPago').addEventListener('change', cargarGastos);
document.getElementById('filtroDesde').addEventListener('change', cargarGastos);
document.getElementById('filtroHasta').addEventListener('change', cargarGastos);
document.getElementById('filtroSearch').addEventListener('input', cargarGastos);

document.getElementById('gastoCategoria').addEventListener('change', function() {
    const selectedId = parseInt(this.value);
    const cat = categorias.find(c => parseInt(c.id) === selectedId);
    const dateInput = document.getElementById('gastoFecha');
    if (cat && cat.tipo === 'fija') {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(cat.dia_pago).padStart(2, '0');
        dateInput.value = `${year}-${month}-${day}`;
        dateInput.readOnly = true;
        dateInput.style.opacity = '0.7';
    } else {
        dateInput.readOnly = false;
        dateInput.style.opacity = '1';
    }
});

cargarCategorias();
cargarGastos();
</script>

<?php renderFooter(); ?>
