<!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="utf-8">
        <meta content="width=device-width, initial-scale=1.0" name="viewport">

        <title>J-Classify Tracer Study MIF</title>
        <meta content="" name="description">
        <meta content="" name="keywords">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <!-- Favicons -->
        <link href="{{ asset('assets/img/favicon.png') }}" rel="icon">
        <link href="{{ asset('assets/img/apple-touch-icon.png') }}" rel="apple-touch-icon">

        <!-- Google Fonts -->
        <link href="https://fonts.gstatic.com" rel="preconnect">
        <link
            href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i"
            rel="stylesheet">

        <!-- Tambahkan ini di bagian <head> atau sebelum penutup </body> -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


        <!-- Vendor CSS Files -->
        <link href="{{ asset('assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
        <link href="{{ asset('assets/vendor/bootstrap-icons/bootstrap-icons.css') }}" rel="stylesheet">
        <link href="{{ asset('assets/vendor/boxicons/css/boxicons.min.css') }}" rel="stylesheet">
        <link href="{{ asset('assets/vendor/quill/quill.snow.css') }}" rel="stylesheet">
        <link href="{{ asset('assets/vendor/quill/quill.bubble.css') }}" rel="stylesheet">
        <link href="{{ asset('assets/vendor/remixicon/remixicon.css') }}" rel="stylesheet">
        <link href="{{ asset('assets/vendor/simple-datatables/style.css') }}" rel="stylesheet">
        <script src="{{ asset('assets/vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>


        <!-- Template Main CSS File -->
        <link href="{{ asset('assets/css/style.css') }}" rel="stylesheet">
    </head>

    <body>

        <!-- ======= Header ======= -->
        @include('header')
        <!-- ======= Sidebar ======= -->
        @include('sidebar')

        <main id="main" class="main">
            <div class="pagetitle">
                <h1>List Pengguna</h1>
                <nav>
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.html">Home</a></li>
                        <li class="breadcrumb-item">user</li>
                    </ol>
                </nav>
            </div><!-- End Page Title -->

            <section class="section">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">Data User</h5>
                                <div class="mb-2">
                                    <input type="text" class="form-control" id="searchInput" placeholder="Cari User..."
                                        style="width: 400px;">
                                </div>
                                <div class="mb-1 d-flex align-items-center">
                                    <label class="me-2">Tampilkan:</label>
                                    <select id="entriesPerPage" class="form-select w-auto">
                                        <option value="20">20</option>
                                        <option value="50">50</option>
                                        <option value="all">Semua</option>
                                    </select>
                                </div>
                                <div class="d-flex justify-content-end align-items-center mb-3">
                                    <button type="button" class="btn btn-success" data-bs-toggle="modal"
                                        data-bs-target="#tambahUser">
                                        Tambah User
                                    </button>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-striped table-bordered" id="userTable">
                                        <thead>
                                            <tr>
                                                <th>No</th>
                                                <th>Nama</th>
                                                <th>Username</th>
                                                <th>Email</th>
                                                <th>password</th>
                                                <th>Role</th>
                                                <th>Foto</th>
                                                <th>Tanggal Dibuat</th>
                                                <th>Tanggal DiUpdate</th>
                                                <th colspan="2">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($user as $s)
                                                <tr>
                                                    <td>{{ $loop->iteration }}</td>
                                                    <td>{{ $s->name }}</td>
                                                    <td>{{ $s->username }}</td>
                                                    <td>{{ $s->email }}</td>
                                                    <td>
                                                        @php
                                                            try {
                                                                echo Crypt::decryptString($s->password);
                                                            } catch (\Exception $e) {
                                                                echo '<span class="text-danger">Error decrypting</span>';
                                                            }
                                                        @endphp
                                                    </td>

                                                <td>{{ $s->role->nama_role ?? 'Tidak ada role' }}</td>
                                                    <td>@if ($s->image)
                                                            <img src="{{ asset ($s->image) }}" alt="Foto Pengguna" width="50">
                                                        @else
                                                            <span class="text-muted">Tidak ada foto</span>
                                                        @endif
                                                    </td>
                                                    <td>{{ $s->created_at }}</td>
                                                    <td>{{ $s->updated_at }}</td>
                                                    <td>
                                                        <button type="button" class="btn btn-primary btn-sm"
                                                            data-bs-toggle="modal"
                                                            data-bs-target="#editUser{{ $s->id }}">
                                                            Edit
                                                        </button>
                                                        <td>
                                                        <!-- Tombol Hapus -->
                                                        <button type="button" class="btn btn-danger btn-sm"
                                                            onclick="confirmDelete({{ $s->id }})">Hapus</button>
                                                        </td>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </main><!-- End #main -->

        <!-- Modal Tambah-->
        <div class="modal fade" id="tambahUser" tabindex="-1" aria-labelledby="modaltambahuserLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTambahSiswaLabel">Tambah Data Siswa</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form action="{{ 'store' }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mb-3">
                                <label for="nama" class="form-label">Nama</label>
                                <input type="text" class="form-control" id="nama" name="nama" required>
                            </div>
                            <div class="mb-3">
                                <label for="username" class="form-label">Username</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                            </div>
                            <div class="mb-3">
                                <label for="email" class="form-label">Email</label>
                                <input type="text" class="form-control" id="email" name="email"
                                    accept="image/*" required>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label">Password</label>
                                <input type="text" class="form-control" id="password" name="password" required>
                            </div>
                            <!-- Kalau Mau Pake Inputtan Foto di Bawah ini -->


                            <div class="mb-3">
                                <label for="text" class="form-label">Role</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="">Pilih Role</option>
                                    @foreach ($roleuser as $r)
                                    <option value="{{$r->id_role}}">{{$r->nama_role}}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="image" class="form-label">Foto User</label>
                                <input type="file" class="form-control" id="image" name="image"
                                    accept="image/*">
                            </div>

                            <!-- contoh dari dani -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                        <button type="submit" class="btn btn-primary">Simpan Data</button>
                    </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Modal Edit -->
        @foreach ($user as $s)
            <div class="modal fade" id="editUser{{ $s->id }}" tabindex="-1"
                aria-labelledby="modalEditUserLabel{{ $s->id }}" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="modalEditUserLabel{{ $s->id }}">Edit Data User</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form action="{{ route('user.update', $s->id) }}" method="POST" enctype="multipart/form-data">
                                @csrf
                                @method('PUT')
                                <div class="mb-3">
                                    <label for="nama" class="form-label">Nama</label>
                                    <input type="text" class="form-control" id="nama" name="nama"
                                        value="{{ $s->name }}" required>
                                </div>
                                <div class="mb-3">
                                    <label for="username" class="form-label">Username</label>
                                    <input type="text" class="form-control" id="username" name="username"
                                        value="{{ $s->username }}" required>
                                </div>

                                <div class="mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="email" name="email"
                                        value="{{ $s->email }}" required>
                                </div>
                                <div class="mb-3">
                                    <label for="text" class="form-label">password</label>
                                    <input type="text" class="form-control" id="password" name="password"
                                        value="{{ Crypt::decryptString($s->password) }}" required>
                                </div>
                                <div class="mb-3">
                                    <label for="role" class="form-label">Role</label>
                                    <select class="form-select" id="role" name="role" required>
                                        <option value="">Pilih Role</option>
                                        @foreach ($roleuser as $r)
                                            <option value="{{ $r->id_role }}" {{ $s->id_roleuser == $r->id_role ? 'selected' : '' }}>
                                                {{ $r->nama_role }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>


                                <!-- contoh user edit-->
                                <div class="mb-3">
                                    <label for="image" class="form-label">Foto User (Opsional)</label>
                                    <input type="file" class="form-control" id="image" name="image"
                                        accept="image/*">
                                        @if ($s->image)
                                        <div class="mt-2">
                                            <img src="{{ asset($s->image) }}" alt="Foto Pengguna" width="100" height="100" class="rounded-circle">
                                        </div>
                                        @endif
                                </div>
                                <input type="hidden" name="status" value="Aktif">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                            <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                        </div>
                        </form>
                    </div>
                </div>
            </div>
        @endforeach


        <!-- ======= Footer ======= -->
        @include('footer')

        <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i
                class="bi bi-arrow-up-short"></i></a>

        <!-- Vendor JS Files -->
        <script src="{{ asset('assets/vendor/apexcharts/apexcharts.min.js') }}"></script>
        <script src="{{ asset('assets/vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
        <script src="{{ asset('assets/vendor/chart.js/chart.umd.js') }}"></script>
        <script src="{{ asset('assets/vendor/echarts/echarts.min.js') }}"></script>
        <script src="{{ asset('assets/vendor/quill/quill.js') }}"></script>
        <script src="{{ asset('assets/vendor/simple-datatables/simple-datatables.js') }}"></script>
        <script src="{{ asset('assets/vendor/tinymce/tinymce.min.js') }}"></script>
        <script src="{{ asset('assets/vendor/php-email-form/validate.js') }}"></script>
        <!-- Di akhir sebelum penutup body -->
        <script src="{{ asset('assets/vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>

        <!-- Template Main JS File -->
        <script src="{{ asset('assets/js/main.js') }}"></script>

        <script>
            document.getElementById('searchInput').addEventListener('keyup', function() {
                let filter = this.value.toLowerCase();
                let rows = document.querySelectorAll('tbody tr');

                rows.forEach(row => {
                    let text = row.innerText.toLowerCase();
                    row.style.display = text.includes(filter) ? '' : 'none';
                });
            });
        </script>


        <!-- Ini buat sweet alert Konfirmasi Hapus-->
       <script>
    function confirmDelete(userId) {
        Swal.fire({
            title: 'Apakah Anda yakin?',
            text: "Data tidak bisa dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, hapus!'
        }).then((result) => {
            if (result.isConfirmed) {
                // Membuat dan submit form delete secara dinamis
                const form = document.createElement('form');
                form.action = `/user/${userId}`;
                form.method = 'POST';

                const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

                // Tambahkan CSRF token dan spoof method DELETE
                form.innerHTML = `
                    <input type="hidden" name="_token" value="${csrfToken}">
                    <input type="hidden" name="_method" value="DELETE">
                `;

                document.body.appendChild(form);
                form.submit();
            }
        })
    }
</script>


        <!-- Ini buat datatables Custom Rownya dengan Sorting --> <!--Pencarian-->
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                const table = document.getElementById("userTable");
                const tbody = table.querySelector("tbody");
                const rows = Array.from(tbody.querySelectorAll("tr"));
                const headers = table.querySelectorAll("thead th");
                const paginationContainer = document.createElement("div");
                paginationContainer.className = "pagination-container mt-3 d-flex justify-content-end";

                const searchInput = document.getElementById("searchInput");
                const entriesPerPageSelect = document.getElementById("entriesPerPage");

                let currentPage = 1;
                let rowsPerPage = parseInt(entriesPerPageSelect.value) || 5;
                let currentSortColumn = null;
                let currentSortDirection = "asc";

                function filterRows() {
                    const filter = searchInput.value.toLowerCase();
                    return rows.filter(row => row.innerText.toLowerCase().includes(filter));
                }

                function sortRows(columnIndex, direction) {
                    rows.sort((a, b) => {
                        const aText = a.cells[columnIndex].innerText.trim().toLowerCase();
                        const bText = b.cells[columnIndex].innerText.trim().toLowerCase();

                        if (!isNaN(aText) && !isNaN(bText)) {
                            return direction === "asc" ? aText - bText : bText - aText;
                        }

                        return direction === "asc" ? aText.localeCompare(bText) : bText.localeCompare(aText);
                    });
                }

                function displayTablePage(page) {
                    const filteredRows = filterRows();
                    const totalPages = Math.ceil(filteredRows.length / rowsPerPage);

                    if (page > totalPages) page = totalPages;
                    if (page < 1) page = 1;

                    tbody.innerHTML = "";

                    if (entriesPerPageSelect.value === "all") {
                        filteredRows.forEach(row => tbody.appendChild(row));
                    } else {
                        const startIndex = (page - 1) * rowsPerPage;
                        const endIndex = startIndex + rowsPerPage;

                        const rowsToDisplay = filteredRows.slice(startIndex, endIndex);
                        rowsToDisplay.forEach(row => tbody.appendChild(row));

                        updatePagination(page, totalPages);
                    }
                }

                function updatePagination(currentPage, totalPages) {
                    paginationContainer.innerHTML = "";

                    if (totalPages <= 1) return;

                    for (let i = 1; i <= totalPages; i++) {
                        const button = document.createElement("button");
                        button.textContent = i;
                        button.className = "btn btn-sm btn-outline-primary mx-1";
                        if (i === currentPage) button.classList.add("active");

                        button.addEventListener("click", () => {
                            displayTablePage(i);
                        });

                        paginationContainer.appendChild(button);
                    }
                }

                headers.forEach((header, index) => {
                    header.addEventListener("click", () => {
                        if (currentSortColumn === index) {
                            currentSortDirection = currentSortDirection === "asc" ? "desc" : "asc";
                        } else {
                            currentSortColumn = index;
                            currentSortDirection = "asc";
                        }

                        sortRows(index, currentSortDirection);
                        displayTablePage(1);
                    });
                });

                searchInput.addEventListener("keyup", () => displayTablePage(1));
                entriesPerPageSelect.addEventListener("change", function() {
                    rowsPerPage = entriesPerPageSelect.value === "all" ? rows.length : parseInt(
                        entriesPerPageSelect.value);
                    displayTablePage(1);
                });

                displayTablePage(1);
                table.parentNode.appendChild(paginationContainer);
            });
        </script>
    </body>

    </html>