// ── Init: read ent_id fresh and set up branch selector ────────────────────────
selectBranchByUserPermission(($("#ent_id_value").val() || '').trim());

// ── Event: branch change ──────────────────────────────────────────────────────
$(document).on('change', '#pos_id_value', async function () {
    const posInfo = await getBranchData($(this).val());
    jsStorePosInfo(posInfo);
    jsShowStatisticsData();
});

// ── Event: refresh button ─────────────────────────────────────────────────────
$(document).on('click', '.btnSearch', () => jsShowStatisticsData());

// ── Helper: build a Highcharts column chart ───────────────────────────────────
function buildColumnChart(containerId, categories, series, colors) {
    Highcharts.chart(containerId, {
        colors,
        chart: { type: 'column' },
        title: { text: '' },
        xAxis: { categories },
        tooltip: {
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
            shared: true,
        },
        series,
    });
}

// ── Main statistics loader ────────────────────────────────────────────────────
async function jsShowStatisticsData() {

    const ent_id = ($("#ent_id_value").val() || '').trim();
    const pos_id = ($("#pos_id_value").val() || '').trim();
    const date = ($(".dashboardDate").val() || '').trim();

    // Lock UI while loading
    $('.btnSearch').html(translate.loading_icon_text);
    $('.loadingSpinner').html(translate.loading_icon);

    // Guard: pos_info must exist before we can format currency
    const pos_info = JSON.parse(localStorage.getItem('pos_info'));
    if (!pos_info) {
        console.error('jsShowStatisticsData: pos_info not found in localStorage');
        $('.btnSearch').html(`<i class="ph-arrows-clockwise me-1"></i> ${translate.refresh}`);
        $('.loadingSpinner').html('');
        return;
    }

    const fmt = val => showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, val);

    // ── Collect params ────────────────────────────────────────────────────────
    const props = { ent_id, pos_id, date };

    // ── Validate required props ───────────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([, value]) => value === '' || value === undefined)
        .map(([key]) => key);

    if (missingProps.length > 0) {
        $('.btnSearch').html(`<i class="ph-arrows-clockwise me-1"></i> ${translate.refresh}`);
        $('.loadingSpinner').html('');
        await swalInit.fire(translate.please_fill_in_all_required_fields, missingProps.join(', '), 'warning');
        return;
    }

    try {
        const params = new URLSearchParams({ op: 'ajaxShowStatisticsData', ...props });

        const response = await fetch(`ajax/dashboard.ajax.php?${params.toString()}`);

        if (!response.ok) {
            throw new Error(`HTTP error — status: ${response.status}`);
        }

        const res = await response.json();

        // ── Stat tiles ────────────────────────────────────────────────────────
        $('.spanTodaySale').text(fmt(res.today_sales));
        $('.spanDebtsCollectedToday').text(fmt(res.debts_collected_today));
        $('.spanWeekSale').text(fmt(res.sales_of_the_week));
        $('.spanMonthSale').text(fmt(res.sales_of_the_month));

        $('.spanPendingAccounts').text(fmt(res.pending_accounts));
        $('.spanMonthlyDailyExpenses').text(fmt(res.monthly_daily_expenses));
        $('.spanMonthlyFixedExpenses').text(fmt(res.monthly_fixed_expenses));
        $('.spanPurchasesOfTheMonth').text(fmt(res.purchases_of_the_month));

        $('.spanGeneralPurchases').text(fmt(res.general_purchases));
        $('.spanGeneralExpenses').text(fmt(res.general_expenses));
        $('.spanGeneralDebts').text(fmt(res.general_pending_payments));
        $('.spanGeneralSale').text(fmt(res.general_sale));

        // ── Charts ────────────────────────────────────────────────────────────
        buildColumnChart(
            'MontlhySaleIncomeChart',
            res.arraySalesMontlhyDate,
            [
                { name: translate.incomes, data: res.arraySalesMonthlyIncomes.map(Number) },
                { name: translate.cashback, data: res.arraySalesMonthlyCashBackIncomes.map(Number) },
            ],
            ['#2E8B57', '#8E70C1', '#3B4863']
        );

        buildColumnChart(
            'monthly_expense_charts',
            res.arrayMonthlyExpenseDate,
            [
                { name: translate.monthly_expense, data: res.arrayTotalMonthlyExpenses.map(Number) },
            ],
            ['#E07A5F', '#3B4863', '#673ab7']
        );

        buildColumnChart(
            'purchases_charts',
            res.arrayPurchaseDate,
            [
                { name: translate.total_purchases, data: res.arrayTotalPurchases.map(Number) },
            ],
            ['#4f7dff', '#3B4863', '#4682B4']
        );

    } catch (error) {
        console.error('jsShowStatisticsData error:', error);

    } finally {
        $('.btnSearch').html(`<i class="ph-arrows-clockwise me-1"></i> ${translate.refresh}`);
        $('.loadingSpinner').html('');
    }
}