<?php
session_start();
include '../includes/session_control.php';

require_once __DIR__ . '/../cotizaciones/api/_node.php';

$message = '';
$years = [];
$currentYear = intval(date('Y'));

$token = $_SESSION['node_token'] ?? '';
$hasToken = is_string($token) && trim($token) !== '';
$nodeBase = cpn_node_api_base();

if ($hasToken) {
    $resp = cpn_node_request('GET', $nodeBase . '/api/informes/gastos/years', $token);
    if (($resp['ok'] ?? false) && is_array($resp['data'] ?? null)) {
        $years = $resp['data'];
    } else {
        $message = (string)($resp['error']['message'] ?? 'No se pudo cargar la lista de años.');
    }
} else {
    $message = 'Token de sesión no disponible. Vuelva a iniciar sesión.';
}

if (!$years) {
    $years = [$currentYear];
}
?>
<?php include '../templates/header.php'; ?>

<div class="container-fluid">

    <?php if ($message !== ''): ?>
        <div class="alert alert-info"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <!-- ───── Filtro de año ──────────────────────────────────────────── -->
    <div class="row mb-3 align-items-end">
        <div class="col-md-3 col-sm-6">
            <label for="yearSelect" class="mb-1">Año</label>
            <select id="yearSelect" class="form-control" aria-label="Año">
                <?php foreach ($years as $yy):
                    $yyInt = intval($yy);
                    $sel = ($yyInt === $currentYear) ? 'selected' : '';
                ?>
                    <option value="<?= $yyInt ?>" <?= $sel ?>><?= $yyInt ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

    <!-- ───── Tabla de Gastos ────────────────────────────────────────── -->
    <div class="table-responsive mb-4">
        <table id="gastosTable"
            class="table table-bordered table-sm text-right"
            style="width:100%;">
            <thead>
                <tr>
                    <th class="text-left">Concepto</th>
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                        <th><?= date('M', mktime(0, 0, 0, $m, 1)) ?></th>
                    <?php endfor; ?>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody id="gastosBody"></tbody>
            <tfoot>
                <tr id="missingRow" class="bg-light font-weight-bold">
                    <td class="text-left">Sin mes / concepto</td>
                    <?php for ($m = 1; $m <= 12; $m++): ?><td>&minus;</td><?php endfor; ?>
                    <td>&minus;</td>
                </tr>
            </tfoot>
        </table>
    </div>

    <!-- ───── Pie de participación ───────────────────────────────────── -->
    <div id="gastosPieChart" style="height:350px;"></div>
</div>

<style>
    /* Select2 dark (según estándar del proyecto) */
    .select2-container--default .select2-selection--single {
        background: #1f2937;
        border: 1px solid #374151;
        height: calc(1.5em + .75rem + 2px);
        padding: .375rem .75rem;
        color: #fff;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        color: #fff;
        line-height: 1.5;
        padding-left: 0;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: calc(1.5em + .75rem + 2px);
        right: .35rem;
    }

    .select2-dropdown {
        background: #111827;
        border: 1px solid #374151;
        z-index: 20000;
    }

    .select2-container--default .select2-results__option {
        color: #fff;
    }

    .select2-container--default .select2-results__option--highlighted[aria-selected] {
        background: #2563eb;
        color: #fff;
    }

    .select2-container--default .select2-search--dropdown .select2-search__field {
        background: #0b1220;
        color: #fff;
        border: 1px solid #374151;
    }

    /* Tabla: mantener columnas alineadas y evitar “descuadres” */
    #gastosTable {
        table-layout: fixed;
        font-size: .82rem;
    }

    #gastosTable th,
    #gastosTable td {
        vertical-align: middle;
        white-space: nowrap;
    }

    #gastosTable th:first-child,
    #gastosTable td:first-child {
        width: 280px;
        white-space: normal;
        font-size: .88rem;
    }

    #gastosTable th:not(:first-child),
    #gastosTable td:not(:first-child) {
        width: 95px;
    }

    tr.terceros-hidden {
        display: none;
    }

    .pago-total {
        color: #28a745 !important;
    }

    .pago-parcial {
        color: #fd7e14 !important;
    }

    .pago-nulo {
        color: #dc3545 !important;
    }
