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

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

// Column selectors
const tbCategoriesList = $('.categories-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"]],
});

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

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

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

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

    $("#cat_id").val("");
    $("#cat_ent_id").val($("#ent_id_value").val());
    $("#cat_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());

    $('#category-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/categories.ajax.php?op=ajaxCategoriesList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&cat_status=${props.cat_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: 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>`;
    }

    // ── 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(),
        cat_status: ($(".searchStatus").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 => [
                    item.cat_id,
                    item.pos_name,
                    item.cat_name,
                    buildToggle(item.cat_status !== 'Disabled', 'jsSwitchStatus', item.cat_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>`,
                ]);

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

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

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

            tbCategoriesList.clear().draw();

        } else {

            tbCategoriesList.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) {
        tbCategoriesList.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(cat_id, status, thisSwitcher, switcher) {

    let props = {
        cat_id: cat_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: 'warning',
        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/categories.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;
            }
        }
    });
}


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

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

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

    document.getElementById("frmAddEditCategory").reset();
    // Modal form
    $("#cat_id").val(data.cat_id);
    $("#cat_ent_id").val(data.cat_ent_id);
    $("#cat_pos_id").val(data.cat_pos_id);
    $("#cat_name").val(data.cat_name);
    $(".pos_description").text(data.pos_name);

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


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

    if (type == "edit") {

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

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

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

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

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


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

document.getElementById('cat_name').addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
        event.preventDefault(); // Prevent the form from submitting
    }
});

// ── 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}`);
    }
}

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

    setButtonStatus('loading');

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

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

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