<?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/ventas/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; ?>

    <div class="row mb-4">
        <div class="col-md-2">
            <label for="yearSelect">Año:</label>
            <select id="yearSelect" class="form-control">
                <?php foreach ($years as $yy):
                    $yyInt = intval($yy);
                    $sel = ($yyInt === $currentYear) ? 'selected' : '';
                ?>
                    <option value="<?= $yyInt ?>" <?= $sel ?>><?= $yyInt ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>

    <!-- Gráfico de columnas + línea -->
    <div id="monthlyChart" style="width:100%; height:500px; max-width:100%;"></div>

    <h2 class="mt-4">Detalle Mensual</h2>
    <div class="table-responsive mb-5">
        <table id="monthlyTable"
            class="table table-bordered table-sm text-right"
            style="table-layout:fixed;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>
                <?php foreach (['Subtotal', 'Impuesto', 'Envio', 'Total'] as $c):
                    $k = strtolower($c);
                ?>
                    <tr data-concept="<?= $k ?>">
                        <td class="text-left"><?= $c ?></td>
                        <?php for ($m = 1; $m <= 12; $m++): ?>
                            <td class="month-<?= $m ?>">&minus;</td>
                        <?php endfor; ?>
                        <td class="font-weight-bold total">&minus;</td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>


    <!-- Resumen por Tipo -->
    <h2 class="mt-5">Resumen de Ventas por Tipo</h2>
    <div id="typePieChart" style="height:300px;"></div>
    <table id="tipoTable"
        class="table table-bordered table-sm text-right"
        style="table-layout:fixed;width:100%;">
        <thead>
            <tr>
                <th class="text-left">Tipo</th>
                <?php for ($m = 1; $m <= 12; $m++): ?>
                    <th><?= strftime('%b', mktime(0, 0, 0, $m, 1)) ?></th>
                <?php endfor; ?>
                <th>Total</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <!-- Resumen por Medio -->
    <h2 class="mt-5">Resumen de Ventas por Medio</h2>
    <div id="medioPieChart" style="height:300px;"></div>
    <table id="medioTable"
        class="table table-bordered table-sm text-right"
        style="table-layout:fixed;width:100%;">
        <thead>
            <tr>
                <th class="text-left">Medio</th>
                <?php for ($m = 1; $m <= 12; $m++): ?>
                    <th><?= strftime('%b', mktime(0, 0, 0, $m, 1)) ?></th>
                <?php endfor; ?>
                <th>Total</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<style>
    #monthlyChart,
    #typePieChart,
    #medioPieChart {
        width: 100% !important;
        max-width: 100%;
    }

    /* Tablas: más compactas */
    #monthlyTable,
    #tipoTable,
    #medioTable {
        font-size: .82rem;
    }

    #monthlyTable th,
    #monthlyTable td,
    #tipoTable th,
    #tipoTable td,
    #medioTable th,
    #medioTable td {
        padding: .3rem .45rem;
        white-space: nowrap;
    }
</style>