</style>

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
    let chartsReady = false;

    google.charts.load('current', {
        packages: ['corechart']
    });
    google.charts.setOnLoadCallback(() => {
        chartsReady = true;
        drawAll();
    });

    $(function() {
        const $year = $('#yearSelect');
        $year.select2({
            width: '100%',
            dropdownAutoWidth: true,
            minimumResultsForSearch: 8
        });
        $year.on('change', drawAll);
        // Carga inicial aunque charts no haya terminado.
        drawAll();
    });

    function money(v) {
        return v ? '$ ' + Math.round(v).toLocaleString('es-CO') : '&minus;';
    }

    function drawAll() {
        $.getJSON('informe_gastos_data.php', {
            year: $('#yearSelect').val()
        }, data => {
            if (data && data.error) {
                alert(data.error);
                return;
            }
            const $body = $('#gastosBody').empty();
            data.concepts.forEach(p => {
                addRow(p, 0);
                p.children.forEach(c => {
                    addRow(c, 1);
                    if (c.terceros) c.terceros.forEach(t => addRow(t, 2));
                });
            });
            fillRow($('#missingRow'), data.missing.monthly, data.missing.total, []);

            // Pie chart: solo si Google Charts ya está listo.
            if (chartsReady && google && google.visualization) {
                const dt = new google.visualization.DataTable();
                dt.addColumn('string', 'Concepto');
                dt.addColumn('number', 'Valor');
                (data.pie || []).forEach(r => dt.addRow([r.name, r.value]));
                new google.visualization.PieChart(
                    document.getElementById('gastosPieChart')
                ).draw(dt, {
                    title: 'Participación ' + $('#yearSelect').val(),
                    is3D: true,
                    legend: {
                        position: 'right'
                    },
                    pieSliceText: 'percentage'
                });
            }
        });
    }

    function addRow(o, lvl) {
        const hasTerceros = lvl === 1 && Array.isArray(o.terceros) && o.terceros.length;
        const $tr = $('<tr>').attr('data-lvl', lvl);
        if (lvl === 2) $tr.addClass('terceros-hidden');
        if (lvl === 0) $tr.addClass('font-weight-bold');

        // construye la etiqueta: link sólo en lvl=2
        let label = o.name;
        if (lvl === 2) {
            label = `<a href="/gastos/movimiento_tercero.php?id=${o.id}">${o.name}</a>`;
        }
        const icon = hasTerceros ? '<span class="toggle">[+]</span> ' : '';
        $tr.append(
            $('<td class="text-left">').html('&nbsp;'.repeat(lvl * 4) + icon + label)
        );

        fillRow($tr, o.monthly, o.total, o.status);
        $('#gastosBody').append($tr);

        if (hasTerceros) {
            $tr.find('.toggle')
                .css('cursor', 'pointer')
                .on('click', function() {
                    $(this).closest('tr')
                        .nextUntil('tr[data-lvl!="2"]')
                        .toggle();
                    $(this).text($(this).text() === '[+]' ? '[-]' : '[+]');
                });
        }
    }



    function fillRow($tr, monthly, total, status) {
        // Si la fila ya trae celdas (caso tfoot #missingRow), evita duplicarlas.
        const $cells = $tr.children('td');
        if ($cells.length > 1) {
            $cells.slice(1).remove();
        }

        // Asegura 12 columnas (ene-dic) para evitar descuadres.
        for (let i = 0; i < 12; i++) {
            const v = (Array.isArray(monthly) && i < monthly.length) ? monthly[i] : 0;
            const cls = (Array.isArray(status) && i < status.length) ? status[i] : '';
            $tr.append($('<td>').addClass(cls).html(money(v)));
        }
        $tr.append($('<td class="font-weight-bold">').html(money(total)));
    }
</script>

<?php include '../templates/footer.php'; ?>