$(document).ready(function () {
    $("#profile-form").on("click", "#saveBtn-contact", function () {

        let fields = ["first_name", "last_name", "user_name", "Phone", "Security_question_index", "Security_answer"];
        sendAjaxRequest("profile-form", fields, "confirm-contact", "error-contact");
    });

    $("#profile-form").on("click", "#cancelBtn-contact", function () {
        reloadForm("profile-form");
    });


    $("#changepassword-form").on("click", "#saveBtn-changepassword", function () {

        let fields = ["currentpassword", "password", "password_confirmation"];
        sendAjaxRequest("changepassword-form", fields, "confirm-changepassword", "error-changepassword", resetPasswordForm);
    });

    $("#changepassword-form").on("click", "#cancelBtn-changepassword", function () {
        reloadForm("changepassword-form");
    });

    $("#organization-form").on("click", "#saveBtn-organization", function () {

        let fields = ["name", "contact_info", "tax_info"];
        sendAjaxRequest("organization-form", fields, "confirm-organization", "error-organization");
    });

    $("#organization-form").on("click", "#cancelBtn-organization", function () {
        reloadForm("organization-form");
    });


    $("#logo-form").on("click", "#saveBtn-Logo", function () {

        let fields = ["logo"];
        sendAjaxRequest("logo-form", fields, "confirm-Logo", "error-Logo");
    });

    function resetPasswordForm() {

        $('#currentpassword').val("");
        $('#password').val("");
        $('#password_confirmation').val("");
    }

});


/**
 * Select logo validation and preview
 *
 */

const imageMimeTypes = [
    'image/png',
    'image/jpeg',
    'image/gif',
];

const originalImage = document.getElementById("displayImage");

const maxWidth = originalImage.getAttribute('data-width');

const maxHeight = originalImage.getAttribute('data-height');

const originalImageSrc = originalImage.getAttribute("data-original-src");

// Function to display a selected image
const errorParagraph = document.querySelector('#error-Logo');
const successParagraph = document.querySelector('#confirm-Logo');

function displaySelectedImage() {

    const imageInput = document.getElementById("logo");
    const displayImage = document.getElementById("displayImage");
    const label = document.getElementById("logoLabel");
    if (imageInput.files && imageInput.files[0]) {

        if (!validateExtension(imageInput.files[0], [...imageMimeTypes])) {
            updateErrorMessage(
                errorParagraph,
                `Image type must be PNG, JPG, JPEG, or GIF.`
            );
            return;
        }

        var widthValidationFailed = false;

        let image = new Image();
        image.src = window.URL.createObjectURL(imageInput.files[0])
        image.onload = () => {
            if (!validateWidth(image.width, maxWidth) || !validateHeight(image.height, maxHeight)) {

                updateErrorMessage(
                    errorParagraph,
                    `Image maximum width shouldn't exceed ${maxWidth}, and Image max height shouldn't exceed ${maxHeight}.`
                );

                widthValidationFailed = true;

            } else {

                if (!validateSize(imageInput.files[0], 1024 ** 2 * 0.5)) {
                    updateErrorMessage(
                        errorParagraph,
                        `Image size can't exceed 500KB.`
                    );
                    return;
                }
                errorParagraph.style.display = 'none'
                const fileName = imageInput.files[0].name;
                label.textContent = fileName;
                const reader = new FileReader();
                reader.onload = function (e) {
                    displayImage.src = e.target.result;
                };
                reader.readAsDataURL(imageInput.files[0]);

            }

        }

    }
}
// Function to reset the displayed image to its original source
function resetImage(e) {
    if (e) {
        e.preventDefault();
        removeFromDB = true
    }
    const displayImage = document.getElementById("displayImage");

    const label = document.getElementById("logoLabel");
    label.textContent = "Choose an Image";

    // Reset the input file field
    const imageInput = document.getElementById("logo");
    imageInput.value = null;

    if (typeof removeFromDB !== 'undefined') {
        let form = document.getElementById("form-logo");
        let deleteUrl = document.getElementById("logo-form").getAttribute('data-delete');
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: deleteUrl,
            type: "POST",
            // data: new FormData(form),
            success: function (response) {
                if (response.demo) {
                    $(`#demo-modal`).find('h5').text(response.demo).show();
                    $(`#demo-modal`).modal('show');

                } else {
                    displayImage.src = originalImageSrc;
                    $(`#logo-form`).html($(response).find(`#logo-form`).html());
                }
            }
        });
        errorParagraph.style.display = 'none'
        successParagraph.style.display = 'none'
    }
}

// Event listener to reset the displayed image when the delete button is clicked
document
    .getElementById("cancelBtn-Logo")
    .addEventListener("click", resetImage);


function validateSize(file, max) {
    return file.size <= max;
}

function validateExtension(file, allowedExtensions = []) {
    return allowedExtensions.includes(file.type);
}


function validateWidth(fileWidth, maxWidth) {
    return fileWidth <= maxWidth;
}

function validateHeight(fileHeight, maxHeight) {
    return fileHeight <= maxHeight;
}

function updateErrorMessage(el, message) {
    el.innerText = message;
    el.style.display = 'block';
    successParagraph.style.display = 'none';
    resetImage();

}
function updateSuccessMessage(el, message) {
    el.innerText = message;
    el.style.display = 'block';
    errorParagraph.style.display = 'none';
}
