$(".modalCompanySelect").change(async(e)=>{
    if(e.target.value&&e.target.value!=''){
        $(".modalDivisionSelect").removeAttr('disabled');
        var getToken = await fetch(`/session/key?s=jwt`);
        if(getToken.ok){
            var token = await getToken.text();
            var res = await fetch(`/api/divisions${(e.target.value == 'All')?'':`?filters[companies][id][$in]=${e.target.value}`}`,{
                headers:{
                    "Authorization" : "Bearer "+token,
                }
            });
            if(res.ok){
                var obj = await res.json();
                $(".modalDivisionSelect").empty();
                $(".modalDivisionSelect").append(($("#formCreateAdmin").length>0)?'<option value="All">Semua</option>':'<option  value="">Pilih divisi dari list</option>');
                obj.data.forEach((i)=>{
                    $(".modalDivisionSelect").append(`<option  value="${i.id}">${i.attributes.Name}</option>`);
                });
            }
        }
        else{
            showAlert('error','Gagal menarik data divisi. Harap login ulang!');
        }
    }
    else {
        $(".modalDivisionSelect").attr('disabled','disabled');
    }
});

$('#modal-reset-password').on('shown.bs.modal',async function () {
    var getToken = await fetch(`/session/key?s=jwt`);
        if(getToken.ok){
            var res = await fetch("/api/users?populate=*",{
                headers:{
                    Authorization:"Bearer "+await getToken.text(),
                }
            })
            if(res.ok){
                var users= await res.json();
                $(".modalUserSelect").empty();
                $(".modalUserSelect").append(`<option value="">Pilih User</option>`);
                users.forEach(i=>{
                    $(".modalUserSelect").append(`<option value="${i.id}">${i.username}</option>`);
                });
            }
            else{
                showAlert('error',"Terjadi kesalahan, harap login kembali atau hubungi admin!");
            }
        }
        else{
            showAlert('error',"Terjadi kesalahan, harap login kembali atau hubungi admin!");
        }

});

$('#modal-new-user').on('shown.bs.modal',async function () {
    var user = $("#modal-new-user").attr('user');
    if(user){
        $("#modal-new-user").find("button[type=submit]").text('Save');

        $("#modal-new-user").find("input[name=password]").parent().parent().hide();
        var getToken = await fetch(`/session/key?s=jwt`);
        if(getToken.ok){
            var res = await fetch("/api/users/"+user,{
                headers:{
                    Authorization:"Bearer "+await getToken.text(),
                }
            })
            if(res.ok){
                var user= await res.json();
                Object.keys(user).forEach(i=>{
                    if($(`input[name=${i}]`).length>0){
                        $(`input[name=${i}]`).val(user[i]);
                    }
                    if(i == 'company' && user[i]){
                        $(".modalCompanySelect").val(`${user[i].id}`);
                        $(".modalCompanySelect").trigger('change');
                    }
                    if(i == 'division'&& user[i]){
                        setTimeout(function(){ $(".modalDivisionSelect").val(`${user[i].id}`); }, 500);
                    }
                });
            }
            else{
                showAlert('error',"Terjadi kesalahan, harap login kembali atau hubungi admin!");
            }
        }
        else{
            showAlert('error',"Terjadi kesalahan, harap login kembali atau hubungi admin!");
        }
    }
});

$('#modal-new-user').on('hide.bs.modal',async function () {
    $("#modal-new-user").removeAttr('user');
    $(`#modal-new-user input`).val('');
    $('#modal-new-user select').val('');
    $("#modal-new-user").find("input[name=password]").parent().parent().show();
    $("#modal-new-user").find("button[type=submit]").text('Buat');
});

$("#formReset").submit(async(event)=>{
    event.preventDefault();
    if($(event.target).serializeArray().filter((item)=>item.value=='').length>0){
        showAlert('error',"Cek kembali data yang belum diisi!");
    }else{
        loading(10,true);
        var getToken = await fetch(`/session/key?s=jwt`);
        if(getToken.ok){
            var data = $(event.target).serializeArray();
            var res = await fetch(`/api/users/${data.filter(i=>i.name=='user')[0].value}`,{
                method:"PUT",
                headers:{
                    Authorization:"Bearer "+await getToken.text(),
                    'Content-Type': 'application/json',
                },
                body:JSON.stringify({
                    "password":data.filter(i=>i.name=='password')[0].value
                })
            });
            loading(100,true);
            if(res.ok){
                loading(0,false);
                showAlert('success',"Password sudah di reset!");
            }
            else{
                loading(0,false);
                try{
                    var obj = await res.json();
                    showAlert('error',obj["error"]["message"]);
                }catch(e){
                    showAlert('error',"Tidak dapat menghapus materi. Terjadi kesalahan!");
                }
            }
            console.log(res.ok);
        }
        else{
            loading(0,false);
            showAlert('error','Terjadi kesalahan. Harap login kembali!');
        }
    }
});

