$(document).ready(function () {
    
    $('.status-select').select2({
        placeholder: 'Select Status', 
        allowClear: false,             
        width: '100%',                
        minimumResultsForSearch: Infinity 
    });
    $('.select-company').select2({
        placeholder: 'Select Company', 
        allowClear: false,             
        width: '100%',                
        minimumResultsForSearch: Infinity 
    });
    $(".no_special_chars").bind("input", function () {
        var c = this.selectionStart,
            r = /[^a-z0-9 .]/gi,
            v = $(this).val();
        if (r.test(v)) {
            $(this).val(v.replace(r, ""));
            c--;
        }
        this.setSelectionRange(c, c);
    });

    $(document).on("input", ".number-only", function () {
        // Replace any non-numeric character
        $(this).val($(this).val().replace(/[^0-9]/g, ""));
    });

    $(document).on("keydown", ".decimal-only", function (event) {


        if (event.shiftKey == true) {
            event.preventDefault();
        }

        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

        } else {
            event.preventDefault();
        }

        if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
            event.preventDefault();

    });

    // function sweetConfirm(text, confirmButtonText, cancelButtonText, confirmCallback, cancelCallback = null) {
    //     Swal.fire({
    //         text: text,
    //         icon: 'warning',

    //         cancelButtonColor: '#3085d6',
    //         cancelButtonText: cancelButtonText,
    //         confirmButtonText: confirmButtonText,
    //         showCancelButton: true,
    //         customClass: {
    //             confirmButton: 'btn btn-primary',
    //         },
    //         showClass: {
    //             popup: `
    //                 animate__animated
    //                 animate__fadeInUp
    //                 animate__faster`
    //         },
    //         hideClass: {
    //             popup: `
    //                 animate__animated
    //                 animate__fadeOutDown
    //                 animate__faster`
    //         }
    //     }).then((result) => {
    //         if (result.isConfirmed) {
    //             if (typeof confirmCallback === 'function') {
    //                 confirmCallback();
    //             }
    //         } else if (result.dismiss === Swal.DismissReason.cancel) {
    //             if (typeof cancelCallback === 'function') {
    //                 cancelCallback();
    //             }
    //         }
    //     });
    // }

    function sweetConfirm({
        text,
        confirmButtonText = 'Yes',
        cancelButtonText = 'Cancel',
        confirmButtonColor = '#235361', // Default confirm button color
        cancelButtonColor = '#3085d6', // Default cancel button color
        small = false, // Toggle for smaller alert
        confirmCallback,
        cancelCallback = null,
    }) {
        Swal.fire({
            text: text,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: confirmButtonText,
            cancelButtonText: cancelButtonText,
            confirmButtonColor: confirmButtonColor,
            cancelButtonColor: cancelButtonColor,
            customClass: {
                popup: small ? 'small-alert' : '', // Apply smaller alert style if `small` is true
            },
            showClass: {
                popup: `
                    animate__animated
                    animate__fadeInUp
                    animate__faster`
            },
            hideClass: {
                popup: `
                    animate__animated
                    animate__fadeOutDown
                    animate__faster`
            }
        }).then((result) => {
            if (result.isConfirmed) {
                if (typeof confirmCallback === 'function') {
                    confirmCallback();
                }
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                if (typeof cancelCallback === 'function') {
                    cancelCallback();
                }
            }
        });
    }
    

    function sweetAlert(text, icon = 'success', buttonText = 'OK', callback = null) {
        Swal.fire({
            text: text,
            icon: icon,
            confirmButtonText: buttonText,
            showClass: {
                popup: `
                    animate__animated
                    animate__fadeInUp
                    animate__faster`
            },
            hideClass: {
                popup: `
                    animate__animated
                    animate__fadeOutDown
                    animate__faster`
            }
        }).then((result) => {
            if (result.isConfirmed && typeof callback === 'function') {
                callback();
            }
        }); 
    }

       
    $("body").on("click", ".delete-btn", function () {
        const deleteUrl = $(this).data("url");
        //  const DELETE_ICON_URL = "{{ url('public/assets/images/delete-circle.svg') }}";
        // alert(DELETE_ICON_URL)
        Swal.fire({
            iconHtml: `<img src="${ASSET_PATH}/delete-circle.svg" class="img-fluid">`,
            text: "Are you sure? You will not be able to recover this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'No, keep it!',
            reverseButtons: true,
            customClass: {
                confirmButton: 'custom-ok-button-class',
                cancelButton: 'btn custom-cancel-button-class',
            }
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(deleteUrl, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                }).then(response => response.json())
                    .then(data => {
                        if (data.status === "success") {
                            Swal.fire({
                                iconHtml: `<img src="${ASSET_PATH}/success-circle.svg" class="img-fluid">`,
                                text: data.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            }).then(() => {
                                location.reload(); // Refresh the table
                            });
                        } else {
                            Swal.fire({
                                iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                                text: data.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            });
                        }
                    }).catch(error => {
                        Swal.fire({
                            text: "An error occurred.",
                            iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                            confirmButtonText: "OK",
                            customClass: {
                                confirmButton: 'custom-ok-button-class w-sm'
                            }
                        });
                    });
            }
        });
    });
    
    
     $("body").on("click", ".approve-btn", function () {
        const deleteUrl = $(this).data("url");
        //  const DELETE_ICON_URL = "{{ url('public/assets/images/delete-circle.svg') }}";
        // alert(DELETE_ICON_URL)
        Swal.fire({
            iconHtml: `<img src="${ASSET_PATH}/delete-circle.svg" class="img-fluid">`,
            text: "Are you sure? You You want to approve this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, approve this!',
            cancelButtonText: 'No, keep this!',
            reverseButtons: true,
            customClass: {
                confirmButton: 'custom-ok-button-class',
                cancelButton: 'btn custom-cancel-button-class',
            }
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(deleteUrl, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                }).then(response => response.json())
                    .then(data => {
                        if (data.status === "success") {
                            Swal.fire({
                                iconHtml: `<img src="${ASSET_PATH}/success-circle.svg" class="img-fluid">`,
                                text: data.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            }).then(() => {
                                location.reload(); // Refresh the table
                            });
                        } else {
                            Swal.fire({
                                iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                                text: data.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            });
                        }
                    }).catch(error => {
                        Swal.fire({
                            text: "An error occurred.",
                            iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                            confirmButtonText: "OK",
                            customClass: {
                                confirmButton: 'custom-ok-button-class w-sm'
                            }
                        });
                    });
            }
        });
    });
    

    $("body").on('change', '.status-checkbox', function () {
        const checkbox = $(this);
        const packageUrl = checkbox.data('url');
        const newStatus = checkbox.prop('checked') ? 1 : 0;
        const id = checkbox.data('id');
    
        setTimeout(function () {
            Swal.fire({
                iconHtml: `<img src="${ASSET_PATH}/alert-circle.svg" class="img-fluid">`,
                text: "Are you sure you want to change the status?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Change It!',
                cancelButtonText: 'Cancel',
                reverseButtons: true,
                customClass: {
                    confirmButton: 'custom-ok-button-class',
                    cancelButton: 'btn custom-cancel-button-class',
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: packageUrl,
                        type: 'PATCH',
                        dataType: 'json',
                        data: {
                            _token: $('meta[name="csrf-token"]').attr('content'),
                            status: newStatus,
                        },
                        success: function (response) {
                            if (response.status === "success") {
                                Swal.fire({
                                    iconHtml: `<img src="${ASSET_PATH}/success-circle.svg" class="img-fluid">`,
                                    text: response.message,
                                    confirmButtonText: "OK",
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm'
                                    }
                                });
                            } else {
                                Swal.fire({
                                    iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                                    text: response.message,
                                    confirmButtonText: "OK",
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm'
                                    }
                                });
                            }
                        },
                        error: function (xhr) {
                            checkbox.prop('checked', !newStatus); // Revert checkbox state
                            Swal.fire({
                                text: xhr.responseJSON?.message || 'Failed to update status. Please try again.',
                                iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm'
                                }
                            });
                        }
                    });
                } else {
                    checkbox.prop('checked', !checkbox.prop('checked')); // Revert checkbox state
                }
            });
        }, 0);
    });


    $("body").on("click", "#changePasswordBtn", function () {
        const changePasswordUrl = $(this).data("url");
        const newPassword = $("#passwordInput").val();
        const confirmPassword = $("#passwordConfirmInput").val();

        if (newPassword !== confirmPassword || newPassword === '' || confirmPassword === '') {
            Swal.fire({
            text: "Passwords do not match.",
            iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
            confirmButtonText: "OK",
            customClass: {
                confirmButton: 'custom-ok-button-class w-sm'
            }
            });
            return;
        }

        $.ajax({
            url: changePasswordUrl,
            type: 'POST',
            dataType: 'json',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content'),
                password: newPassword,
                password_confirmation: confirmPassword
            },
            success: function (response) {
            if (response.status === "success") {
                Swal.fire({
                iconHtml: `<img src="${ASSET_PATH}/success-circle.svg" class="img-fluid">`,
                text: response.message,
                confirmButtonText: "OK",
                customClass: {
                    confirmButton: 'custom-ok-button-class w-sm'
                }
                }).then(() => {
                    $("#newPassword").val('');
                    $("#confirmPassword").val('');
                    $("#changepass").modal('hide');
                });
            } else {
                Swal.fire({
                iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                text: response.message,
                confirmButtonText: "OK",
                customClass: {
                    confirmButton: 'custom-ok-button-class w-sm'
                }
                });
            }
            },
            error: function (xhr) {
            Swal.fire({
                text: xhr.responseJSON?.message || 'Failed to change password. Please try again.',
                iconHtml: `<img src="${ASSET_PATH}/error-circle.svg" class="img-fluid">`,
                confirmButtonText: "OK",
                customClass: {
                confirmButton: 'custom-ok-button-class w-sm'
                }
            });
            }
        });
    });

    
    

    if($(".edit-form").length > 0) {

        $('#submitBtn').prop('disabled', true);

        // Store the initial state of the form when the page is loaded
        var initialValues = $('.edit-form').serialize();

        // Listen for changes in any form fields and compare with initial state
        $('body').on('input change','.edit-form input, .edit-form textarea, .edit-form select', function() {
            // If the form values are different from the initial state, enable the submit button
            if ($('.edit-form').serialize() !== initialValues) {
                $('#submitBtn').prop('disabled', false);
            } else {
                $('#submitBtn').prop('disabled', true);
            }
        });
        

    }

    

    

});