<!-- Google Charts y tu JS deben ir **después** de jQuery -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
    let chartsReady = false;

    google.charts.load('current', {
        packages: ['corechart', 'bar']
    });
    google.charts.setOnLoadCallback(function() {
        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 drawAll() {
        const year = $('#yearSelect').val();
        $.getJSON('informe_ventas_data.php', {
            year
        }, function(data) {
            // 1) Columnas + Meta (solo si Charts está listo)
            if (chartsReady && google && google.visualization) {
                const dt = new google.visualization.DataTable();
                dt.addColumn('string', 'Mes');
                dt.addColumn('number', 'Subtotal');
                dt.addColumn('number', 'Meta');
                data.months.forEach((m, i) => dt.addRow([m, data.monthlySubtotal[i], data.threshold]));
                const comboOpt = {
                    title: 'Ventas Mensuales',
                    hAxis: {
                        title: 'Mes'
                    },
                    vAxis: {
                        format: '#,###'
                    },
                    seriesType: 'bars',
                    series: {
                        1: {
                            type: 'line',
                            color: 'red',
                            lineWidth: 2
                        }
                    },
                    legend: {
                        position: 'none'
                    },
                    bar: {
                        groupWidth: '70%'
                    }
                };
                new google.visualization.ComboChart(
                    document.getElementById('monthlyChart')
                ).draw(dt, comboOpt);
            }

            // --- Llenar Detalle Mensual ---
            ['subtotal', 'impuesto', 'envio', 'total'].forEach(function(concept) {
                // obtiene el array desde el JSON
                const arr = data['monthly' + concept.charAt(0).toUpperCase() + concept.slice(1)];
                let sum = 0;
                arr.forEach(function(val, i) {
                    const v0 = Math.round(Number(val || 0));
                    sum += v0;
                    $('#monthlyTable tr[data-concept=' + concept + '] td.month-' + (i + 1))
                        .text('$ ' + v0.toLocaleString('es-CO'));
                });
                $('#monthlyTable tr[data-concept=' + concept + '] td.total')
                    .text('$ ' + sum.toLocaleString('es-CO'));
            });

            // 2) Pie Tipo (solo si Charts está listo)
            if (chartsReady && google && google.visualization) {
                const dt1 = new google.visualization.DataTable();
                dt1.addColumn('string', 'Tipo');
                dt1.addColumn('number', 'Subtotal');
                data.pieTipo.forEach(r => dt1.addRow([r.name, r.value]));
                new google.visualization.PieChart(
                    document.getElementById('typePieChart')
                ).draw(dt1, {
                    title: 'Ventas por Tipo',
                    is3D: true,
                    pieSliceText: 'percentage',
                    legend: {
                        position: 'right'
                    }
                });
            }

            // 3) Tabla Tipo
            const $tb1 = $('#tipoTable tbody').empty();
            Object.entries(data.tipoMonthly).forEach(([name, arr]) => {
                const sum = arr.reduce((a, b) => a + Math.round(Number(b || 0)), 0);
                const $tr = $('<tr>');
                $tr.append($('<td class="text-left">').text(name));
                arr.forEach(v => {
                    const v0 = Math.round(Number(v || 0));
                    $tr.append($('<td>').text('$ ' + v0.toLocaleString('es-CO')));
                });
                $tr.append($('<td class="font-weight-bold">').text('$ ' + sum.toLocaleString('es-CO')));
                $tb1.append($tr);
            });

            // 4) Pie Medio (solo si Charts está listo)
            if (chartsReady && google && google.visualization) {
                const dt2 = new google.visualization.DataTable();
                dt2.addColumn('string', 'Medio');
                dt2.addColumn('number', 'Subtotal');
                data.pieMedio.forEach(r => dt2.addRow([r.name, r.value]));
                new google.visualization.PieChart(
                    document.getElementById('medioPieChart')
                ).draw(dt2, {
                    title: 'Ventas por Medio',
                    is3D: true,
                    pieSliceText: 'percentage',
                    legend: {
                        position: 'right'
                    }
                });
            }

            // 5) Tabla Medio
            const $tb2 = $('#medioTable tbody').empty();
            Object.entries(data.medioMonthly).forEach(([name, arr]) => {
                const sum = arr.reduce((a, b) => a + Math.round(Number(b || 0)), 0);
                const $tr = $('<tr>');
                $tr.append($('<td class="text-left">').text(name));
                arr.forEach(v => {
                    const v0 = Math.round(Number(v || 0));
                    $tr.append($('<td>').text('$ ' + v0.toLocaleString('es-CO')));
                });
                $tr.append($('<td class="font-weight-bold">').text('$ ' + sum.toLocaleString('es-CO')));
                $tb2.append($tr);
            });
        });
    }
</script>

<?php include '../templates/footer.php'; ?>