@push('script')
    <script>
        $(document).ready(function () {

            // sessionStorage.clear();

            function load_admin(params = []) {
                $("table.table").DataTable().destroy()
                $("table.table").DataTable({
                    "deferRender": true,
                    "responsive": true,
                    'serverSide': true,
                    'processing': true,
                    "ordering": false,
                    "ajax": {
                        "url": "{{ route('api.admin.index') }}",
                        "type": "GET",
                        "data": {
                            "sort": "ASC"
                        },
                        "headers": {
                            "Authorization" : getAuthorization()
                        },
                        "dataSrc": "data"
                    },
                    "columns": [
                        {
                            data: null,
                            render: function (data, type, row, meta) {
                                return meta.row + meta.settings._iDisplayStart + 1 + '.';
                            }
                        },
                        {
                            data: 'name'
                        },
                        {
                            data: 'username'
                        },
                        {
                            data: 'email'
                        },
                        {
                            data: null,
                            render: res => {
                                let btn_edit = ''
                                let btn_delete = ''

                                btn_edit = `<a class="btn btn-sm btn-white border-dark mb-1 btn-update-admin" data-id="${res.id}" data-name="${res.name}" data-email="${res.email}" href="javascript:void(0);"  data-bs-toggle="modal" data-bs-target="#crudModal">
                                                <i class="bx bx-edit-alt me-1"></i> Edit
                                            </a>`


                                btn_delete = `<a class="btn btn-sm btn-white border-dark mb-1 btn-delete-admin" data-id="${res.id}" data-name="${res.name}" href="javascript:void(0);">
                                                <i class="bx bx-trash me-1"></i> Delete
                                            </a>`



                                 if ("{{$user->id}}" != res.id) {
                                    btn_edit = ''
                                    btn_delete = ''
                                }

                                return `
                                    ${btn_edit} <br>
                                    ${btn_delete}
                                `;
                            }
                        }
                    ],
                    lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]]
                });
            }

            load_admin();

            $(document).on('click', '.btn-add-admin', function () {
                $('.title-admin-modal').html('Tambah')
                $('.btn-confirm-add-admin').removeClass('d-none')
                $('.btn-confirm-update-admin').addClass('d-none')
                $('#crudModal .admin-name').html('')

                $('#crudModal #name').val("")
                $('#crudModal #email').val("")
                $('#crudModal #email').attr('disabled', false)
                $('#crudModal #password').val("")
                $('#crudModal #password_confirmation').val("")

                $('#crudModal .required-input').removeClass("d-none")

                $('#crudModal #name').val('')
            })

            $(document).on('click', '.btn-confirm-add-admin', function () {
                data = {
                    name: $("input#name").val(),
                    email: $("input#email").val(),
                    password: $("input#password").val(),
                    password_confirmation: $("input#password_confirmation").val()
                }

                callApi("POST", "{{ route('api.admin.store') }}", data, function (req) {
                    pesan = req.message;
                    if (req.error == true) {
                        Swal.fire(
                        'Gagal ditambahkan!',
                        pesan,
                        'error'
                        )
                        $("#crudModal .btn-close").trigger('click')
                    }else{
                        Swal.fire(
                        'Ditambahkan!',
                        pesan,
                        'success'
                        )
                        $("#crudModal .btn-close").trigger('click')
                        load_admin();
                    }
                })
            })

            $(document).on('click', ".btn-update-admin", function () {
                $('.title-admin-modal').html('Edit')
                $('.btn-confirm-update-admin').removeClass('d-none')
                $('.btn-confirm-add-admin').addClass('d-none')
                $('#crudModal .admin-name').html($(this).attr('data-name'))

                $('#crudModal #name').val($(this).attr('data-name'))
                $('#crudModal #email').val($(this).attr('data-email'))
                $('#crudModal #email').attr('disabled', true)
                $('#crudModal #password').val("")
                $('#crudModal #password_confirmation').val("")

                $('#crudModal .required-input').addClass("d-none")

                $('.btn-confirm-update-admin').attr('data-id', $(this).attr('data-id'))
            })

            $(document).on('click', '.btn-confirm-update-admin', function () {
                data = {
                    name: $("input#name").val(),
                    password: $("input#password").val(),
                    password_confirmation: $("input#password_confirmation").val()
                }

                let id = $(this).attr('data-id');

                let url = "{{ route('api.admin.update', ':id') }}";
                url = url.replace(':id', id);

                callApi("PUT", url, data, function (req) {
                    pesan = req.message;
                    if (req.error) {
                        Swal.fire(
                        'Gagal diupdate!',
                        pesan,
                        'error'
                        )
                        $("#crudModal .btn-close").trigger('click')
                    }else{
                        Swal.fire(
                        'Diupdate!',
                        pesan,
                        'success'
                        )
                        $("#crudModal .btn-close").trigger('click')
                        load_admin();
                    }
                })
            })

            $(document).on('click', ".btn-delete-admin", function () {
                let id = $(this).attr('data-id')
                let name = $(this).attr('data-name')

                Swal.fire({
                title: 'Apakah anda yakin?',
                text: `Anda ingin menghapus data ${name}!`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Ya, hapus!'
                }).then((result) => {
                if (result.isConfirmed) {
                    let url = "{{ route('api.admin.delete', ':id') }}";
                    url = url.replace(':id', id);
                    callApi("DELETE", url, [], function (req) {
                        pesan = req.message;
                        if (req.error == true) {
                            Swal.fire(
                            'Gagal Dihapus!',
                            pesan,
                            'error'
                            )
                        }else{
                            Swal.fire(
                            'Dihapus!',
                            pesan,
                            'success'
                            )
                            cookie.remove('mm_token')
                            window.location.href = "{{ route('login') }}"
                        }
                    })

                }
                })
            })

        })
    </script>
@endpush