$("#formCreateUser").submit(async(event)=>{
    event.preventDefault();
    var data = $(event.target).serializeArray();
    if($("#modal-new-user").attr('user')){
        data = data.filter(i=>i.name!='password');
    }
    if(data.filter((item)=>item.value=='').length>0){
        showAlert('error',"Cek kembali data yang belum diisi!");
    }
    else {
        loading(10,true);
        var getToken = await fetch(`/session/key?s=jwt`);
        if(getToken.ok){
            const formData = new FormData();
            data.forEach(element => {
                try{
                    var  obj = element;
                    if(obj.name == 'username') {
                        var user_=obj.value;
                        user_ = (user_)?user_.replaceAll(" ",'_'):user_;
                        formData.append('email',user_ + '@thamrin.co.id');
                    }
                    if(obj.value[0]=='{'){
                        formData.append(obj.name, JSON.parse(obj.value));
                    }else{
                        formData.append(obj.name, obj.value);
                    }
                }
                catch(e){
                    // obj[element.name] = element.value;
                    formData.append(obj.name, obj.value);
                }
            });
            formData.append('role', 3);
            const request = new XMLHttpRequest();

            request.onreadystatechange=async function()
            {
                if(request.readyState==4){
                    loading(0,false);
                    console.log('status',request.status);
                    if(request.status<300){
                        showAlert('success','User Berhasil dibuat!');
                    }
                    else{
                        try{
                            var message = await JSON.parse(this.responseText);
                            showAlert('error',message.error.message);

                        }catch(e){
                            showAlert('error','Terjadi kesalahan! Harap coba login kembali / hubungi admin!');
                        }
                    }
                }
            }
            if($("#modal-new-user").attr('user')){
                request.open('PUT', "/api/users/"+$("#modal-new-user").attr('user'));
            }
            else request.open('POST', "/api/users");
            request.setRequestHeader("Authorization", "Bearer "+await getToken.text());
            request.send(formData);
        }
        else{
            loading(0,false);
            showAlert('error','Terjadi kesalahan. Harap login kembali!');
        }
    }
});

$('input[type=file]').not('[multiple]').change(function(e){
    if(e.target.files.length>0)$('label.custom-file-label[for='+e.target.id+']').text(e.target.files[0].name);
});

function clearAlert(){
    $("#alertBox").html('');
}

function showAlert(type,text){
    $("#alertBox").html(
        `
        <div class="alert ${(type =='error')?'alert-danger':'alert-success'} alert-dismissible fade show" role="alert">
            <span class="alert-icon">${(type =='error')?'<i class="ni ni-bulb-61"></i>':'<i class="ni ni-like-2"></i>'}</span>
            <span class="alert-text">${text}</span>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        `
    );
}

function loading(percent,show){
    if(show){
        $("#loadingBar").removeClass('hide');
        $("#loadingBar div[role=progressbar]").attr("aria-valuenow",percent);
        $("#loadingBar div[role=progressbar]").css("width",`${percent}%`);
    }
    else{
        $("#loadingBar").addClass('hide');
    }
}

var rowPage = 9;

async function paginationParticipants(pageSize,page,id,token){
    var res = await fetch(`/api/participants?filters[material][id][$eq]=${id}&pagination[page]=${page}&pagination[pageSize]=${pageSize}`,{
        headers: {
            'Authorization': `Bearer ${token}`
        },
    });
    if(res.ok){
        var obj = await res.json();
        $("#participantsTable tbody").empty();
        $("#participantPagination").empty();
        $("#participantPagination").append(`
            <li class="page-item ${obj.meta.pagination.page==1?'disabled':''}">
                <a value="${obj.meta.pagination.page-1}" class="page-link" href="#" tabindex="-1">
                <i class="fas fa-angle-left"></i>
                <span class="sr-only">Previous</span>
                </a>
            </li>
        `);
        for(var i =1; i <= obj.meta.pagination.pageCount;i++){
            $("#participantPagination").append(`
                <li class="page-item ${obj.meta.pagination.page==i?"active":''}"><a value="${i}" class="page-link" href="#">${i}</a></li>
            `);
        }
        $("#participantPagination").append(`
            <li class="page-item ${obj.meta.pagination.page==obj.meta.pagination.pageCount?'disabled':''}">
                <a value="${obj.meta.pagination.page+1}" class="page-link" href="#">
                <i class="fas fa-angle-right"></i>
                <span class="sr-only">Next</span>
                </a>
            </li>
        `);
        obj.data.forEach((i,indx)=>{
            $("#participantsTable tbody").append(`
            <tr>
            <th scope="row">${((obj.meta.pagination.page-1)*pageSize)+indx+1}</th>
            <td>${i.attributes.Name}</td>
            <td>${i.attributes.Company}</td>
            <td>${i.attributes.Division}</td>
            <td>${i.attributes.Email}</td>
            </tr>
            `);
        });

        //set callback pagination
        $(".page-link").click(async(e)=>{
            e.preventDefault();
            paginationParticipants(pageSize,$(e.target.closest('a')).attr('value'),id,token);
        });
    }
    else{
        showAlert('error','Gagal menarik data divisi. Harap login ulang!');
    }
}

$(".openParticipants").click(async(e)=>{
    e.preventDefault();
    var id = $(e.target.closest('a')).attr('value');
    $("#selMaterial").val(id);
    if(id){
        var getToken = await fetch(`/session/key?s=jwt`);
        if(getToken.ok){
            paginationParticipants(rowPage,1,id,await getToken.text());
        }
        else{
            showAlert('error','Gagal menarik data divisi. Harap login ulang!');
        }
    }
    else{
        showAlert("error","Terjadi kesalahan saat menarik data!");
    }
    $('#modal-participants').modal('show');
});
