<?php include_once __DIR__ . '/../layouts/head.php'; ?>
<div class="container py-4" style="max-width: 1350px; width: 100%;">
  <div class="row">
    <div class="col-lg-12">
      <div class="shadow-sm bg-white rounded overflow-hidden border">
        <div class="p-0">
          <div class="row px-0 m-0">
            <?php include_once __DIR__ . '/../layouts/menu_body.php'; ?>
            <div class="col-12 col-md-9 px-0">
              <div class="tab-content" id="v-pills-tabContent">
                <div class="tab-pane fade show active" id="v-pills-home" role="tabpanel">
                  <div class="p-4">

                    <!-- ================= BAGIAN ATAS: MAHASISWA ================= -->
                    <div class="d-flex justify-content-between align-items-center mb-2">
                      <h5 class="mb-0 fw-bold">Data Mahasiswa Baru</h5>
                      <form method="GET" class="d-flex" style="gap:8px;">
                        <!-- preserve kelas state when searching/paging mahasiswa -->
                        <input type="hidden" name="search_kelas" value="<?= htmlspecialchars($_GET['search_kelas'] ?? '') ?>">
                        <input type="hidden" name="page_kelas" value="<?= htmlspecialchars($_GET['page_kelas'] ?? '') ?>">
                        <input type="text" name="search_user" class="form-control form-control-sm" placeholder="Cari Mahasiswa..." value="<?= htmlspecialchars($_GET['search_user'] ?? '') ?>">
                        <button class="btn btn-sm btn-primary">Cari</button>
                      </form>
                    </div>

                    <div class="table-responsive">
                      <table class="table table-bordered table-striped">
                        <thead class="table-light">
                          <tr>
                            <th width="150">NIM</th>
                            <th>Nama</th>
                            <th>Pilihan</th>
                            <th width="120" class="text-center">Aksi</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php if (!empty($users)): ?>
                            <?php foreach ($users as $user): ?>
                              <tr>
                                <td><?= htmlspecialchars($user['nim']) ?></td>
                                <td><?= htmlspecialchars($user['nama']) ?></td>
                                <td><?= htmlspecialchars($user['pusat_pokjar'] ?? '') ?></td>
                                <td class="text-center">
                                    <button type="button" 
                                      class="btn btn-sm btn-warning edit-user"
                                      data-id="<?= htmlspecialchars($user['id_user']) ?>"
                                      data-nim="<?= htmlspecialchars($user['nim']) ?>"
                                      data-nama="<?= htmlspecialchars($user['nama']) ?>">
                                      <i class="bi bi-pencil"></i>
                                    </button>

                                  <a href="/dashboard/admin-mbr/delete-user/<?= htmlspecialchars($user['id_user']) ?>" class="btn btn-sm btn-danger" onclick="return confirm('Hapus user ini?')">
                                    <i class="bi bi-trash"></i>
                                  </a>
                                </td>
                              </tr>
                            <?php endforeach; ?>
                          <?php else: ?>
                            <tr><td colspan="3" class="text-center">Tidak ada data</td></tr>
                          <?php endif; ?>
                        </tbody>
                      </table>
                    </div>

                    <!-- Pagination Mahasiswa (maks 5 nomor) -->
                    <?php
                        $maxLinks = 5;
                        $cur = (int)($pageUser ?? ($_GET['page_user'] ?? 1));
                        $total = (int)($totalPagesUser ?? 1);
                        $start = max(1, $cur - (int)floor($maxLinks/2));
                        $end = min($total, $start + $maxLinks - 1);
                        if ($end - $start + 1 < $maxLinks) {
                            $start = max(1, $end - $maxLinks + 1);
                        }
                    ?>
                    <nav class="mt-2">
                      <ul class="pagination pagination-sm">
                        <?php
                            for ($btn = 0; $btn <= 1; $btn++) {
                                // first & prev
                                if ($btn == 0) {
                                    $target = 1;
                                    $disabled = $cur <= 1 ? ' disabled' : '';
                                    $params = $_GET; $params['page_user'] = 1;
                                    echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&laquo;&laquo;</a></li>';
                                } else {
                                    $target = max(1, $cur - 1);
                                    $disabled = $cur <= 1 ? ' disabled' : '';
                                    $params = $_GET; $params['page_user'] = $target;
                                    echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&laquo;</a></li>';
                                }
                            }

                            for ($i = $start; $i <= $end; $i++):
                                $params = $_GET; $params['page_user'] = $i;
                        ?>
                          <li class="page-item <?= ($cur == $i) ? 'active' : '' ?>"><a class="page-link" href="/dashboard/admin-mbr?<?= http_build_query($params) ?>"><?= $i ?></a></li>
                        <?php endfor; ?>

                        <?php
                            // next & last
                            $next = min($total, $cur + 1);
                            $params = $_GET; $params['page_user'] = $next;
                            $disabled = $cur >= $total ? ' disabled' : '';
                            echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&raquo;</a></li>';

                            $params = $_GET; $params['page_user'] = $total;
                            $disabled = $cur >= $total ? ' disabled' : '';
                            echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&raquo;&raquo;</a></li>';
                        ?>
                      </ul>
                    </nav>

                    <!-- ================= BAGIAN BAWAH: KELAS ================= -->
                    <div class="d-flex justify-content-between align-items-center mt-4 mb-2">
                      <h5 class="mb-0 fw-bold">Data Kelas</h5>
                      <div class="d-flex" style="gap:8px;">
                        <form method="GET" class="d-flex">
                          <!-- preserve mahasiswa state when searching/paging kelas -->
                          <input type="hidden" name="search_user" value="<?= htmlspecialchars($_GET['search_user'] ?? '') ?>">
                          <input type="hidden" name="page_user" value="<?= htmlspecialchars($_GET['page_user'] ?? '') ?>">
                          <input type="text" name="search_kelas" class="form-control form-control-sm" placeholder="Cari Kelas..." value="<?= htmlspecialchars($_GET['search_kelas'] ?? '') ?>">
                          <button class="btn btn-sm btn-primary ms-2">Cari</button>
                        </form>

                        <!-- tombol tambah kelas (popup) -->
                        <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#addKelasModal">
                          <i class="fa fa-plus"></i> Tambah Data
                        </button>
                      </div>
                    </div>

                    <div class="table-responsive">
                      <table class="table table-bordered table-striped">
                        <thead class="table-light">
                          <tr>
                            <th>Kode Kelas</th>
                            <th>NIM</th>
                            <th>Semester</th>
                            <th>Tahun Akademik</th>
                            <th>Status</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php if (!empty($kelas)): ?>
                            <?php foreach ($kelas as $k): ?>
                              <tr>
                                <td><?= htmlspecialchars($k['kode_kelas'] ?? '') ?></td>
                                <td><?= htmlspecialchars($k['nim'] ?? '') ?></td>
                                <td><?= htmlspecialchars($k['smt'] ?? '') ?></td>
                                <td><?= htmlspecialchars($k['tahun_akademik'] ?? '') ?></td>
                                <td><?= htmlspecialchars($k['Status'] ?? '') ?></td>
                              </tr>
                            <?php endforeach; ?>
                          <?php else: ?>
                            <tr><td colspan="6" class="text-center">Tidak ada data</td></tr>
                          <?php endif; ?>
                        </tbody>
                      </table>
                    </div>

                    <!-- Pagination Kelas (maks 5 nomor) -->
                    <?php
                        $maxLinks = 5;
                        $curK = (int)($pageKelas ?? ($_GET['page_kelas'] ?? 1));
                        $totalK = (int)($totalPagesKelas ?? 1);
                        $startK = max(1, $curK - (int)floor($maxLinks/2));
                        $endK = min($totalK, $startK + $maxLinks - 1);
                        if ($endK - $startK + 1 < $maxLinks) {
                            $startK = max(1, $endK - $maxLinks + 1);
                        }
                    ?>
                    <nav class="mt-2">
                      <ul class="pagination pagination-sm">
                        <?php
                            $params = $_GET; $params['page_kelas'] = 1;
                            $disabled = ($curK <= 1) ? ' disabled' : '';
                            echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&laquo;&laquo;</a></li>';

                            $params = $_GET; $params['page_kelas'] = max(1, $curK - 1);
                            $disabled = ($curK <= 1) ? ' disabled' : '';
                            echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&laquo;</a></li>';

                            for ($i = $startK; $i <= $endK; $i++):
                                $params = $_GET; $params['page_kelas'] = $i;
                        ?>
                          <li class="page-item <?= ($curK == $i) ? 'active' : '' ?>"><a class="page-link" href="/dashboard/admin-mbr?<?= http_build_query($params) ?>"><?= $i ?></a></li>
                        <?php endfor; ?>

                        <?php
                            $params = $_GET; $params['page_kelas'] = min($totalK, $curK + 1);
                            $disabled = ($curK >= $totalK) ? ' disabled' : '';
                            echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&raquo;</a></li>';

                            $params = $_GET; $params['page_kelas'] = $totalK;
                            $disabled = ($curK >= $totalK) ? ' disabled' : '';
                            echo '<li class="page-item'.$disabled.'"><a class="page-link" href="/dashboard/admin-mbr?'.http_build_query($params).'">&raquo;&raquo;</a></li>';
                        ?>
                      </ul>
                    </nav>

                    <!-- ================= MODAL: EDIT MAHASISWA ================= -->
                    <div class="modal fade" id="editUserModal" tabindex="-1">
                      <div class="modal-dialog">
                        <div class="modal-content">
                            <form method="POST" action="/dashboard/admin-mbr/update-user">
                              <div class="modal-header">
                                <h5 class="modal-title">Edit Mahasiswa</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                              </div>
                              <div class="modal-body">
                                <input type="hidden" name="id_user" id="edit_id_user">
                                <input type="hidden" name="nim_lama" id="edit_nim_lama">
                            
                                <div class="mb-3">
                                  <label class="form-label">Username (NIM)</label>
                                  <input type="text" class="form-control" name="username" id="edit_nim" required>
                                </div>
                                <div class="mb-3">
                                  <label class="form-label">Nama</label>
                                  <input type="text" class="form-control" name="nama" id="edit_nama" readonly>
                                </div>
                                <div class="mb-3">
                                  <label class="form-label">Password</label>
                                  <input type="password" class="form-control" name="password" value="mahasiswa">
                                </div>
                                <div class="mb-3">
                                  <label class="form-label">Level</label>
                                  <select name="level" id="edit_level" class="form-select">
                                    <option value="Mahasiswa">Mahasiswa</option>
                                  </select>
                                </div>
                              </div>
                              <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                <button type="submit" class="btn btn-primary">Simpan</button>
                              </div>
                            </form>
                        </div>
                      </div>
                    </div>

                    <!-- ================= MODAL: ADD KELAS ================= -->
                    <div class="modal fade" id="addKelasModal" tabindex="-1">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <form method="POST" action="/dashboard/admin-mbr/insert-kelas">
                            <div class="modal-header">
                              <h5 class="modal-title">Tambah Kelas</h5>
                              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                              <div class="mb-3">
                                <label class="form-label">Kode Kelas</label>
                                <input type="text" name="kode_kelas" class="form-control" required>
                              </div>
                              <div class="mb-3">
                                <label class="form-label">NIM</label>
                                <input type="text" name="nim" class="form-control" required>
                              </div>
                              <div class="mb-3">
                                <label class="form-label">Semester</label>
                                <input type="text" name="smt" class="form-control" required>
                              </div>

                              <?php if (!empty($tahun_akademik)): ?>
                              <div class="mb-3">
                                <label class="form-label">Tahun Akademik</label>
                                <select name="tahun_akademik" class="form-select" required>
                                  <?php foreach ($tahun_akademik as $ta): ?>
                                    <option value="<?= htmlspecialchars($ta['tahun_akademik']) ?>"><?= htmlspecialchars($ta['tahun_akademik']) ?></option>
                                  <?php endforeach; ?>
                                </select>
                              </div>
                              <?php else: ?>
                              <div class="mb-3">
                                <label class="form-label">Tahun Akademik</label>
                                <input type="text" name="tahun_akademik" class="form-control" placeholder="contoh 20251" required>
                              </div>
                              <?php endif; ?>

                              <div class="mb-3">
                                <label class="form-label">Status</label>
                                <select name="status" class="form-select" required>
                                  <option value="Aktif" selected>Aktif</option>
                                  <option value="Non Aktif">Non Aktif</option>
                                </select>
                              </div>
                            </div>
                            <div class="modal-footer">
                              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                              <button type="submit" class="btn btn-success">Tambah</button>
                            </div>
                          </form>
                        </div>
                      </div>
                    </div>

                        <script>
                          // Listener tombol edit user
                          document.querySelectorAll('.edit-user').forEach(btn => {
                            btn.addEventListener('click', function() {
                              document.getElementById('edit_id_user').value = this.dataset.id;
                              document.getElementById('edit_nim').value = this.dataset.nim;
                              document.getElementById('edit_nim_lama').value = this.dataset.nim;
                              document.getElementById('edit_nama').value = this.dataset.nama;
                              // isi default password setiap buka modal
                              document.querySelector('#editUserModal input[name="password"]').value = 'mahasiswa';
                              document.getElementById('edit_level').value = 'Mahasiswa';
                              // tampilkan modal
                              new bootstrap.Modal(document.getElementById('editUserModal')).show();
                            });
                          });
                        </script>

                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>  
    </div>
  </div>
</div>
<?php include_once __DIR__ . '/../layouts/footer.php'; ?>
