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", function () {

    let pos_id = $(this).val();

    if (Number(pos_id) >= 1) {
        jsOnChangeBranchId(pos_id);
    }

});

// ON CHANGE BRANCH ID
async function jsOnChangeBranchId(pos_id) {

    $(".pos_description").text($("#sale_pos_id option:selected").text());
    $(".divBranchSelect").hide();
    $(".divBranchDescription").show();

    jsProductDropdownList(pos_id);
};

async function jsProductDropdownList(pos_id = "") {
    try {
        const url = `ajax/products.ajax.php?op=ajaxProductDropdownList&pos_id=${pos_id}&type=All`;
        const response = await fetch(url);

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

        const res = await response.json();

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

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

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

// Column selectors
const tbProductsReportList = $('.products-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/products.ajax.php?op=ajaxProductReportList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&fromDate=${props.fromDate}&toDate=${props.toDate}&pro_id=${props.pro_id}`;
        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}`);
    }

    // ── Helper: stock badge — FULL guard must come first ──────────────────────
    function buildStockBadge(stockRaw) {
        if (stockRaw === 'FULL') {
            return `<span class="badge bg-primary fw-medium text-white">FULL</span>`;
        }

        const stock = Number(stockRaw);
        const formatted = decimalNumberFormat(stockRaw);
        const badgeColour = stock > 20 ? 'bg-success'
            : stock > 10 ? 'bg-warning'
                : 'bg-danger';

        return `<span class="badge ${badgeColour} fw-medium text-white">${formatted}</span>`;
    }

    // ── 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(),
        pro_id: ($("#prod_id_value").val() || '').trim(), // optional filter
        fromDate,
        toDate,
    };

    // ── Validate required props (pro_id is optional) ──────────────────────────
    const missingProps = Object.entries(props)
        .filter(([key, value]) => key !== 'pro_id' && (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;
    }

    let totalSold = 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 => {

                    totalSold += Number(item.product_quantity);

                    const ticketInfo = {
                        transaction_id: item.sale_det_sale_id,
                        sale_id: item.sale_det_sale_id,
                        sale_cus_id: item.sale_det_cus_id,
                        sale_ent_id: item.sale_det_ent_id,
                        sale_pos_id: item.sale_det_pos_id,
                        section: 'products-report',
                    };

                    return [
                        item.sale_det_sale_date,
                        item.pos_name,
                        item.pro_description,
                        decimalNumberFormat(item.product_quantity),
                        buildStockBadge(item.stock_actual),
                        `<button type="button" class="btn btn-sm btn-indigo"
                                 onclick='jsShowTicket(${JSON.stringify(ticketInfo)})'>
                             <i class="ph-eye me-1"></i> Ticket
                         </button>`,
                    ];
                });

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

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

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

            tbProductsReportList.clear().draw();

        } else {

            tbProductsReportList.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) {
        tbProductsReportList.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();
        $('#totalSold').text(decimalNumberFormat(totalSold));
    }
}

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

    let pos_id = $.trim($("#pos_id_value").val());
    let pro_id = $.trim($("#prod_id_value").val());
    let daterange = $.trim($(".dateSelected").val()).split(" / ");
    let fromDate = daterange[0];
    let toDate = daterange[1];

    listDataToDatatable();

    let url = `reports/products-report/index.php?pos=${pos_id}&proId=${pro_id}&from=${fromDate}&to=${toDate}`;

    window.open(url);
});