const ent_id_value = $.trim($("#ent_id_value").val());

// Declared in header.js
selectBranchByUserPermission(ent_id_value);

// ON CHANGE BRANCH ID
$(document).on("change", "#pos_id_value", async function () {
    var ent_id = $("#ent_id_value").val();
    let pos_id = $(this).val();
    let posInfo = await getBranchData(pos_id);
    jsStorePosInfo(posInfo);
    js_SelectSaleType(pos_id);
    js_SelectPaymentType(ent_id, pos_id);
    jsCashierList();
    listDataToDatatable();
});


/*================================================
FUNCTION TO SHOW ALL SALES TYPE LIST
=================================================*/
async function js_SelectSaleType(pos_id = "") {

    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    if (Number(pos_id) <= 0) {
        $("#pay_det_sale_type").html("");
        $("#pay_det_sale_type").append(`<option value="">-- ${translate.select} --</option>`);
        return;
    }

    try {

        const url = `ajax/sale-types.ajax.php?op=ajaxSelectSaleType&pos_id=${pos_id}&section=sales-report`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const res = await response.json();
        // console.log(res);

        $("#pay_det_sale_type").html("");
        $("#pay_det_sale_type").html(`<option value="">-- ${translate.all_m} --</option>`);

        if (res.status == "success") {
            res.data.forEach(item => {
                let saleTypeName = item.sale_type_name;
                if (saleTypeName == "Local" && pos_info.pos_business_category == "Restaurant") saleTypeName = translate.local_sale_type;
                if (saleTypeName == "Delivery") saleTypeName = translate.delivery;
                if (saleTypeName == "Take Away") saleTypeName = translate.takeaway;
                if (saleTypeName == "Without Taxes") saleTypeName = translate.without_taxes;
                $("#pay_det_sale_type").append(`<option value='${item.sale_type_name}'>${saleTypeName}</option>`);
            });
        }

    } catch (error) {
        console.log(error);
    }
}


async function js_SelectPaymentType(ent_id, pos_id) {

    if (Number(pos_id) <= 0) {
        $("#pay_det_payment_type").html("");
        $("#pay_det_payment_type").append(`<option value="">-- ${translate.select} --</option>`);
        return;
    }

    try {

        const url = `ajax/payment-types.ajax.php?op=ajaxSelectPaymentType&ent_id=${ent_id}&pos_id=${pos_id}&section=sales-report`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const res = await response.json();
        // console.log(res);

        $("#pay_det_payment_type").html("");
        $("#pay_det_payment_type").html(`<option value="">-- ${translate.all_m} --</option>`);

        if (res.status == "success") {
            res.data.forEach(item => {
                let payTypeName = item.pay_type_name;
                if (payTypeName.toUpperCase() == "CASH") payTypeName = translate.cash;
                if (payTypeName.toUpperCase() == "CREDIT CARD") payTypeName = translate.credit_card;
                if (payTypeName.toUpperCase() == "DEBIT CARD") payTypeName = translate.debit_card;
                if (payTypeName.toUpperCase() == "BANK DEPOSIT") payTypeName = translate.bank_deposit;

                payTypeName = payTypeName.toLowerCase().replace(/\b\w/, char => char.toUpperCase());

                $("#pay_det_payment_type").append(`<option value='${item.pay_type_name}'>${payTypeName}</option>`);
            });
        }

    } catch (error) {
        console.log(error);
    }
}



