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

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

// Column selectors
const tbPaymentTypesList = $('.payment-types-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, "asc"]],
});

// Add New Enterprise
$(document).on("click", ".btnAddNew", function () {

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

    $(".btnSave").show();
    $(".btnEdit").hide();

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

    $("#pay_type_id").val("");
    $("#pay_type_ent_id").val($("#ent_id_value").val());
    $("#pay_type_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());

    $('#payment-type-modal').modal('show');
});

// 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/payment-types.ajax.php?op=ajaxPaymentTypeList&ent_id=${props.ent_id}&pos_id=${props.pos_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: build a toggle switch ─────────────────────────────────────────
    function buildToggle(isOn, handlerFn, id, onValue, offValue) {
        const [nextVal, state, label] = isOn
            ? [onValue, 'checked', translate.enabled]
            : [offValue, 'unchecked', translate.disabled];

        return `
            <div class="form-check form-switch mb-2">
                <input type="checkbox"
                       class="form-check-input form-check-input-success"
                       onclick="${handlerFn}(${id},'${nextVal}',this,'${state}')"
                       ${isOn ? 'checked' : ''}>
                <label class="form-check-label">${label}</label>
            </div>`;
    }

    // ── Translatable payment type names (keyed by uppercased canonical name) ──
    const payTypeTranslations = {
        'CASH': translate.cash,
        'CREDIT CARD': translate.credit_card,
        'DEBIT CARD': translate.debit_card,
        'BANK DEPOSIT': translate.bank_deposit,
    };

    // ── 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(),
        pos_id: ($("#pos_id_value").val() || '').trim(),
    };

    // ── 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') {

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

            if (res.data.length > 0) {

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

                    // Resolve translated name or fall back to the original uppercased
                    const nameKey = item.pay_type_name.toUpperCase();
                    const payTypeName = payTypeTranslations[nameKey] ?? nameKey;

                    return [
                        item.pay_type_id,
                        payTypeName,
                        buildToggle(
                            item.pay_type_status !== 'Disabled',
                            'jsSwitchStatus',
                            item.pay_type_id,
                            'Disabled',
                            'Enabled'
                        ),
                        `<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>`,
                    ];
                });

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

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

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

            tbPaymentTypesList.clear().draw();

        } else {

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

// Enable or disable status
async function jsSwitchStatus(pay_type_id, status, thisSwitcher, switcher) {

    let props = {
        pay_type_id: pay_type_id,
        status: status,
        csrf_token: csrf_token
    }

    swalInit.fire({
        title: translate.are_you_sure,
        text: translate.confirm_that_you_want_to_perform_this_action,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: translate.yes,
        cancelButtonText: translate.no,
        buttonsStyling: false,
        customClass: {
            confirmButton: 'btn btn-success',
            cancelButton: 'btn btn-danger'
        }
    }).then(async function (result) {
        if (result.value) {

            try {

                const response = await $.ajax({
                    type: "POST",
                    url: "ajax/payment-types.ajax.php?op=ajaxSwitchStatus",
                    data: props,
                });

                const res = JSON.parse(response);

                if (res.status == "success") {
                    fnSweetToast(res.message, res.status, 2500);
                    listDataToDatatable();
                }

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

        } else if (result.dismiss === swal.DismissReason.cancel) {
            if (switcher == 'checked') {
                thisSwitcher.checked = true;
            } else {
                thisSwitcher.checked = false;
            }
        }
    });
}


// Edit enterprise function
function jsEditData(data) {

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

    $(".btnSave").hide();
    $(".btnEdit").show();

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

    $("#pay_type_id").val(data.pay_type_id);
    $("#pay_type_ent_id").val(data.pay_type_ent_id);
    $("#pay_type_pos_id").val(data.pay_type_pos_id);
    $("#pay_type_name").val(data.pay_type_name);
    $(".pos_description").text(data.pos_name);

    $("#payment-type-modal").modal("show");
}

// Validation input form
function validateInputFormData(type) {

    var pay_type_ent_id = $("#pay_type_ent_id").val();
    var pay_type_pos_id = $("#pay_type_pos_id").val();

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

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

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

    if ($.trim(pay_type_name) == "") {
        $("#pay_type_name").css("border", "1px solid red ");
        fnSweetToast(translate.you_must_enter_the_pay_type_name, "warning");
        return false;
    } else {
        $("#pay_type_name").css("border", `1px solid ${borderColorValidated}`);
    }
}


// Save enterprise function
$(document).on("click", ".btnSave", function () {
    if (validateInputFormData("save") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

// Save enterprise function
$(document).on("click", ".btnEdit", function () {
    if (validateInputFormData("edit") == false) {
        return false;
    } else {
        fnSaveUpdate();
    }
});

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

// Save and Edit enterprise function
async function fnSaveUpdate() {

    setButtonStatus('loading');

    const formPostData = new FormData($("#frmPaymentType")[0]);
    const apiUrl = 'ajax/payment-types.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');
            fnSweetAlert(data.message, "", data.status, 1500);
            document.getElementById("frmPaymentType").reset();
            $("#payment-type-modal").modal("hide");
            listDataToDatatable();

        } else {
            console.log(data);
            swalInit.fire(translate.data_could_not_be_saved, "", data.status).then(function (result) {
                setButtonStatus('ready');
            });
        }

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