//jshint esversion:6
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

function countUsers(){
    $.ajax({
        url: '/admin/users/count',
        type: 'GET',
        success: function(response) {
            $(".total").html(response.total);
        },
        error: function(response){
            // console.log(response);
        }
    });
}countUsers();

let table = $('.users-init').DataTable({
    processing: true,
    serverSide: true,
    ajax: "/admin/users/load",
    columns: [
        {
            data: 'DT_RowIndex',
            name: 'DT_RowIndex',
            orderable: false,
            searchable: false,
            className: 'nk-tb-col'
        },
        {
            data: 'username',
            name: 'username',
            searchable: true,
            className: 'nk-tb-col'
        },
        {
            data: 'balance',
            name: 'account_balance',
            searchable: true,
            className: 'nk-tb-col'
        },
        {
            data: 'account_type',
            name: 'account_type',
            className: 'nk-tb-col',
            orderable: false,
            searchable: false
        },
        {
            data: 'status',
            name: 'status',
            className: 'nk-tb-col',
            orderable: false,
            searchable: false
        },
        {
            data: 'strength',
            name: 'strength',
            className: 'nk-tb-col',
            orderable: false,
            searchable: false
        },
        {
            data: 'created_at',
            name: 'join_date',
            className: 'nk-tb-col',
            orderable: false,
            searchable: false
        },
        {
            data: 'action',
            name: 'action',
            orderable: false,
            searchable: false,
            className: 'nk-tb-col  nk-tb-col-tools'
        },
    ],
    // responsive: true,
    autoWidth: false,
    dom: '<"row justify-between g-2"<"col-7 col-sm-6 text-left"f><"col-5 col-sm-6 text-right"<"datatable-filter"l>>><"datatable-wrap my-3"t><"row align-items-center"<"col-7 col-sm-12 col-md-9"p><"col-5 col-sm-12 col-md-3 text-left text-md-right"i>>',
    language: {
        search: "",
        searchPlaceholder: "Type in to Search",
        lengthMenu: "<span class='d-none d-sm-inline-block'>Show</span><div class='form-control-select'> _MENU_ </div>",
        info: "_START_ -_END_ of _TOTAL_",
        infoEmpty: "No records found",
        infoFiltered: "( Total _MAX_  )",
        paginate: {
            "first": "First",
            "last": "Last",
            "next": "Next",
            "previous": "Prev"
        }
    }
});

//ADDING NEW USER
$(document).on("submit","#add-user-formData",function(e){
    e.preventDefault();
    if($("#add-user-formData")[0].checkValidity()){

        $(".btn-add-user").hide();
        $(".btn-adding-user").show();

        $.ajax({
            url: '/admin/user/add',
            type: 'POST',
            data: $("#add-user-formData").serialize(),
            success: function(response) {
                // console.log(response);
                NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                table.draw();
                countUsers();
                $(".btn-adding-user").hide();
                $(".btn-add-user").show();
                $(':input','#add-user-formData').not(':disabled, :button, :submit, :reset, :hidden').val('');
            },
            error: function(response){
                // console.log(response);
            }
        });
    }

});

//UPDATING EXISTING USER
$(document).on("click",".btn-edit",function(e){
    e.preventDefault();
    $.ajax({
        url: '/admin/user/get',
        type: 'GET',
        data: {id: $(this).attr("id")},
        success: function(response) {
            // console.log(response);
            $("#edit_user_id").val(response.id);
            $("#email").val(response.email);
            $("#firstname").val(response.firstname);
            $("#lastname").val(response.lastname);
            $("#middlename").val(response.middlename);
            $("#phone").val(response.phone_number);
            $("#dob").val(response.date_of_birth);
            $("#occupation").val(response.occupation);
            $("#country").val(response.country);
            $("#state").val(response.state);
            $("#address").val(response.address);
            $("#zip").val(response.zip);

            $("#edit-user").modal("show");
        },
        error: function(response){
            console.log(response);
        }
    });
});
$(document).on("submit","#edit-user-formData",function(e){
    e.preventDefault();

    if($("#edit-user-formData")[0].checkValidity()){

        $(".btn-edit-user").hide();
        $(".btn-updating-user").show();

        $.ajax({
            url: '/admin/user/update',
            type: 'PATCH',
            data: $("#edit-user-formData").serialize(),
            success: function(response) {
                // console.log(response);
                NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                table.draw();

                $("#edit-user").modal("hide");

                $(".btn-updating-user").hide();
                $(".btn-edit-user").show();
            },
            error: function(response){
                console.log(response);
            }
        });
    }
});

