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

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

// Column selectors
const tbCustomersList = $('.customers-table').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            }
        ]
    },
    order: [[0, "desc"]],
});

// Column selectors
const tbCustomersDebtsOrdersList = $('.tbCustomersDebtsOrdersList').DataTable({
    buttons: {
        buttons: [
            {
                extend: 'excelHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            },
            {
                extend: 'pdfHtml5',
                className: 'btn btn-light',
                exportOptions: {
                    columns: ':visible'
                }
            }
        ]
    },
    order: [[0, "desc"]],
});

// Add New Customer
$(document).on("click", ".btnAddCustomer", function () {

    $(".span-modal-title").text(translate.add_customer);

    $(".btnSaveCustomer").show();
    $(".btnEditCustomer").hide();

    document.getElementById("frmAddEditCustomer").reset();

    $("#cus_id").val("");
    $("#cus_ent_id").val($("#ent_id_value").val());
    $("#cus_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());

    $('#customer-modal').modal('show');
});

// List All Customers 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/customers.ajax.php?op=ajaxCustomersList&ent_id=${props.ent_id}&status=${props.status}`;
        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: apply column visibility based on selected status ─────────────
    function applyColumnVisibility() {
        const isWithoutDebt = status === 'without_debt';

        tbCustomersList.column(3).visible(!isWithoutDebt);  // debt badge
        tbCustomersList.column(4).visible(!isWithoutDebt);  // pending orders btn
        tbCustomersList.column(7).visible(                  // debt reset btn
            !isWithoutDebt && sess_user_profile === 'ROOT'
        );
    }

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

    // ── Collect filter parameters ─────────────────────────────────────────────
    const props = {
        ent_id: ($("#ent_id_value").val() || '').trim(),
        status: ($(".searchStatus").val() || '').trim(),
    };

    const { status } = props;

    // ── Validate required props ───────────────────────────────────────────────
    const missingProps = Object.entries(props)
        .filter(([, value]) => 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') {

            // Apply column visibility now that we know the response succeeded
            applyColumnVisibility();

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

            if (res.data.length > 0) {

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

                    const saleResetInfo = {
                        transaction_id: item.cus_id,
                        transaction_type: 'customer_debt_reset',
                    };

                    return [
                        item.cus_id,
                        item.cus_full_name,
                        item.cus_phone,
                        `<span class="badge bg-danger fw-medium text-white">
                             ${showCurrencyFormat('USD', 'en-US', item.cus_debt)}
                         </span>`,
                        `<button type="button" class="btn btn-sm btn-danger"
                                 onclick='jsShowCustomerPendingOrders(${item.cus_id})'>
                             <i class="ph-handbag me-1"></i> ${translate.show}
                         </button>`,
                        `<span class="badge bg-success fw-medium text-white">
                             ${showCurrencyFormat('USD', 'en-US', item.cus_available_cashback)}
                         </span>`,
                        `<button type="button" class="btn btn-sm btn-indigo"
                                 onclick='jsEditData(${JSON.stringify(item)})'>
                             <i class="ph-pencil-simple-line me-1"></i> ${translate.edit}
                         </button>`,
                        `<button type="button" class="btn btn-sm btn-danger"
                                 onclick='jsSaleDebtReset(${JSON.stringify(saleResetInfo)})'>
                             <i class="ph-warning me-1"></i> ${translate.reset}
                         </button>`,
                    ];
                });

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

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

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

            tbCustomersList.clear().draw();

        } else {

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

/*=============================================
SHOW CUSTOMER INFORMATIONS
=============================================*/
function jsEditData(data) {

    $(".span-modal-title").text(translate.edit_customer);

    $(".btnSaveCustomer").hide();
    $(".btnEditCustomer").show();

    document.getElementById("frmAddEditCustomer").reset();
    // Modal form
    $(".pos_description").text(data.pos_name);

    $("#cus_id").val(data.cus_id);
    $("#cus_ent_id").val(data.cus_ent_id);
    $("#cus_pos_id").val(data.cus_pos_id);
    $("#cus_full_name").val(data.cus_full_name);
    // $("#cus_phone").val(data.cus_phone);

    let fullPhone = data.cus_phone.replace(/[\s\-\_\(\)\.]/g, "");
    intlPhoneFormatShared.setNumber(fullPhone);

    $("#cus_email").val(data.cus_email);
    $("#cus_address").val(data.cus_address);
    $("#cus_fiscal_number").val(data.cus_fiscal_number);

    $("#customer-modal").modal("show");
}

async function jsShowCustomerPendingOrders(cus_id) {
    try {

        const url = `ajax/customers.ajax.php?op=ajaxShowCustomerPendingOrders&cus_id=${cus_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

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

            if (res.data.length > 0) {
                const formattedData = res.data.map(item => {

                    let saleResetInfo = {
                        transaction_id: item.sale_id,
                        transaction_type: "sale_debt_reset",
                    }

                    let btnDebtReset = ``;
                    if (sess_user_profile == "ROOT") {
                        btnDebtReset = `<button type="button" class="dropdown-item text-danger danger-on-hover" onclick='jsSaleDebtReset(${JSON.stringify(saleResetInfo)})'><i class="ph-warning me-1"></i> ${translate.reset}</button>`;
                    }

                    let ticketInfo = {
                        sale_id: item.sale_id,
                        sale_cus_id: item.sale_cus_id,
                        sale_ent_id: item.sale_ent_id,
                        sale_pos_id: item.sale_pos_id,
                    }

                    let btnOptions = `<button type="button" class="btn btn-indigo dropdown-toggle" data-bs-toggle="dropdown">${translate.action}</button>
                    <div class="dropdown-menu dropdown-menu-theme">
                    <button type="button" class="dropdown-item light-warning-on-hover" onclick='jsShowTicket(${JSON.stringify(ticketInfo)})'><i class="ph-note me-1"></i> Ticket</button>
                    <a target="_blank" href="sell-det-${item.sale_id}" role="button" class="dropdown-item light-warning-on-hover" href="javascript:void(0)"> <i class="ph-currency-circle-dollar me-1"></i> ${translate.charge}</a>
                    ${btnDebtReset}
                    </div>`;

                    return [
                        item.sale_id,
                        item.pos_name,
                        item.sale_date,
                        item.waiter_full_name ? formatName(item.waiter_full_name) : "--",
                        showCurrencyFormat("USD", "en-US", item.final_total),
                        `<span class="badge bg-danger fw-medium text-white">${showCurrencyFormat("USD", "en-US", item.sale_debt)}</span>`,
                        btnOptions
                    ];
                });

                tbCustomersDebtsOrdersList.clear().rows.add(formattedData).draw();
                $("#modalCustomerDebtOrdes").modal("show");

            } else {
                tbCustomersDebtsOrdersList.clear().draw();
            }
        } else if (res.status == "warning") {
            // swalInit.fire(res.message, ``, res.status);
            tbCustomersDebtsOrdersList.clear().draw();
        } else {
            tbCustomersDebtsOrdersList.clear().draw();
            console.log(res);
            swalInit.fire(translate.data_could_not_be_loaded_please_contact_the_system_vendor_for_technical_assistance, ``, "error");
        }
    } catch (error) {
        console.log(error);
    }

}


/*=============================================
VALIDATE INPUT FORM
=============================================*/
function validateInputFormData(type) {

    if (type == "edit") {

        var cus_id = $("#cus_id").val();

        if ($.trim(cus_id) == "" && Number(cus_id <= 0)) {
            fnSweetToast(translate.no_data_was_selected_for_updating, "error", 3500);
            return false;
        }
    }

    var cus_full_name = $("#cus_full_name").val();
    var cus_email = $("#cus_email").val();

    if ($.trim(cus_full_name) == "") {
        $("#cus_full_name").css("border", "1px solid red ");
        fnSweetToast(translate.you_must_enter_the_customer_name, "error", 3500);
        return false;
    } else {
        $("#cus_full_name").css("border", `1px solid ${borderColorValidated}`);
    }

    if ($(".intelli-shared-phone").val() != "") {
        if (!intlPhoneFormatShared.isValidNumber()) {
            fnSweetToast(translate.invalid_phone_number_please_try_again, "error", 3500);
            $(".intelli-shared-phone").css("border", "1px solid red");
            return false;
        } else {
            $(".intelli-shared-phone").css("border", `1px solid ${borderColorValidated}`);
        }
    }

    if (cus_email != "") {
        if (validateEmail(cus_email.trim()) == false) {
            $("#cus_email").css("border", "1px solid red ");
            fnSweetToast(translate.invalid_email_address, "error", 3500);
            return false;
        } else {
            $("#cus_email").css("border", `1px solid ${borderColorValidated}`);
        }
    }
}

$(".btnSaveCustomer").click(function () {
    if (validateInputFormData("save") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});


$(".btnEditCustomer").click(function () {
    if (validateInputFormData("edit") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

// ── Helper: set all action buttons to a given state ───────────────────────
function setButtonStatus(state) {
    if (state === 'loading') {
        $('.btnSaveCustomer, .btnEditCustomer')
            .prop('disabled', true)
            .css('cursor', 'not-allowed')
            .html(translate.waiting_icon_text);
        return;
    }
    if (state === 'ready') {
        $('.btnSaveCustomer, .btnEditCustomer')
            .prop('disabled', false)
            .css('cursor', 'pointer')
            .html(`<i class="ph-floppy-disk me-1"></i> ${translate.save}`);
    }
}

/*=============================================
FUNCTION TO SAVE OR UPDATE DATA
=============================================*/
async function fnSaveUpdate() {

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmAddEditCustomer")[0]);
    const apiUrl = 'ajax/customers.ajax.php?op=ajaxSaveUpdate';

    // for (var pair of formPostData.entries()) {
    //     console.log(pair[0] + " - " + pair[1]);
    // }
    // return;

    try {
        const response = await fetch(apiUrl, {
            method: 'POST',
            body: formPostData,
        });


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

        if (data.status == "success") {

            setButtonStatus('ready');

            document.getElementById("frmAddEditCustomer").reset();
            fnSweetAlert(data.message, "", data.status, 1500);
            $("#customer-modal").modal("hide");
            listDataToDatatable();

        } else {
            console.log(data);
            swalInit.fire(translate.data_could_not_be_saved, "", data.status).then(function (result) {
                $("#customer-modal").modal("hide");
                document.getElementById("frmAddEditCustomer").reset();
                setButtonStatus('ready');
            });
        }

    } catch (error) {
        console.error('Error:', error);
        swalInit.fire(translate.data_could_not_be_saved, "", "error").then(function (result) {
            $("#customer-modal").modal("hide");
            document.getElementById("frmAddEditCustomer").reset();
            setButtonStatus('ready');
        });
    }
}