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

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

// Column selectors
const tbStocksAdjustment = $('.stocks-adjustment-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: [[0, "desc"]],
});

$(document).on("change", "#pos_id_value", function () {
    jsProductDropdownList($(this).val());
    listDataToDatatable();
});


async function jsProductDropdownList(pos_id = "") {
    try {
        const url = `ajax/products.ajax.php?op=ajaxProductDropdownList&pos_id=${pos_id}&type=product`;
        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);
    }
}

// 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/stock-adjustment.ajax.php?op=ajaxStockAdjustmentList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&pro_id=${props.pro_id}&fromDate=${props.fromDate}&toDate=${props.toDate}`;
        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(),
        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;
    }

    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 => [
                    item.adjust_id,
                    item.pos_name,
                    item.adjust_datetime,
                    item.user_fullname ? formatName(item.user_fullname) : '--',
                    item.product_name,
                    item.adjust_type === 'Increase' ? translate.increase : translate.decrease,
                    decimalNumberFormat(Number(item.adjust_quantity)),
                    decimalNumberFormat(Number(item.adjust_final_stock)),
                    `<button type="button" class="btn btn-sm btn-indigo"
                             onclick='jsViewAdjustmentDetail(${JSON.stringify(item)})'>
                         <i class="ph-eye me-1"></i> ${translate.view}
                     </button>`,
                ]);

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

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

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

            tbStocksAdjustment.clear().draw();

        } else {

            tbStocksAdjustment.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) {
        tbStocksAdjustment.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();
    }
}

function jsViewAdjustmentDetail(data) {
    // Modal form
    let adjust_type = data.adjust_type == 'Increase' ? translate.increase : translate.decrease;

    $("#stock_adjustment_id").text(data.adjust_id);
    $("#stock_adjustment_branch").text(data.pos_name);
    $("#stock_adjustment_date").text(data.adjust_datetime);
    $("#stock_adjustment_user").text(data.user_fullname);
    $("#stock_adjustment_product").text(data.product_name);
    $("#stock_adjustment_type").text(adjust_type);
    $("#stock_adjustment_initial").text(decimalNumberFormat(Number(data.adjust_current_stock)));
    $("#stock_adjustment_qty").text(decimalNumberFormat(Number(data.adjust_quantity)));
    $("#stock_adjustment_final").text(decimalNumberFormat(Number(data.adjust_final_stock)));
    $("#stock_adjustment_reason").text(data.adjust_reason);

    $("#stock-adjustment-view-modal").modal("show");
}