@extends('template.master')

@section('content')
    @if ($canCreate)
        <button class="mb-4 btn btn-primary add">Tambah Users</button>
    @endif
    <nav>
        <div class="nav nav-tabs" id="nav-tab" role="tablist">
            <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button"
                role="tab" aria-controls="nav-home" aria-selected="true">User Aktif</button>
            <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button"
                role="tab" aria-controls="nav-profile" aria-selected="false">User Hapus</button>

        </div>
    </nav>
    <div class="tab-content" id="nav-tabContent">
        <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
            <div class="card">
                <div class="card-body">
                    <table id="activeTable" class="table table-striped data-table">
                        <thead>
                            <tr>
                                <th id="no">No</th>
                                <th>Nama</th>
                                <th>Tgl Lahir</th>
                                <th>NIK</th>
                                <th>NO HP</th>
                                <th>Email</th>
                                <th>Username</th>
                                <th>Sites</th>
                                <th>Role</th>
                                <th width="105px">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
            <div class="card">
                <div class="card-body">
                    <table id="trashTable" class="table table-striped data-table">
                        <thead>
                            <tr>
                                <th id="no">No</th>
                                <th>Nama</th>
                                <th>Tgl Lahir</th>
                                <th>NIK</th>
                                <th>NO HP</th>
                                <th>Email</th>
                                <th>Username</th>
                                <th>Sites</th>
                                <th>Role</th>
                                <th width="105px">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>



    @include('master-data.users.modal')
@endsection

@push('extraJS')
    <script type="text/javascript">
        $(function () {
            var table = $('#activeTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('users.index') }}",
                    data: function (d) {
                        d.option = "active"
                    },
                    error: function (d) {
                        console.log(d);
                    }
                },
                columnDefs: [{
                    width: "50px",
                    targets: 0
                } // 0 adalah index kolom 'id'
                ],
                columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex',
                    className: 'text-center',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'name',
                    name: 'name'
                },
                {
                    data: 'tgl_lahir',
                    name: 'tgl_lahir',
                    render: function (data, type, row) {
                        if (!data) return '-';
                        const date = new Date(data);
                        const day = String(date.getDate()).padStart(2, '0');
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const year = date.getFullYear();
                        return `${day}-${month}-${year}`;
                    }
                },
                {
                    data: 'nik',
                    name: 'nik',
                    render: function (data) {
                        return data ? data : '-';
                    }
                },
                {
                    data: 'no_hp',
                    name: 'no_hp',
                    render: function (data) {
                        return data ? data : '-';
                    }
                },
                {
                    data: 'email',
                    name: 'email'
                },
                {
                    data: 'username',
                    name: 'username'
                },
                {
                    data: 'sites',
                    name: 'sites'
                },
                {
                    data: 'role',
                    name: 'role'
                },
                // { data: 'content', name: 'content' },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
                ]
            });
            var table2 = $('#trashTable').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('users.index') }}",
                    error: function (d) {
                        console.log(d);
                    },
                    data: function (d) {
                        d.option = "trash"
                    }
                },
                columnDefs: [{
                    width: "50px",
                    targets: 0
                } // 0 adalah index kolom 'id'
                ],
                columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex',
                    className: 'text-center',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'name',
                    name: 'name'
                },
                {
                    data: 'tgl_lahir',
                    name: 'tgl_lahir',
                    render: function (data, type, row) {
                        if (!data) return '-';
                        const date = new Date(data);
                        const day = String(date.getDate()).padStart(2, '0');
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const year = date.getFullYear();
                        return `${day}-${month}-${year}`;
                    }
                },
                {
                    data: 'nik',
                    name: 'nik',
                    render: function (data) {
                        return data ? data : '-';
                    }
                },
                {
                    data: 'no_hp',
                    name: 'no_hp',
                    render: function (data) {
                        return data ? data : '-';
                    }
                },
                {
                    data: 'email',
                    name: 'email'
                },
                {
                    data: 'username',
                    name: 'username'
                },
                {
                    data: 'sites',
                    name: 'sites'
                },
                {
                    data: 'role',
                    name: 'role'
                },
                // { data: 'content', name: 'content' },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
                ]
            });


        });

        $(document).on("click", ".add", function () {
            $(".invalid-feedback").text("")
            $("#addModal").modal("show");

        });
        $(document).on("click", ".edit", function () {
            $(".invalid-feedback").text("")
            var id = $(this).data('id');
            var name = $(this).data('name');
            var tgl_lahir = $(this).data('tgl_lahir');
            var nik = $(this).data('nik');
            var no_hp = $(this).data('no_hp');
            var email = $(this).data('email');
            var username = $(this).data('username');
            var roles = $(this).data('roles');
            var location = $(this).data('location');

            // Ubah ini ke URL update sesuai route Anda
            var updateUrl = `{{ route('users.update', ":id") }}`.replace(":id", id);
            $("#editModal form").attr("action", updateUrl);
            $("#name_edit").val(name);
            $("#tgl_lahir_edit").val(tgl_lahir);
            $("#nik_edit").val(nik);
            $("#no_hp_edit").val(no_hp);
            $("#email_edit").val(email);
            $("#username_edit").val(username);
            $("#roles_edit").val(roles).trigger('change'); // trigger agar select2 update
            $("#location_edit").val(location).trigger('change'); // trigger agar select2 update
            $("#editModal").modal("show");
        });


        $(document).on("click", ".delete", function () {
            var id = $(this).data("id");
            var option = $(this).data("option");

            let textConfirm =
                option == "restore" ?
                    "Data akan dipulihkan." :
                    option == "delete" ?
                        "Data akan dihapus sementara (bisa dipulihkan kembali)." :
                        "Data akan dihapus secara permanen dan tidak bisa dikembalikan!";

            let confirmBtnText =
                option == "restore" ?
                    "Ya, pulihkan!" :
                    option == "force-delete" ?
                        "Ya, hapus permanen!" :
                        "Ya, hapus!";

            let confirmBtnColor =
                option == "restore" ?
                    "#ffae1f" :
                    option == "force-delete" ?
                        "#000"
                        :
                        "#d33";
            const url = `{{ route('users.destroy', ":id") }}`.replace(":id", id);

            Swal.fire({
                title: 'Apakah kamu yakin?',
                text: textConfirm,
                icon: 'warning',
                showCancelButton: true,
                cancelButtonColor: '#3085d6',
                confirmButtonColor: confirmBtnColor,
                confirmButtonText: confirmBtnText,
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: url + "?option=" + option,
                        type: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function (res) {
                            Swal.fire({
                                title: option == "restore" ?
                                    "Dipulihkan!" :
                                    option == "force-delete" ?
                                        "Dihapus Permanen!" :
                                        "Terhapus!",
                                text: res.message,
                                icon: 'success',
                                confirmButtonColor: '#3085d6'
                            });

                            $('.data-table').DataTable().ajax.reload();
                        },
                        error: function (xhr) {
                            console.log(xhr);
                            Swal.fire('Gagal!', 'Terjadi kesalahan saat memproses data.',
                                'error');
                        }
                    });
                }
            });
        });
    </script>
@endpush
