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

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

// Column selectors
const tbProvidersList = $('.providers-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", ".btnAddProvider", function () {

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

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

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

    $("#prov_id").val("");
    $("#prov_ent_id").val($("#ent_id_value").val());
    $("#prov_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());

    $('#provider-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/providers.ajax.php?op=ajaxProvidersList&ent_id=${props.ent_id}&pos_id=${props.pos_id}&prov_status=${props.prov_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(),
        prov_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.prov_id,
                    item.pos_name,
                    item.prov_name,
                    item.prov_address,
                    item.prov_phone,
                    item.prov_fiscal_number,
                    buildToggle(
                        item.prov_status !== 'Disabled',
                        'jsSwitchStatus',
                        item.prov_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>`,
                ]);

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

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

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

            tbProvidersList.clear().draw();

        } else {

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

    let props = {
        prov_id: prov_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/providers.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_provider);

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

    document.getElementById("frmAddEditProvider").reset();
    // Modal form
    $("#prov_id").val(data.prov_id);
    $("#prov_ent_id").val(data.prov_ent_id);
    $("#prov_pos_id").val(data.prov_pos_id);
    $("#prov_name").val(data.prov_name);
    $("#prov_fiscal_number").val(data.prov_fiscal_number);
    $("#prov_address").val(data.prov_address);
    $("#prov_city").val(data.prov_city);
    $("#prov_state").val(data.prov_state);
    $("#prov_zip_code").val(data.prov_zip_code);
    $("#prov_country").val(data.prov_country);
    // $("#prov_phone").val(data.prov_phone);

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

    $("#prov_phone2").val(data.prov_phone2);
    $("#prov_email").val(data.prov_email);
    $(".pos_description").text(data.pos_name);

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


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

    if (type == "edit") {

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

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

    var prov_name = $("#prov_name").val();
    // var prov_address = $("#prov_address").val();
    // var prov_phone = $("#prov_phone").val();
    var prov_email = $("#prov_email").val();

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

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

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

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

    // if ($.trim(prov_phone) == "") {
    //     $("#prov_phone").css("border", "1px solid red ");
    //     fnSweetToast(translate.you_must_enter_the_provider_phone, "error", 3500);
    //     return false;
    // } else {
    //     $("#prov_phone").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('prov_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($("#frmAddEditProvider")[0]);
    const apiUrl = 'ajax/providers.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("frmAddEditProvider").reset();
            fnSweetAlert(data.message, "", data.status, 1500);
            $("#provider-modal").modal("hide");
            listDataToDatatable();

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

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

// International Phone Number Validation
const intellinput = document.querySelector(".intelli-phone");

const intlPhoneFormat = window.intlTelInput(intellinput, {
    initialCountry: "auto",
    geoIpLookup: callback => {
        fetch("https://ipapi.co/json")
            .then(res => res.json())
            .then(data => callback(data.country_code))
            .catch(() => callback("us"));
    },
    strictMode: true,
    autoPlaceholder: true,
    formatAsYouType: true,
    formatOnDisplay: true,
    nationalMode: false,
    hiddenInput: () => ({ phone: "full_phone", country: "country_code" }),
    loadUtilsOnInit: "../intlTelInput/utils.js", // just for formatting/placeholders etc
    // loadUtilsOnInit: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.6.0/build/js/utils.js",
});


var productSearchTimeId = null;
$(".intelli-phone").keyup(function (e) {

    if (productSearchTimeId) {
        clearTimeout(productSearchTimeId);
    }

    if (!intlPhoneFormat.isValidNumber()) {
        // console.log("Invalid number. Please try again.");
        return false;
    }

    // Get the formatted phone number
    const fullPhone = intlPhoneFormat.getNumber();

    // Get the hidden input value
    productSearchTimeId = setTimeout(() => {
        if (fullPhone) {
            // console.log(`fullPhone: ${fullPhone}`);
            intlPhoneFormat.setNumber(fullPhone);
        }
    }, 500);

});