<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$base = cpn_node_api_base();

if (!isset($_SESSION['node_token']) || !is_string($_SESSION['node_token']) || trim($_SESSION['node_token']) === '') {
    header('Location: /login.php');
    exit;
}

// Control de acceso (roles 1,2,4 o super)
$roleId = isset($_SESSION['user']['roleId']) ? (int)$_SESSION['user']['roleId'] : 0;
$isSuper = isset($_SESSION['user']['isSuper']) && (int)$_SESSION['user']['isSuper'] === 1;
if (!$isSuper && !in_array($roleId, [1, 2, 4], true)) {
    http_response_code(403);
    die('No autorizado');
}
?>

<?php include '../templates/header.php'; ?>

<style>
    /* Select2 dark (fondo oscuro, texto blanco) */
    .select2-container--default .select2-selection--single {
        background-color: #343a40;
        border-color: #4e73df;
        color: #fff;
        height: calc(1.5em + .75rem + 2px);
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: #fff;
        line-height: calc(1.5em + .75rem);
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: calc(1.5em + .75rem);
    }

    .select2-dropdown {
        background: #343a40;
        border-color: #4e73df;
        color: #fff;
    }

    .select2-container--default .select2-search--dropdown .select2-search__field {
        background: #212529;
        border-color: #4e73df;
        color: #fff;
    }

    .select2-container--default .select2-results__option {
        color: #fff;
    }

    .select2-container--default .select2-results__option--highlighted[aria-selected] {
        background-color: #4e73df;
        color: #fff;
    }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Contabilidad - Cuentas Contables</h1>
    <p class="text-muted">Vista de solo lectura para análisis contable. Seleccione una cuenta para ver los gastos asociados.</p>

    <div class="card mb-3">
        <div class="card-body">
            <div class="form-group">
                <label for="cuentaSearch">Buscar Cuenta Contable</label>
                <select id="cuentaSearch" class="form-control" style="width: 100%"></select>
            </div>
        </div>
    </div>

    <div id="detallesCuenta" style="display: none;">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0" id="cuentaNombre"></h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm table-bordered table-hover" id="gastosTable">
                        <thead class="thead-light">
                            <tr>
                                <th>ID Gasto</th>
                                <th>Fecha</th>
                                <th>Factura</th>
                                <th>Beneficiario</th>
                                <th>Concepto</th>
                                <th class="text-right">Valor</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                        <tfoot class="font-weight-bold">
                            <tr>
                                <td colspan="5" class="text-right">TOTAL:</td>
                                <td class="text-right" id="totalGastos"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/footer.php'; ?>

<script>
    jQuery(function($) {
        const $sel = $('#cuentaSearch');
        const $detalles = $('#detallesCuenta');
        const $cuentaNombre = $('#cuentaNombre');
        const $gastosBody = $('#gastosTable tbody');
        const $totalGastos = $('#totalGastos');

        function fmt(val) {
            if (!val || val == 0) return '-';
            return '$ ' + Number(Math.abs(val)).toLocaleString('es-CO', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
            });
        }

        $sel.select2({
            placeholder: 'Buscar cuenta…',
            width: '100%',
            ajax: {
                url: '<?php echo htmlspecialchars($base); ?>/api/gastos/cuentas/search',
                dataType: 'json',
                delay: 250,
                headers: {
                    'Authorization': 'Bearer <?php echo htmlspecialchars($_SESSION['node_token'] ?? ''); ?>'
                },
                data: function(params) {
                    return {
                        q: params.term || ''
                    };
                },
                processResults: function(resp) {
                    const results = (resp && resp.ok && resp.data && Array.isArray(resp.data.results)) ? resp.data.results : [];
                    return {
                        results
                    };
                }
            }
        });

        $sel.on('select2:select', function(e) {
            const idCuenta = e.params.data.id;
            const cuentaText = e.params.data.text;

            $cuentaNombre.text(cuentaText);
            $detalles.show();
            $gastosBody.html('<tr><td colspan="6" class="text-center"><i class="fas fa-spinner fa-spin"></i> Cargando gastos...</td></tr>');

            // Cargar gastos que usan esta cuenta (endpoint a crear en Node)
            $.ajax({
                url: '<?php echo htmlspecialchars($base); ?>/api/gastos/items/by-cuenta?idCuenta=' + idCuenta,
                method: 'GET',
                dataType: 'json',
                headers: {
                    'Authorization': 'Bearer <?php echo htmlspecialchars($_SESSION['node_token'] ?? ''); ?>'
                }
            }).done(function(resp) {
                if (!resp.ok || !resp.data || !Array.isArray(resp.data.items)) {
                    $gastosBody.html('<tr><td colspan="6" class="text-center text-muted">No se encontraron gastos para esta cuenta</td></tr>');
                    $totalGastos.text('-');
                    return;
                }

                const items = resp.data.items;
                if (items.length === 0) {
                    $gastosBody.html('<tr><td colspan="6" class="text-center text-muted">No hay gastos asociados a esta cuenta</td></tr>');
                    $totalGastos.text('-');
                    return;
                }

                $gastosBody.empty();
                let total = 0;
                items.forEach(function(item) {
                    const valor = Number(item.valor || 0);
                    total += valor;
                    $gastosBody.append(`
                        <tr>
                            <td><strong>#${item.idGasto}</strong></td>
                            <td>${item.fecha || ''}</td>
                            <td>${item.factura || ''}</td>
                            <td>${item.beneficiario || ''}</td>
                            <td>${item.concepto || ''}</td>
                            <td class="text-right">${fmt(valor)}</td>
                        </tr>
                    `);
                });
                $totalGastos.text(fmt(total));
            }).fail(function() {
                $gastosBody.html('<tr><td colspan="6" class="text-center text-danger">Error al cargar gastos</td></tr>');
                $totalGastos.text('-');
            });
        });
    });
</script>