$(document).ready( function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    var userAccessLogsListTable = null;
    var userListTableUrl = $("#userListTable").attr('data-ajax-url');
    var userListTableEmptyText = $("#userListTable").attr('data-empty-text');
    var userListTable = $("#userListTable").DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: userListTableUrl,
            type: 'post',
            "dataSrc": function ( json ) {
                for (var i = 0; i < json.data.length; i++) {
                    $.each( json.data[i], function( key, value ) {
                        json.data[i][key] = value ? value : '-';
                    });
                }

                return json.data;
            }    
        },
        columns: [
            {data: 'first_name', name: 'users.first_name'},
            {data: 'last_name', name: 'users.last_name'},
            {data: 'phone', name: 'users.phone'},
            {data: 'email', name: 'users.email'},
            {data: 'display_name', name: 'roles.display_name'},
            {data: 'status', name: 'users.status'},
            {data: 'actions', name: 'actions', searchable: false, sortable: false}
        ],
        order: [[0, "asc"]],
        searchDelay: 500,
        "language": {
            "paginate": {
                "next": ">",         // Text for the "Next" page button
                "previous": "<"  // Text for the "Previous" page button
            },
              "emptyTable": userListTableEmptyText
            // Add more text customizations if needed
        }
    });

    $('.password-hide-show').click(function() {
        var type = $(this).parent().find('input').attr('type');

        if (type == 'password') {
            $(this).parent().find('input').attr('type', 'text');
        }
        else {
            $(this).parent().find('input').attr('type', 'password');
        }
    });

    $('#addUserFrm').submit(function(e) {
        e.preventDefault();
        var action = $(this).attr('action');
        var button = $(this).find('button[type="submit"]');
        var buttonHtml = button.html();

        if (!button.is(':disabled') && action) {
            button.attr('disabled', 'disabled');
            button.html('<i class="fa fa-spinner fa-spin" style="font-size:24px"></i>');

            $.ajax({
                url: action,
                type: "post",
                data: $(this).serialize(),
                dataType: 'json',
                success:function(data) {
                    button.removeAttr('disabled');
                    button.html(buttonHtml);

                    if (data.success) {
                        $('#newUserModal').modal('hide');
                        $('#validationModal').modal('show');
                        $('#validationModal .error-message').html(data.message);

                        $('#addUserFrm').trigger("reset");
                        userListTable.ajax.reload();
                    }
                    else {
                        $('#validationModal .error-message').html(data.message);
                        $('#validationModal').modal('show');
                    }
                },
                error: function(data) {
                    var errors = data.responseJSON.errors;
                    var errorMessage = '<ul>';
                    $.each(errors, function(index, error) {
                        console.log(error);
                        errorMessage += '<li>' + error[0] + '</li>';
                    });
                    errorMessage += '</ul>';

                    $('#validationModal .error-message').html(errorMessage);
                    $('#validationModal').modal('show');
                    button.removeAttr('disabled');
                    button.html(buttonHtml);
                }
            });
        }
    });

    $(document).on('click', '.suspend-user', function(e) {
        var action = $(this).attr('data-action');

        if (action) {
            Swal.fire({
                title: languageTexts["Are you sure?"],
                text: languageTexts["You would not be able to revert this!"],
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: languageTexts["Yes"],
                cancelButtonText: languageTexts["Cancel"]
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: action,
                        type: "post",
                        data: {},
                        dataType: 'json',
                        success:function(data) {
                            if (data.success) {
                                $('#validationModal').modal('show');
                                $('#validationModal .error-message').html(data.message);

                                userListTable.ajax.reload();
                            }
                        },
                        error: function(data) {
                            var errors = data.responseJSON.errors;
                            var errorMessage = '<ul>';
                            $.each(errors, function(index, error) {
                                console.log(error);
                                errorMessage += '<li>' + error[0] + '</li>';
                            });
                            errorMessage += '</ul>';

                            $('#validationModal .error-message').html(errorMessage);
                            $('#validationModal').modal('show');
                        }
                    });
                }
            });
        }
    });

    $(document).on('click', '.activate-user', function(e) {
        var action = $(this).attr('data-action');

        if (action) {
            Swal.fire({
                title: languageTexts["Are you sure?"],
                text: languageTexts["You would not be able to revert this!"],
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: languageTexts["Yes"],
                cancelButtonText: languageTexts["Cancel"]
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: action,
                        type: "post",
                        data: {},
                        dataType: 'json',
                        success:function(data) {
                            if (data.success) {
                                $('#validationModal').modal('show');
                                $('#validationModal .error-message').html(data.message);

                                userListTable.ajax.reload();
                            }
                        },
                        error: function(data) {
                            var errors = data.responseJSON.errors;
                            var errorMessage = '<ul>';
                            $.each(errors, function(index, error) {
                                console.log(error);
                                errorMessage += '<li>' + error[0] + '</li>';
                            });
                            errorMessage += '</ul>';

                            $('#validationModal .error-message').html(errorMessage);
                            $('#validationModal').modal('show');
                        }
                    });
                }
            });
        }
    });

    $(document).on('click', '.remove-user', function(e) {
        var action = $(this).attr('data-action');

        if (action) {
            Swal.fire({
                title: languageTexts["Are you sure?"],
                text: languageTexts["You would not be able to revert this!"],
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: languageTexts["Yes"],
                cancelButtonText: languageTexts["Cancel"]
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: action,
                        type: "post",
                        data: {},
                        dataType: 'json',
                        success:function(data) {
                            if (data.success) {
                                $('#validationModal').modal('show');
                                $('#validationModal .error-message').html(data.message);

                                userListTable.ajax.reload();
                            }
                        },
                        error: function(data) {
                            var errors = data.responseJSON.errors;
                            var errorMessage = '<ul>';
                            $.each(errors, function(index, error) {
                                console.log(error);
                                errorMessage += '<li>' + error[0] + '</li>';
                            });
                            errorMessage += '</ul>';

                            $('#validationModal .error-message').html(errorMessage);
                            $('#validationModal').modal('show');
                        }
                    });
                }
            });
        }
    });

    $(document).on('click', '.edit-user', function(e) {
        var actionShow = $(this).attr('data-action-show');
        var actionUpdate = $(this).attr('data-action-update');

        if (actionShow && actionUpdate) {
            $.ajax({
                url: actionShow,
                type: "post",
                data: {},
                dataType: 'json',
                success:function(data) {
                    if (data.success) {
                        $('#editUserFrm').attr('action', actionUpdate);
                        $('#editUserFrm input[name="first_name"]').val(data.user.first_name);
                        $('#editUserFrm input[name="last_name"]').val(data.user.last_name);
                        $('#editUserFrm input[name="phone"]').val(data.user.phone);
                        $('#editUserFrm input[name="email"]').val(data.user.email);
                        $('#editUserFrm select[name="role_id"]').val(data.user.role_id);
                        $('#editUserFrm input[name="status"]').val(data.user.status);
                        $('#editUserModal').modal('show');
                    }
                },
                error: function(data) {
                    var errors = data.responseJSON.errors;
                    var errorMessage = '<ul>';
                    $.each(errors, function(index, error) {
                        console.log(error);
                        errorMessage += '<li>' + error[0] + '</li>';
                    });
                    errorMessage += '</ul>';

                    $('#validationModal .error-message').html(errorMessage);
                    $('#validationModal').modal('show');
                }
            });
        }
    });

    $('#editUserFrm').submit(function(e) {
        e.preventDefault();
        var action = $(this).attr('action');
        var button = $(this).find('button[type="submit"]');
        var buttonHtml = button.html();

        if (!button.is(':disabled') && action) {
            button.attr('disabled', 'disabled');
            button.html('<i class="fa fa-spinner fa-spin" style="font-size:24px"></i>');

            $.ajax({
                url: action,
                type: "post",
                data: $(this).serialize(),
                dataType: 'json',
                success:function(data) {
                    button.removeAttr('disabled');
                    button.html(buttonHtml);

                    if (data.success) {
                        $('#editUserModal').modal('hide');
                        $('#validationModal').modal('show');
                        $('#validationModal .error-message').html(data.message);

                        $('#editUserFrm').trigger("reset");
                        userListTable.ajax.reload();
                    }
                    else {
                        $('#validationModal .error-message').html(data.message);
                        $('#validationModal').modal('show');
                    }
                },
                error: function(data) {
                    var errors = data.responseJSON.errors;
                    var errorMessage = '<ul>';
                    $.each(errors, function(index, error) {
                        console.log(error);
                        errorMessage += '<li>' + error[0] + '</li>';
                    });
                    errorMessage += '</ul>';

                    $('#validationModal .error-message').html(errorMessage);
                    $('#validationModal').modal('show');
                    button.removeAttr('disabled');
                    button.html(buttonHtml);
                }
            });
        }
    });

    var userAccessLogsListTableUrl = $("#userAccessLogsListTable").attr('data-ajax-url');
    var userAccessLogsListTableEmptyText = $("#userAccessLogsListTable").attr('data-empty-text');
    $(document).on('click', '.view-user-log', function(e) {
        var action = $(this).attr('data-action');

        if (action) {
            initializeUserAccessLogsListTable(action);
            $('#userActionLogsModal').modal('show');
        }
    });

    function initializeUserAccessLogsListTable(url = userAccessLogsListTableUrl) {
        if (userAccessLogsListTable) {
            userAccessLogsListTable.destroy();
        }

        userAccessLogsListTable = $("#userAccessLogsListTable").DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: url,
                type: 'post',
                "dataSrc": function ( json ) {
                    for (var i = 0; i < json.data.length; i++) {
                        $.each( json.data[i], function( key, value ) {
                            json.data[i][key] = value ? value : '-';
                        });
                    }

                    return json.data;
                }    
            },
            columns: [
                {data: 'date', name: 'user_access_logs.created_at'},
                {data: 'time', name: 'user_access_logs.created_at'},
                {data: 'event', name: 'user_access_logs.event'},
                {data: 'description', name: 'user_access_logs.description'},
                {data: 'status', name: 'user_access_logs.status'},
            ],
            order: [[1, "desc"]],
            searchDelay: 500,
            "language": {
                "paginate": {
                    "next": ">",         // Text for the "Next" page button
                    "previous": "<"  // Text for the "Previous" page button
                },
                  "emptyTable": userAccessLogsListTableEmptyText
                // Add more text customizations if needed
            }
        });
    }
} );