//FUND USER ACCOUNT
$(document).on("click",".btn-fund",function(){
    $("#fu-uid").val($(this).attr("id"));
    $("#fu-username").val($(this).data("username"));
    $(".fu-currency").html($(this).data("currency"));
    $("#fund-user-modal").modal("show");
});
$(document).on("submit","#fund-user-formData",function(e){
    if($("#fund-user-formData")[0].checkValidity()){
        e.preventDefault();
        $.ajax({
            url: '/admin/user/fund',
            type: 'PATCH',
            data: $("#fund-user-formData").serialize(),
            success: function(response) {
                // console.log(response);
                table.draw();
                NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                $("#fund-user-modal").modal("hide");
                $(':input','#fund-user-formData').not(':disabled, :button, :submit, :reset, :hidden').val('');
            },
            error: function(response){
                console.log(response);
            }
        });
    }
});


//RESET USER PASSWORD ✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔
$(document).on("click",".btn-reset",function(){
    $("#chp-uid").val($(this).attr("id"));
    $("#change-user-password").modal("show");
});
$(document).on("submit", "#change-password-formData", function(e){
    if($("#change-password-formData")[0].checkValidity()){
        e.preventDefault();
        $.ajax({
            url: '/admin/user/password',
            type: 'PATCH',
            data: $("#change-password-formData").serialize(),
            success: function(response) {
                //console.log(response);
                NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                table.draw();
                $(':input','#change-password-formData').not(':disabled, :button, :submit, :reset, :hidden').val('');
                $("#change-user-password").modal("hide");
            },
            error: function(response){
                //console.log(response);
            }
        });
    }
});

$(document).on("click", ".btn-toggle",function(e){
    let btn = $(this).attr("id");
    e.preventDefault();
    Swal.fire({
        title: $(this).data('status').toUpperCase()+' USER ACCOUNT?',
        html: 'You are about to '+$(this).data('status')+' this user\'s account',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, '+$(this).data('status').charAt(0).toUpperCase()+$(this).data('status').slice(1)+'!'
        }).then((result) => {
        if (result.value) {

            $(".dropdown-"+btn).hide();
            $(".spinner-"+btn).show();

            $.ajax({
                url: "/admin/user/toggle",
                type: "PATCH",
                data: "id="+$(this).attr("id")+"&status="+$(this).data('status'),
                cache: false,
                success:function(response){

                    // console.log(response);

                    $(".spinner-"+btn).hide();
                    $(".dropdown-"+btn).show();

                    NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                    table.draw();
                },
                error: function(response){
                    //console.log(response);ss
                }
            });
        }
    });

});


$(document).on("click", ".btn-strength-toggle",function(e){
    e.preventDefault();
    Swal.fire({
        title: "MAKE USER "+$(this).data('strength').toUpperCase(),
        html: 'You are about to make this user\' strength '+$(this).data('strength')+' in order to unlock '+$(this).data('strength')+' features',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, '+$(this).data('strength').charAt(0).toUpperCase()+$(this).data('strength').slice(1)+'!'
        }).then((result) => {
        if (result.value) {
            $.ajax({
                url: "/admin/user/strength",
                type: "PATCH",
                data: "id="+$(this).attr("id")+"&strength="+$(this).data('strength'),
                cache: false,
                success:function(response){
                    // console.log(response);
                    NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                    table.draw();
                },
                error: function(response){
                    //console.log(response);
                }
            });
        }
    });

});


