

// datatable
/* ------------------------------------------------------------------------------
*
*  # Basic datatables
*
*  Specific JS code additions for datatable_basic.html page
*
*  Version: 1.0
*  Latest update: Aug 1, 2015
*
* ---------------------------------------------------------------------------- */
// cryptoDecrypt(PHRASE, nim);
// console.log(nim)



// alert("asup bray");
const statusActive      = 10;
const statusInactive    = 30;

$("#userman").css({"background-color":"#09c"});   
loadUser();
function loadUser(){
    let isObject = {};
    isObject.param = iduser;
    // console.log(isObject)

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loaduser',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            $("tbody").empty();
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                // console.log(result.data);
                let data    = result.data;
                let counter = 1;

                for (i in data){
                    var row = "";
                    
                    
                        row     += `<tr>
                                        <td>`+counter+`</td>
                                        <td>`+data[i].name+`</td>
                                        <td>`+data[i].username+`</a></td>`;
                                        
                                        if(data[i].role == 10){
                                            row += `<td>Akademik</td>`;
                                        }else if(data[i].role == 20){
                                            row += `<td>Mahasiswa</td>`;
                                        }else if(data[i].role == 30){
                                            row += `<td>Dosen</td>`;
                                        }else if(data[i].role == 40){
                                            row += `<td>Perusahaan</td>`;
                                        }

                                        if(data[i].status == 30){
                                            row += `<td><span style="min-width: 70px" class="label label-danger">Blocked</span></td>`;
                                        } else{
                                            row += `<td><span style="min-width: 70px" class="label label-success">Active</span></td>`;
                                        }
                                        
                        row     +=      `<td class="text-center">
                                            <ul class="icons-list">
                                                <li class="dropdown">
                                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                                        <i class="icon-menu9"></i>
                                                    </a>
                        
                                                    <ul class="dropdown-menu dropdown-menu-right">
                                                        <li><a onclick="validatedelete(`+data[i].iduser+`)"><i class="icon-user-cancel"></i> Delete user</a></li>`;
                                                        if(data[i].status == 30){
                                                            row += `<li><a onclick="validatestatus(`+data[i].iduser+`,`+data[i].status+`)"><i class="  icon-user-check"></i> Activate user</a></li>`;
                                                        } else {
                                                            row += `<li><a onclick="validatestatus(`+data[i].iduser+`,`+data[i].status+`)"><i class="icon-user-block"></i> Deactivate user</a></li>`;
                                                        }
                                                        
                        row     +=                      `<li><a onclick="validateresetpassword('`+data[i].username+`')"><i class=" icon-user-lock"></i> Reset password user</a></li>
                                                    </ul>
                                                </li>
                                            </ul>
                                        </td>
                                    </tr>` ;
                        $("tbody").append(row);
                        counter++;
                    
                }
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
            
                // Basic datatable
                
            
            
                // Alternative pagination
                $('.datatable-pagination').DataTable({
                    pagingType: "simple",
                    language: {
                        paginate: {'next': 'Next &rarr;', 'previous': '&larr; Prev'}
                    }
                });
            
            
                // Datatable with saving state
                $('.datatable-save-state').DataTable({
                    stateSave: true
                });
            
            
                // Scrollable datatable
                $('.datatable-scroll-y').DataTable({
                    autoWidth: true,
                    scrollY: 300
                });
            
            
            
                // External table additions
                // ------------------------------
            
                // Enable Select2 select for the length option
                $('.dataTables_length select').select2({
                    minimumResultsForSearch: Infinity,
                    width: 'auto'
                });
                
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function validatedelete(id){
    event.preventDefault();
    swal({
        title: "Hapus data user",
        text: "once you remove this data, you wont be able to retrieve this file.",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Ya!",
        cancelButtonText: "Tidak!",
        cancelButtonColor: "#DD6B55",
        closeOnConfirm: false,
        closeOnCancel: false
      },
      function(isConfirm){
        if (isConfirm) {
            deleteuser(id);
                     // submitting the form when user press yes
        } else {
          swal("Cancelled", "", "error");
        }
    });
}

function validateresetpassword(id){
    event.preventDefault();
    swal({
        title: "Reset password user?",
        // text: "once you remove this data, you wont be able to retrieve this file.",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes!",
        cancelButtonText: "Cancel!",
        cancelButtonColor: "#DD6B55",
        closeOnConfirm: false,
        closeOnCancel: false
      },
      function(isConfirm){
        if (isConfirm) {
            // $("tbody").empty();
            resetpassword(id)
                     // submitting the form when user press yes
        } else {
          swal("Cancelled", "", "error");
        }
    });
}

function validatestatus(id,status){
    event.preventDefault();
    // console.log(id);
    // console.log(role);

    if(status == 30){
        swal({
            title: "Aktifkan user?",
            // text: "once you remove this data, you wont be able to retrieve this file.",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes!",
            cancelButtonText: "Cancel!",
            cancelButtonColor: "#DD6B55",
            closeOnConfirm: false,
            closeOnCancel: false
          },
          function(isConfirm){
            if (isConfirm) {
                // $("tbody").empty();
                changestatus(id, statusActive);
                         // submitting the form when user press yes
            } else {
              swal("Cancelled", "", "error");
            }
        });
    } else {
        swal({
            title: "Nonaktifkan user?",
            // text: "once you remove this data, you wont be able to retrieve this file.",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes!",
            cancelButtonText: "Cancel!",
            cancelButtonColor: "#DD6B55",
            closeOnConfirm: false,
            closeOnCancel: false
          },
          function(isConfirm){
            if (isConfirm) {
                changestatus(id, statusInactive);
            } else {
              swal("Cancelled", "", "error");
            }
        });
    }
}

function changestatus(id, status){
    var isObject = {};

    isObject.id      = id;
    isObject.status  = status;
    isObject.columns = "status";

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/changestatus',
        async: true,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            
            if(response.code == CODE_SUCCESS){
                if(status == statusActive){
                    swal({
                        title: "Alert",
                        text:  " Berhasil Aktivasi User :)",
                        confirmButtonColor: "#2196F3",
                        type: "success",
                        icon: "success"
                    }, function(){
                        // $("tbody").empty();
                        // loadUser();  
                        location.reload();      
                    });
                } else {
                    swal({
                        title: "Alert",
                        text:  " Berhasil Deaktivasi User :)",
                        confirmButtonColor: "#2196F3",
                        type: "success",
                        icon: "success"
                    }, function(){
                        // $("tbody").empty();
                        // loadUser();  
                        location.reload();      
                    });
                } 
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }    
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function resetpassword(username){
    var isObject = {};

    isObject.id      = username;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/resetpassworduser',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            
            if(response.code == CODE_SUCCESS){
                
                swal({
                    title: "Alert",
                    text:  " Berhasil Reset Password User :)",
                    confirmButtonColor: "#2196F3",
                    type: "success",
                    icon: "success"
                });
               
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }    
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function validateuname(){
    let isObject = {};
    isObject.param = iduser;
    var noinduk     = $("#username > input").val();
    console.log(noinduk)
    var exist   = false;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/loaduser',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            // $("tbody").empty();
            
            if(response.code == CODE_SUCCESS){
                let result  = cryptoDecrypt(PHRASE, response.data);
                console.log(result.data);
                let data    = result.data;
                
                for(i in data){
                    if(noinduk == data[i].username){
                        exist = true;
                    }
                }
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

    return exist;
}

function saveuser(){
    
    var isObject    = {};
    var nimpattern  = /^[0-9]{10}$/;
    var namapattern = /^[a-zA-Z ]{2,30}$/;
    var role = $("#userrole").val();

    isObject.role       = role;
    isObject.nama       = $("#name").val();
    isObject.username   = $("#username > input").val();
    isObject.fakultas   = $("#faculty").val();
    isObject.jurusan    = $("#jurusan").val();
    isObject.gender     = $('input[name="gender"]:checked').val();

    console.log(isObject);
    if(isObject.nama == ""){
        swal({
            // title: "Ops!",
            text:" Nama tidak boleh kosong. Silahkan coba kembali :)",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    } else if(!namapattern.test(isObject.nama)){
        swal({
            // title: "Ops!",
            text:" Format nama salah!",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    }

    if(isObject.username == ""){
        swal({
            // title: "Ops!",
            text:" Nomor Induk tidak boleh kosong. Silahkan coba kembali :)",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    } else if(!nimpattern.test(isObject.username)){
        swal({
            // title: "Ops!",
            text:" Nomor induk harus terdiri dari 10 karakter:)",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    } else if(validateuname()){
        swal({
            title: "Alert",
            text:  "Nomor induk sudah terdaftar!",
            confirmButtonColor: "#2196F3",
            type: "error"
        });  
        return false
    }

    if(isObject.gender == ""){
        swal({
            // title: "Ops!",
            text:" Jenis Kelamin tidak boleh kosong. Silahkan coba kembali :)",
            confirmButtonColor: "#2196F3",
            type: "warning"
        });
        return false;
    } 

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/saveuser',
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function (response) {
            $('#modal-add').modal("hide");
            if(response.code == CODE_SUCCESS){

                // document.getElementById("form-data").reset();
                var object2 = isObject.nimmhs;
                swal({
                    title: "Alert",
                    text: "User telah ditambahkan ",
                    confirmButtonColor: "#66BB6A",
                    type: "success"
                }, function(){ 
                    // $("tbody").empty();
                    // loadMahasiswa();
                    location.reload()
                });

            }else{
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            };

            loaderPage(false);
            
        },
        error: function () {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Alert",
                    text:  xhr.status+"-"+xhr.statusText+" Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });
}

function deleteuser(id){
    var isObject    = {}

    isObject.id = id;
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: baseURL + '/jsondata/deleteuser',
        async: false,
        data: {
            iparam	    : cryptoEncrypt(PHRASE, isObject),
        },
        success: function(response){
            // console.log(response.code)
            
            if(response.code == CODE_SUCCESS){
                swal({
                    title: "Alert",
                    text:  " User berhasil dihapus :)",
                    confirmButtonColor: "#2196F3",
                    type: "success",
                    icon: "success"
                }, function(){
                    $("tbody").empty();
                    loadUser();  
                    // location.reload();      
                });  
                
            } else {
                swal({
                    title: "Alert",
                    text:  response.info+ " Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });  
            }    
            
        },
        error: function(xhr) {
            loaderPage(false);
            if(xhr.status != 200){
                swal({
                    title: "Galat",
                    text:  xhr.status+"-"+xhr.statusText+"<br> Silahkan coba kembali :)",
                    confirmButtonColor: "#2196F3",
                    type: "error"
                });                        
            }
        }
    });

    // console.log(id)
}

$(document).ready(function(){
    $('.datatable-basic').DataTable({
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            "width": "10px", "targets": 0,
            "width": "10px", "targets": 5,
            
        }],
        dom: '<"datatable-header"fl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            searchPlaceholder: 'Type to filter...',
            lengthMenu: '<span>Show:</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });

    // Alternative pagination
    $('.datatable-pagination').DataTable({
        pagingType: "simple",
        language: {
            paginate: {'next': 'Next &rarr;', 'previous': '&larr; Prev'}
        }
    });


    // Datatable with saving state
    $('.datatable-save-state').DataTable({
        stateSave: true
    });


    // Scrollable datatable
    $('.datatable-scroll-y').DataTable({
        autoWidth: true,
        scrollY: 300
    });



    // External table additions
    // ------------------------------

    // Enable Select2 select for the length option
    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });

    $("#btn-add-add").on("click", function(){
        $('#modal-add').modal("show");
    })

    $("#submit-user").on("click", function(){
        saveuser();
        // validateuname();
    })

    
        
    $("#userrole").on("change", function(){
        var role = $("#userrole").val();
        console.log(role);     // $("#perusahaan").hide();
        
        if(role == 10){
            $("#username > label").html("Username");
            $("#username > input").attr("placeholder","Enter Username...");
            $("#fakultas").hide();
            $("#major").hide();
        }

        if(role == 20){
            $("#username > label").html("Nomor Induk Mahasiswa");
            $("#username > input").attr("placeholder","Enter Nomor Induk Mahasiswa...");
            $("#fakultas").show();
            $("#major").show();
        }

        if(role == 30){
            $("#username > label").html("Nomor Induk Dosen");
            $("#username > input").attr("placeholder","Enter Nomor Induk Dosen...");
            $("#fakultas").show();
            $("#major").show();
        }
    })
})

loadElementsMhs()
function loadElementsMhs(clicksc){
    loaderPage(true)
    let isObject     = {}; 
    isObject.ipoly   = 1;

    var dtpr = $('#mahasiswalist').DataTable({
        serverSide	: true,
        destroy		: true,
        bFilter		: true,
        responsive	: true,
        searching   : true,
        pagingType  : 'full',
        lengthMenu  : [[1, 25, 50, -1], [1, 25, 50, "All"]],
        pageLength  : 25,
        ajax		: {
            url: baseURL + '/jsondata/loaduserlist',
            type: 'POST',
            // async: false,
            data : function (d) {         
                return $.extend( {}, d, {
                    iparam	    : cryptoEncrypt(PHRASE, isObject),
                });
            },
            dataSrc: function(response) {
                
                if(response.code == CODE_SUCCESS){
                    response = cryptoDecrypt(PHRASE, response.data);
                    // console.log(response.data.data);
                    var data = response.data.data;
                    
                    console.log(data)
                    return data;
                }else{
                    return response;
                }
               
            }
        },	
        columns: [
            { 'data': 'iduser', 'sClass':'','sWidth':'10px'},
            { 'data': 'name', 'sClass':''},
            { 'data': 'username', 'sClass':''},
            { 'data': 'role', 'sClass':''},
            { 'data': 'status', 'sClass':'text-center'},
            { 'data': '', 'sClass':'text-center','sWidth':'10px'}
        ],
        buttons: {            
            buttons: [
                {
                    extend: 'colvis',
                    className: 'btn btn-default'
                },
            ]
        },
        processing: true,
        stateSave: false,
        autoWidth: false,
        dom: '<"datatable-header"fBl><"datatable-scroll-wrap"t><"datatable-footer"ip>',
        language: {
            search: '<span>Filter:</span> _INPUT_',
            lengthMenu: '<span>Show:</span> _MENU_',
            processing: "<div class='table-loading'><img src='../../img/loadingtwo.gif' /></div>",

            paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }
        },
        columnDefs: [
            {
                width: '20px',
                targets: 0,
                visible: true
            },
            {   


                render: function (data, type, row){
                    // var $rowData = '<img src="/distro/assets/images/placeholder.jpg" alt="" class="img-rounded img-preview showAtt" style="cursor: pointer;">';
                    var $rowData ='';
                    if(row.role == 10){
                        $rowData += `<td>Akademik</td>`;
                    }else if(row.role == 20){
                        $rowData += `<td>Mahasiswa</td>`;
                    }else if(row.role == 30){
                        $rowData += `<td>Dosen</td>`;
                    }else if(row.role == 40){
                        $rowData += `<td>Perusahaan</td>`;
                    }else{
                        $rowData += `<td>Else</td>`;
                    }

                    return $rowData;
                },
                visible: true,
                targets: 3,
            },  
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = ``;
                    if(row.status == 30){
                        $rowData += `<td><span style="min-width: 70px" class="label label-danger">Blocked</span></td>`;
                    } else if(row.status == 10){
                        $rowData += `<td><span style="min-width: 70px" class="label label-success">Active</span></td>`;
                    } else {
                        $rowData += `<td><span style="min-width: 70px" class="label label-warning">Not Active</span></td>`;
                    }
                    return $rowData;
                },
                visible: true,
                targets: 4,
            }, 
            {   
                render: function (data, type, row){
                    // console.log(row);
                    var $rowData = ``;
                    

                    $rowData     +=      `<td class="text-center">
                                            <ul class="icons-list">
                                                <li class="dropdown">
                                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                                                        <i class="icon-menu9"></i>
                                                    </a>
                        
                                                    <ul class="dropdown-menu dropdown-menu-right">
                                                        <li><a onclick="validatedelete(`+row.iduser+`)"><i class="icon-user-cancel"></i> Delete user</a></li>`;
                                                        if(row.status == 30){
                                                            $rowData += `<li><a onclick="validatestatus(`+row.iduser+`,`+row.status+`)"><i class="  icon-user-check"></i> Activate user</a></li>`;
                                                        } else {
                                                            $rowData += `<li><a onclick="validatestatus(`+row.iduser+`,`+row.status+`)"><i class="icon-user-block"></i> Deactivate user</a></li>`;
                                                        }
                                                        
                                                        $rowData     +=                      `<li><a onclick="validateresetpassword('`+row.username+`')"><i class=" icon-user-lock"></i> Reset password user</a></li>
                                                    </ul>
                                                </li>
                                            </ul>
                                        </td>
                                    </tr>` ;

                    
                        // $rowData = `<ul class="icons-list">
                        //                 <li class="dropdown">
                        //                     <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        //                         <i class="icon-menu9"></i>
                        //                     </a>

                        //                     <ul class="dropdown-menu dropdown-menu-right">
                                             
                                                
                        //                     </ul>
                        //                 </li>
                        //             </ul>`;
                    
                                                // <li class=""><a ><i class=" icon-file-eye2"></i> Lihat Mahasiswa</a></li>
                                                // <li class=""><a class=""><i class="icon-user-plus"></i> Edit Mahasiswa</a></li>                                               
                                                // <li><a ><i class="icon-user-cancel"></i> Delete Mahasiswa</a></li>
                    return $rowData;
                },
                visible: true,
                targets: 5,
                className: 'dt-center'
            }, 
        ],
        fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ 
            var index = iDisplayIndexFull + 1; 
            $('td:eq(0)', nRow).html('#'+index); 
            return  index;
        },
        drawCallback: function (settings) {
            // console.log(settings.json);
            
            var api  = this.api();
            var rows = api.rows({page:'current'}).nodes();
            var last = null;

            // console.log(rows)
            // Reverse last 3 dropdowns orientation
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');

            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            this.$('.showAtt').on('click', function(){

                var tr      = $(this).parents('tr')
                var aData   = dtpr.row( tr ).data();

                // loadAttachments(aData);

            });

            
        },
        fnInitComplete: function (oSettings, json) {
            var that = this;
            var td ;
            var tr ;

            this.$('td').click( function () {
                td = this;
            });
            this.$('tr').click( function () {
                tr = this;
            });

            

            $('#mahasiswalist input').bind('keyup', function (e) {
                return this.value;
            });

            setIFrameSize();

        }
    });

}