async function jsCashierList() {

    let ent_id = $.trim($("#ent_id_value").val());

    let props = {
        ent_id: ent_id,
        profile: "!Waiter",
    }

    try {

        const url = `ajax/users.ajax.php?op=ajaxGetUsersList&ent_id=${props.ent_id}&profile=${props.profile}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const res = await response.json();

        $("#pay_det_created_by").html("");
        $("#pay_det_created_by").append(`<option value="">-- ${translate.all} --</option>`);

        if (res.status == "success") {
            res.data.forEach(item => {
                $("#pay_det_created_by").append(`<option value='${item.user_id}'>${item.user_full_name}</option>`);
            });
        }

    } catch (error) {
        console.log(error);
    }
}


// Column selectors
const tbSalesReportList = $('.sales-report-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'colvis',
                text: '<i class="ph-list"></i>',
                className: 'btn btn-light btn-icon dropdown-toggle'
            }
        ]
    },
    order: false,
});

// List All Enterprises on click btnRefresh
$(document).on("click", ".btnSearch", function () {
    let btnRefresh = "clicked";
    listDataToDatatable(btnRefresh);
});

// Get data from API
async function getDataFromAPI(props) {
    try {

        const url = `ajax/payments.ajax.php?op=ajax_paymentsReport&ent_id=${props.ent_id}&pos_id=${props.pos_id}&fromDate=${props.fromDate}&toDate=${props.toDate}&pay_det_sale_type=${props.pay_det_sale_type}&pay_det_payment_type=${props.pay_det_payment_type}&pay_det_created_by=${props.pay_det_created_by}&group_by_period=${props.group_by_period}`;
        const response = await fetch(url);

        if (!response.ok) {
            throw new Error('Failed to get data from API');
        }

        const data = await response.json();
        return data;

    } catch (error) {
        console.log(error);
        return false;
    }
}

// List All data function
async function listDataToDatatable(btnRefresh = '') {

    // ── Helper: restore search button ─────────────────────────────────────────
    function resetSearchButton() {
        $('.btnSearch')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-magnifying-glass me-1"></i> ${translate.search}`);
    }

    // ── Lock button while loading ─────────────────────────────────────────────
    $('.btnSearch')
        .prop('disabled', true)
        .css('cursor', 'not-allowed')
        .html(translate.loading_icon_text);

    // ── Collect filter parameters ─────────────────────────────────────────────
    const [fromDate, toDate] = $.trim($('.dateSelected').val()).split(' / ');

    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
        pos_id: ($("#pos_id_value").val() || '').trim(),
        pay_det_sale_type: ($("#pay_det_sale_type").val() || '').trim(),
        pay_det_payment_type: ($("#pay_det_payment_type").val() || '').trim(),
        pay_det_created_by: ($("#pay_det_created_by").val() || '').trim(),
        group_by_period: ($("#group_by_period").val() || '').trim(),
        fromDate,
        toDate,
    };

    // ── Validate required props ───────────────────────────────────────────────
    // Optional filters that may legitimately be empty
    const optionalKeys = new Set(['pay_det_sale_type', 'pay_det_payment_type', 'pay_det_created_by']);

    const missingProps = Object.entries(props)
        .filter(([key, value]) => !optionalKeys.has(key) && (value === '' || value === undefined))
        .map(([key]) => key);

    if (missingProps.length > 0) {
        resetSearchButton();
        await swalInit.fire(translate.please_fill_in_all_required_fields, missingProps.join(', '), 'warning');
        return;
    }

    const pos_info = JSON.parse(localStorage.getItem('pos_info'));
    const fmt = val => showCurrencyFormat(pos_info.pos_currency, pos_info.pos_country_code, val);

    let finalTotalIncomes = 0;
    let finalTotalDebtCollected = 0;
    let finalTotalGeneral = 0;

    try {
        const res = await getDataFromAPI(props);

        if (res.status === 'success') {

            if (btnRefresh === 'clicked') {
                fnSweetToast(translate.data_loaded_successfully, 'success', 2000);
            }

            if (res.data.length > 0) {

                const formattedData = res.data.map(item => {

                    finalTotalIncomes += Number(item.pay_det_income);
                    finalTotalDebtCollected += Number(item.pay_det_debt_collect);
                    finalTotalGeneral += Number(item.total_pay_det_income);

                    return [
                        item.pay_det_period,
                        item.pos_name,
                        item.pay_det_payment_type,
                        fmt(item.pay_det_income),
                        fmt(item.pay_det_debt_collect),
                        fmt(item.total_pay_det_income),
                    ];
                });

                tbSalesReportList.clear().rows.add(formattedData).draw();

            } else {
                tbSalesReportList.clear().draw();
            }

        } else if (res.status === 'warning') {

            tbSalesReportList.clear().draw();

        } else {

            tbSalesReportList.clear().draw();
            console.error('listDataToDatatable unexpected response:', res);
            await swalInit.fire(
                translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
                '',
                'error'
            );
        }

    } catch (error) {
        tbSalesReportList.clear().draw();
        console.error('listDataToDatatable error:', error);
        await swalInit.fire(
            translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance,
            '',
            'error'
        );

    } finally {
        resetSearchButton();
        $('#finalTotalIncomes').text(fmt(finalTotalIncomes));
        $('#finalTotalDebtCollected').text(fmt(finalTotalDebtCollected));
        $('#finalTotalGeneral').text(fmt(finalTotalGeneral));
    }
}


$(document).on("click", ".btnPrintSalesReport", function () {

    let ent_id = $.trim($("#ent_id_value").val());
    let pos_id = $.trim($("#pos_id_value").val());
    let pay_det_sale_type = $.trim($("#pay_det_sale_type").val());
    let pay_det_payment_type = $.trim($("#pay_det_payment_type").val());
    let pay_det_created_by = $.trim($("#pay_det_created_by").val());
    let group_by_period = $.trim($("#group_by_period").val());
    let daterange = $.trim($(".dateSelected").val()).split(" / ");
    let fromDate = daterange[0];
    let toDate = daterange[1];

    listDataToDatatable();

    let url = `reports/sales-report/index.php?ent=${ent_id}&pos=${pos_id}&from=${fromDate}&to=${toDate}&saleType=${pay_det_sale_type}&payType=${pay_det_payment_type}&cashier=${pay_det_created_by}&groupBy=${group_by_period}`;

    window.open(url);
});