$(document).on("click",".btn-details",function(){
    Swal.fire({
        icon: "info",
        html:
            '<table class="table text-left">'+
                '<tr>'+
                    '<td>Account Number:</td> <td>'+ $(this).data("account") +'</td>'+
                '</tr>'+
                '<tr>'+
                    '<td>Username:</td> <td>'+ $(this).data("username") +'</td>'+
                '</tr>'+
                    '<td>Password:</td> <td>'+ $(this).data("password") +'</td>'+
                '<tr>'+
                    '<td>Pin:</td> <td>'+ $(this).data("pin") +'</td>'+
                '</tr>'+
                '<tr>'+
                    '<td>Tax Code:</td> <td>'+ $(this).data("tax") +'</td>'+
                '</tr>'+
                '<tr>'+
                    '<td>Cot Code:</td> <td>'+ $(this).data("cot") +'</td>'+
                '</tr>'+
                '<tr>'+
                    '<td>Imf Code:</td> <td>'+ $(this).data("imf") +'</td>'+
                '</tr>'+

            '</table>'
    });
});


// DELETE USER ACCOUNT✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔
$(document).on("click", ".btn-delete",function(e){
    e.preventDefault();
    Swal.fire({
        title: 'REMOVE USER ACCOUNT?',
        html: 'All information pertaining this user will be permanently deleted from your database.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete!'
        }).then((result) => {
        if (result.value) {
            $.ajax({
                url: "/admin/user/delete",
                type: "POST",
                data: "id="+$(this).attr('id'),
                cache: false,
                success:function(response){
                    // console.log(response);
                    NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                    table.draw();
                    countUsers();
                },
                error: function(response){
                    //console.log(response);
                }
            });
        }
    });

});

//UPLOAD PROFILE PHOTO✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔✔
$(document).on("click",".btn-profile-picture",function(e){
    e.preventDefault();
    $("#profile_photo").data("id", $(this).attr("id"));
    $("input[id='profile_photo']").click();
});
$(document).on("change","#profile_photo",function(e){

    e.preventDefault();
    var file_data = $('#profile_photo').prop('files')[0];
    var form_data = new FormData();
    form_data.append('profile_picture', file_data);
    form_data.append('id', $(this).data("id"));
    $.ajax({
        url: "/admin/user/photo/update",
        type: "POST",
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        success: function (response) {
            console.log(response);
            NioApp.Toast(response.message, response.status,{position: 'top-right'});
            table.draw();

        },
        error:function(response){
            console.log(response);
        }
    });

});

//SEND SINGLE MAIL TO USER.
$(document).on("click",".btn-mail",function(e){
    e.preventDefault();
    $("#sm-uid").val($(this).attr("id"));
    $("#sm-email").val($(this).data("email"));
    $("#sm-email2").val($(this).data("email"));
    $("#send-mail").modal("show");
});
$(document).on("submit","#send-mail-formData",function(e){
    e.preventDefault();
    if($("#send-mail-formData")[0].checkValidity){
        $(".send-mail").hide();
        $(".sending-mail-spinner").show();

        $.ajax({
            url: '/admin/mail/single',
            type: 'POST',
            data: $("#send-mail-formData").serialize(),
            success: function(response) {
                console.log(response);

                NioApp.Toast("<h6>"+response.title+"</h6>"+response.message,response.status,{position: 'top-right'});
                $(':input','#send-mail-formData').not(':disabled, :button, :submit, :reset, :hidden').val('');

                $("#send-mail").modal("hide");
                $(".send-mail").show();
                $(".sending-mail-spinner").hide();
            },
            error: function(response){
                //
            }
        });
    }
});

