<?php $__env->startSection('content'); ?>
    <style>
        #datatable td,
        #datatable th {
            white-space: nowrap;
            vertical-align: middle;
        }

        @media (max-width: 768px) {
            .btn {
                padding: 0.25rem 0.5rem;
            }
        }
    </style>
    <div class="row  ">
        <div class="col-md-6">
            <h2>Data User</h2>
        </div>
        <div class="col-md-6 text-end">
            <a href="<?php echo e(route('user.create')); ?>" class="btn btn-primary">Tambah User</a>
        </div>
    </div>


    <div class="card shadow-sm border-0 rounded-4">
        <div class="card-body">

            <div class="row pb-3 align-items-center g-2">
                <!-- Kontrol Tampilkan Baris & Export -->
                <div class="col-12 col-md-auto d-flex gap-2">
                    <!-- Per page -->
                    <div class="dropdown">
                        <button class="btn btn-white btn-sm dropdown-toggle shadow-sm px-3" type="button"
                            data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-list-ol me-1 text-secondary"></i>
                            Tampilkan: <span class="baris fw-bold text-primary">10</span>
                        </button>
                        <ul class="dropdown-menu shadow border-0">
                            <li><button class="dropdown-item" onclick="loadPerPage(10)">10 Baris</button></li>
                            <li><button class="dropdown-item" onclick="loadPerPage(25)">25 Baris</button></li>
                            <li><button class="dropdown-item" onclick="loadPerPage(50)">50 Baris</button></li>
                            <li><button class="dropdown-item" onclick="loadPerPage(100)">100 Baris</button></li>
                        </ul>
                    </div>
                </div>

                <!-- Spasi Pemisah (Hanya muncul di Desktop) -->
                <div class="col d-none d-md-block"></div>

                <!-- Search Input -->
                <div class="col-12 col-md-4">
                    <div class="input-group input-group-sm shadow-sm">
                        <span class="input-group-text bg-white border-end-0 text-secondary">
                            <i class="bi bi-search"></i>
                        </span>
                        <input type="text" id="searchInput" name="search" class="form-control border-start-0 ps-0"
                            placeholder="Cari data di sini...">
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <!-- TABLE -->
                <div class="table-responsive">
                    <table id="datatable" class="table table-hover table-sm align-middle mb-0">

                        <thead class="table-light">
                            <tr>
                                <th>No</th>
                                <th>Nama</th>
                                <th>NRP (Username)</th>
                                <th>Role</th>
                                <th style="text-align: center">Aksi</th>
                            </tr>
                        </thead>

                        <tbody></tbody>
                    </table>
                </div>

                <!-- PAGINATION -->
                <nav class="mt-3">
                    <ul class="pagination pagination-sm justify-content-end" id="pagination"></ul>
                </nav>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const params = new URLSearchParams(window.location.search);
            let today = new Date();

            let page = parseInt(params.get('page')) || 1;
            let perPage = parseInt(params.get('perPage')) || 10;

            let search = params.get('search') || '';

            let typingTimer;
            const delay = 500;

            $("#searchInput").on("keyup", function() {
                clearTimeout(typingTimer);

                typingTimer = setTimeout(() => {
                    search = this.value;
                    page = 1;
                    loadReport();
                }, delay);
            });

            document.getElementById("searchInput").value = search;

            document.querySelector(".baris").innerText = perPage;

            function formatTanggalPendek(dateString) {
                if (!dateString) return '';

                const date = new Date(dateString.replace(' ', 'T'));

                return date.toLocaleDateString('id-ID', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric'
                });
            }

            window.loadPerPage = function(limit) {

                perPage = limit;
                page = 1;

                document.querySelector(".baris").innerText = limit;

                loadReport();
            };
            window.loadReport = function() {

                const newUrl = `?page=${page}&perPage=${perPage}&search=${search}`;
                window.history.replaceState({}, '', newUrl);

                const url =
                    `<?php echo e(route('user.getData')); ?>?page=${page}&perPage=${perPage}&search=${search}`;

                // loading state
                document.querySelector("#datatable tbody").innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center">Loading...</td>
                    </tr>
                `;

                fetch(url)
                    .then(response => response.json())
                    .then(res => {
                        let rows = '';
                        let no = (page - 1) * perPage + 1;
                        let paginationHtml = '';
                        let start = Math.max(1, res.current_page - 2);
                        let end = Math.min(res.last_page, res.current_page + 2);

                        for (let i = start; i <= end; i++) {
                            paginationHtml += `
                                <li class="page-item ${i === res.current_page ? 'active' : ''}">
                                    <button class="page-link" onclick="goPage(${i})">${i}</button>
                                </li>
                            `;
                        }

                        document.getElementById("pagination").innerHTML = paginationHtml;

                        if (res.data.length === 0) {
                            rows = `
                                <tr>
                                    <td colspan="7" class="text-center text-muted">
                                        Data tidak ditemukan
                                    </td>
                                </tr>
                            `;
                        } else {
                            res.data.forEach(item => {

                                let badgeRole = '';

                                if (item.role === 'administrator') {
                                    badgeRole = `
                                    <span class="badge bg-danger">
                                        Administrator
                                    </span>
                                `;
                                } else {
                                    badgeRole = `
                                    <span class="badge bg-info text-dark">
                                        User
                                    </span>
                                `;
                                }

                                rows += `
                                <tr>
                                    <td>${no++}</td> 
                                    <td>${item.name ?? '-'}</td>
                                    <td>${item.nrp ?? '-'}</td>

                                    <td>
                                        ${badgeRole}
                                    </td>

                                    <td class="text-center">

                                        <form action="/user/${item.id}" 
                                            method="POST"
                                            onsubmit="return confirm('Apakah Anda yakin ingin menghapus data ini?');">

                                            <input type="hidden" 
                                                name="_token" 
                                                value="<?php echo e(csrf_token()); ?>">

                                            <input type="hidden" 
                                                name="_method" 
                                                value="DELETE">

                                            <div class="d-flex flex-wrap gap-1 justify-content-center">

                                                <a href="/user/${item.id}/edit"
                                                    class="btn btn-sm btn-warning"
                                                    title="Edit">

                                                    <i class="bi bi-pencil"></i>

                                                    <span class="d-none d-md-inline ms-1">
                                                        Edit
                                                    </span>
                                                </a>

                                                <button type="submit"
                                                    class="btn btn-sm btn-danger"
                                                    title="Hapus">

                                                    <i class="bi bi-trash"></i>

                                                    <span class="d-none d-md-inline ms-1">
                                                        Hapus
                                                    </span>
                                                </button>

                                            </div>

                                        </form>

                                    </td>

                                </tr>
                            `;
                            });
                        }

                        document.querySelector("#datatable tbody").innerHTML = rows;
                    })
                    .catch(err => {
                        console.error("Error:", err);
                        document.querySelector("#datatable tbody").innerHTML = `
                            <tr>
                                <td colspan="7" class="text-center text-danger">
                                    Gagal memuat data
                                </td>
                            </tr>
                        `;
                    });

                const modalEl = document.getElementById('ModalFilter');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) modal.hide();
            };

            window.goPage = function(p) {
                page = p;
                loadReport();
            };

            loadReport();
        });
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\gl-asuh\resources\views/menu/user/index.blade.php ENDPATH**/ ?>