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

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

// ON CHANGE BRANCH ID
$(document).on("change", "#pos_id_value", async function () {
    let pos_id = $(this).val();
    let posInfo = await getBranchData(pos_id);
    jsStorePosInfo(posInfo);
    listDataToDatatable();
});

// Column selectors
const tbUsersList = $('.users-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", ".btnAddNew", function () {

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

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

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

    $("#user_id").val("");
    $("#user_ent_id").val($("#ent_id_value").val());
    $("#user_pos_id").val($("#pos_id_value").val());
    $(".pos_description").text($("#pos_id_value option:selected").text());
    $(".picturePreview").attr("src", "assets/images/anonymous.png");

    selectUserProfile();

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

async function selectUserProfile(currentValue = "") {

    $("#user_profile").html("");

    let user_info = await getUserData(sess_user_id);

    // Get object from localStorage
    let pos_info = JSON.parse(localStorage.getItem("pos_info"));

    let options = [
        { value: 'Cashier', text: translate.cashier },
        { value: 'Manager', text: translate.manager },
        { value: 'Owner', text: translate.owner },
    ];

    if (user_info.user_profile === 'Manager') options = [
        { value: 'Cashier', text: translate.cashier },
        { value: 'Manager', text: translate.manager },
    ];

    if (pos_info.pos_business_category === 'Restaurant' || pos_info.pos_business_category === 'Nightclub') {
        options.unshift({ value: 'Waiter', text: translate.waiter, selected: true });
    } else {
        options[0].selected = true; // Default to Cashier
    }

    if (user_info.user_profile === 'ROOT') {
        options.push({ value: 'ROOT', text: 'ROOT' });
    }

    options = options.map(option => `<option value="${option.value}"${option.value === currentValue ? ' selected' : ''}>${option.text}</option>`);

    $("#user_profile").html(options);
}

// 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/users.ajax.php?op=ajaxUsersList&ent_id=${props.ent_id}&pos_id=${props.pos_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: 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>`;
    }

    // ── Profile translation map ───────────────────────────────────────────────
    const profileTranslations = {
        Waiter: translate.waiter,
        Cashier: translate.cashier,
        Manager: translate.manager,
        Owner: translate.owner,
    };

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

            // ── Apply column visibility now that data is confirmed ────────────
            tbUsersList.column(8).visible(sess_user_profile === 'ROOT');

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

            if (res.data.length > 0) {

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

                    const itemJson = JSON.stringify(item);

                    // ── Last activity / last login — both conditions must hold ─
                    const lastLogin = (item.user_last_login !== null && item.user_last_login.trim() !== '')
                        ? item.user_last_login
                        : 'No connection';

                    const last_activity = (item.user_last_activity !== null && item.user_last_activity.trim() !== '')
                        ? timeAgo(item.user_last_activity)
                        : 'No activity';

                    // ── Profile label — lookup map with fallback ──────────────
                    const userProfile = profileTranslations[item.user_profile] ?? item.user_profile;

                    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='jsEditData(${itemJson})'><i class="ph-pencil-simple-line me-1"></i>${translate.edit}</button>
                    <button type="button" class="dropdown-item light-warning-on-hover" onclick='jsBranchPermissions(${itemJson})'><i class="ph-check-circle me-1"></i> ${translate.branch_permissions}</button>
                    </div>`;

                    return [
                        item.user_id,
                        item.pos_name,
                        `<img src="${item.user_image || 'assets/images/no-image.png'}"
                              class="w-32px h-32px rounded-pill"
                              onerror="this.onerror=null;this.src='assets/images/no-image.png';">`,
                        `${item.user_firstname} ${item.user_lastname}`,
                        item.user_name,
                        userProfile,
                        lastLogin,
                        last_activity,
                        buildToggle(item.user_email_report !== 'Disabled', 'jsSwitchEmailReportStatus', item.user_id, 'Disabled', 'Enabled'),
                        buildToggle(item.user_status !== 'Disabled', 'jsSwitchStatus', item.user_id, 'Disabled', 'Enabled'),
                        btnOptions,
                    ];
                });

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

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

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

            tbUsersList.clear().draw();

        } else {

            tbUsersList.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) {
        tbUsersList.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 jsSwitchEmailReportStatus(user_id, status, thisSwitcher, switcher) {

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

    let text = translate.confirm_that_you_want_to_disable_this_account;
    if (status == 'Enabled') text = translate.confirm_that_you_want_to_enable_this_account;

    swalInit.fire({
        title: translate.are_you_sure,
        text: text,
        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/users.ajax.php?op=ajaxSwitchEmailReportStatus",
                    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;
            }
        }
    });
}

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

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

    let text = translate.confirm_that_you_want_to_disable_this_account;
    if (status == 'Enabled') text = translate.confirm_that_you_want_to_enable_this_account;

    swalInit.fire({
        title: translate.are_you_sure,
        text: text,
        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/users.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
async function jsEditData(data) {

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

    $(".btnSave").hide();
    $(".btnEdit").show();
    document.getElementById("frmUsers").reset();

    $("#user_id").val(data.user_id);
    $("#user_ent_id").val(data.user_ent_id);
    $("#user_pos_id").val(data.user_pos_id);
    $("#user_firstname").val(data.user_firstname);
    $("#user_lastname").val(data.user_lastname);
    $("#user_document").val(data.user_document).trigger('change');
    $("#user_document_number").val(data.user_document_number);

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

    $("#user_email").val(data.user_email);
    $("#user_address").val(data.user_address);
    $("#user_birthday").val(data.user_birthday);

    if (data.user_birthday) {
        let picker = $('#user_birthday').data('daterangepicker');
        picker.setStartDate(data.user_birthday);
        picker.setEndDate(data.user_birthday); // required for single picker
        $('#user_birthday').val(data.user_birthday);
    }

    $("#user_name").val(data.user_name);
    $("#user_password").val("");
    $("#user_password_confirm").val("");
    $("#current_password").val(data.user_password);
    $(".pos_description").text(data.pos_name);

    let imagePath = data.user_image || "assets/images/anonymous.png";
    $(".picturePreview").off("error").on("error", function () {
        $(this).off("error").attr("src", "assets/images/anonymous.png");
    }).attr("src", imagePath);

    selectUserProfile(data.user_profile);

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

// Edit function
async function jsGeneralPermissions(data) {

    $(".btnSavePermission").hide();
    $(".btnEditPermission").show();
    document.getElementById("frmUsersPermission").reset();

    $("#perm_user_id").val(data.user_id);

    $("#user-permission-modal").modal("show");
}


$(document).on("change", ".new_picture", async function () {

    var imageUploaded = this.files[0];

    //image validation
    if (imageUploaded["type"] != "image/jpeg" && imageUploaded["type"] != "image/jpg" && imageUploaded["type"] != "image/png") {

        $(".new_picture").val("");

        fnSweetToast(translate.the_image_must_be_in_jpg_jpeg_or_png_forma, "error", 3500);

    } else if (imageUploaded["size"] > 2000000) {

        $(".new_picture").val("");

        fnSweetToast(translate.the_image_must_not_exceed_2m, "error", 3500);

    } else {

        var imageData = new FileReader;
        imageData.readAsDataURL(imageUploaded);

        $(imageData).on("load", function (event) {
            var imagePath = event.target.result;
            $(".picturePreview").attr("src", imagePath);
        })
    }
});

// Validation input form
function validateInputFormData(type) {

    if (type == "edit") {

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

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

    var user_firstname = $("#user_firstname").val();
    var user_lastname = $("#user_lastname").val();
    var user_document_number = $("#user_document_number").val();
    var user_email = $("#user_email").val();
    var user_address = $("#user_address").val();
    var user_name = $("#user_name").val();
    var user_password = $("#user_password").val();
    var user_password_confirm = $("#user_password_confirm").val();

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

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

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

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

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

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

    if ($.trim(user_password_confirm) != $.trim(user_password)) {
        $("#user_password_confirm").css("border", "1px solid red ");
        fnSweetToast(translate.error_you_must_confirm_the_password_correctly, "error");
        return false;
    } else {
        $("#user_password_confirm").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 User function
async function fnSaveUpdate() {

    setButtonStatus('loading');

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

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

            // console.error('Save failed:', res);
            setButtonStatus('ready');

            // Show all failures, let user fix and retry
            await swalInit.fire(data.message, "", data.status);

        } else {
            console.log(data);
            await swalInit.fire(data.message, "", data.status);
            setButtonStatus('ready');
        }

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


async function listBranchPermissions(ent_id, userPosAccess = {}) {

    try {

        const url = `ajax/branches.ajax.php?op=ajax_selectBranchesPermissionsByEntId&ent_id=${ent_id}`;
        const response = await fetch(url);

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

        const res = await response.json();

        $(".user_branch_permission").html("");

        if (res.status == "success") {
            res.data.forEach(item => {
                let selected = ""; // Initialize as empty before each item

                if (userPosAccess) {
                    // Check if any pos_id in userPosAccess matches the current item.pos_id
                    const isSelected = userPosAccess.some(pos_perm => pos_perm.pos_id == item.pos_id);

                    // Set selected attribute if match is found
                    if (isSelected) {
                        selected = "selected";
                    } else {
                        selected = "";
                    }
                }

                // Append the option, with or without the 'selected' attribute
                $(".user_branch_permission").append(`<option value='${item.pos_id}' ${selected}> ${item.pos_name}</option>`);
            });
        }

    } catch (error) {
        console.log(error);
    }
}

// Edit function
async function jsBranchPermissions(data) {

    $("#btn-select-all").html(`<i class="ph-check-circle me-1"></i> ${translate.select_all}`);

    $("#user_id_branch_permission").val(data.user_id);

    if (data.user_branch_access) {
        const userPosAccess = JSON.parse(data.user_branch_access);
        listBranchPermissions(data.user_ent_id, userPosAccess);

    } else {

        listBranchPermissions(data.user_ent_id);
    }

    $("#user-branch-permission-modal").modal("show");
}

$(document).on("click", "#btn-select-all", function () {
    // Select the select element using jQuery
    let selectElement = document.querySelector('.user_branch_permission');
    let allSelected = true;

    // Check if all options are selected
    for (let option of selectElement.options) {
        if (!option.selected) {
            allSelected = false; // If any option is not selected, we set allSelected to false
            break;
        }
    }

    // If all are selected, unselect them. Otherwise, select all.
    for (let option of selectElement.options) {
        option.selected = !allSelected;
    }

    // Update the button text based on the current state
    if (allSelected) {
        $(this).html(`<i class="ph-check-circle me-1"></i> ${translate.select_all}`);
    } else {
        $(this).html(`<i class="ph-x-circle me-1"></i> ${translate.unselect_all}`);
    }

    // Trigger the change event for the UI to visually reflect the changes
    $(selectElement).trigger('change');

});


$(document).on("click", ".btnSaveBranchPermission", function () {

    // Select the multiple select element
    let user_branch_permission = document.querySelector('.user_branch_permission');

    // Initialize an array to store the selected values
    let selectedOptions = [];

    // Loop through the selected options
    for (let option of user_branch_permission.selectedOptions) {
        selectedOptions.push({
            pos_id: option.value,  // Get the option value
            pos_name: option.text  // Get the option text
        });
    }

    // Convert the selected options array into a JSON object
    let userPosAccess = JSON.stringify(selectedOptions);

    const user_id = $("#user_id_branch_permission").val();

    let jsonObject = {
        user_id: user_id,
        branch_permission: userPosAccess,
        csrf_token: csrf_token
    };

    fnSaveUpdateBranchAccess(jsonObject);

});

// Save and Edit enterprise function

async function fnSaveUpdateBranchAccess(jsonObject) {

    const apiUrl = 'ajax/users.ajax.php?op=ajaxSaveUpdateBranchAccess';

    try {

        const response = await $.ajax({
            type: "POST",
            url: apiUrl,
            data: jsonObject,
        });

        const res = JSON.parse(response);

        if (res.status == "success") {
            swalInit.fire(res.message, "", res.status).then(function (result) {
                $("#user-branch-permission-modal").modal("hide");
                listDataToDatatable();
            });

        } else {
            console.log(data);
            swalInit.fire(res.message, "", res.status);
        }

    } catch (error) {
        console.error('Error:', error);
        swalInit.fire(translate.data_could_not_be_saved, "", "error").then(function (result) {
            $("#user-branch-permission-modal").modal("hide");
        });
    }
}

// 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,
    separateDialCode: false,
    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);
        }
    }, 100);

});