<?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" aria-labelledby="v-pills-home-tab">
                  <div class="p-4">
                    <div class="mb-4">
                      <h5 class="mb-0 fw-bold">Pengaturan Jadwal</h5>
                    </div>  
                    
                    <div class="row row-cols-1 row-cols-md-2 g-4">


						<!-- Dropdown Jumlah Data di Sisi Kiri -->
						<div class="d-flex justify-content-left">
							<div class="d-flex align-items-center">
								<select class="form-select me-3" id="pageSize" style="width: auto;" onchange="setPageSize(this.value)">
								  <?php foreach ([10, 25, 50, 100, 200] as $size): ?>
									<option value="<?= $size ?>" <?= $per_page == $size ? 'selected' : '' ?>><?= $size ?></option>
								  <?php endforeach; ?>
								</select>
							</div>
							<button type="button" class="btn btn-sm btn-primary me-2 d-flex align-items-center" data-bs-toggle="modal" data-bs-target="#tambahJadwalModal">
								<i class="bi bi-plus-circle"></i> <span style="font-size: 0.55rem;">&nbsp; Add</span>
							</button>
						</div>

						<!-- Tombol Add dan Soal Nihil di Tengah -->
                        <div class="d-flex justify-content-end align-items-center gap-2">
                            
                            <!-- Belum Upload -->
                            <button type="button"
                                class="btn btn-sm btn-primary d-flex align-items-center"
                                onclick="window.location.href='/dashboard/pegawai-jadwal-ujian/download-belum-upload'">
                                <i class="bi bi-file-earmark-arrow-down"></i>
                                <span style="font-size:0.55rem;">&nbsp;Blm Upload</span>
                            </button>
                        
                            <!-- Sudah Upload -->
                            <button type="button"
                                class="btn btn-sm btn-success d-flex align-items-center"
                                onclick="window.location.href='/dashboard/pegawai-jadwal-ujian/download-sudah-upload'">
                                <i class="bi bi-check-circle"></i>
                                <span style="font-size:0.55rem;">&nbsp;Sudah Upload</span>
                            </button>
                        
                            <!-- Search -->
                            <form method="GET" class="d-flex ms-3" role="search">
                                <input type="hidden" name="per_page" value="<?= $per_page ?>">
                                <input 
                                    type="text" 
                                    name="search" 
                                    class="form-control rounded-end no-rounded-left" 
                                    placeholder="Cari Dosen atau MK" 
                                    value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>">
                                <button type="submit" class="btn btn-primary rounded-start no-rounded-right">
                                    <i class="bi bi-search"></i>
                                </button>
                            </form>
                        
                        </div>
                      
                      <!-- Tabel Jadwal Ujian -->
                      <table class="table table-bordered table-dinamis mt-3" id="jadwalTable">
                        <thead class="text-center">
                          <tr>
                            <th scope="col">No</th>
                            <th scope="col">Nama MK</th>
                            <th scope="col">Kelas</th>
                            <th scope="col">Nama Dosen</th>
                            <th scope="col">Tanggal Ujian</th>
                            <th scope="col">Jam Ujian</th>
                            <th scope="col">Jenis Ujian</th>
                            <th scope="col" colspan="2">Aksi</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php $no = $offset + 1; foreach ($jadwal_ujian as $ujian): ?>
                            <tr>
                              <td class="text-center"><?= $no ?></td>
                              <td><?= htmlspecialchars($ujian['nama_mk']) ?></td>
                              <td class="text-center"><?= htmlspecialchars($ujian['kode_kelas']) ?></td>
                              <td><?= htmlspecialchars($ujian['nama_dosen']) ?></td>
                              <td class="text-center"><?= $ujian['tgl_mulai_ujian'] ?? '<small class="text-muted">Belum Dijadwalkan</small>' ?></td>
                              <td class="text-center"><?= $ujian['jam_mulai'] ?? '<small class="text-muted">Belum Dijadwalkan</small>' ?></td>
                              <td class="text-center"><?= $ujian['jenis_soal'] ?? '<small class="text-muted">Belum Dijadwalkan</small>' ?></td>
                              <?php if ($ujian['soal_terupload'] > 0): ?>
                                <td class="text-center">
                                  <?php if (!empty($ujian['id_jadwal_u'])): ?>
                                    <a href="/dashboard/pegawai-jadwal-ujian?edit=<?= $ujian['id_jadwal_u'] ?>&search=<?= urlencode($search) ?>&per_page=<?= $per_page ?>&page=<?= $page ?>" class="btn btn-primary" title="Edit">
                                      <i class="bi bi-pencil"></i>
                                    </a>
                                  <?php else: ?>
                                    <a href="#" class="btn btn-primary" onclick="showPopup(event)" title="Edit"><i class="bi bi-pencil"></i></a>
                                  <?php endif; ?>
                                </td>
                                <td class="text-center">
                                  <?php if (!empty($ujian['id_jadwal_u'])): ?>
                                    <a href="/dashboard/pegawai-jadwal-ujian?hapus=<?= $ujian['id_jadwal_u'] ?>&search=<?= urlencode($search) ?>&per_page=<?= $per_page ?>&page=<?= $page ?>" class="btn btn-warning" title="Hapus" onclick="return confirm('Yakin hapus jadwal?')">
                                      <i class="bi bi-trash"></i>
                                    </a>
                                  <?php else: ?>
                                    <a href="#" class="btn btn-warning" onclick="showPopup(event)" title="Hapus"><i class="bi bi-trash"></i></a>
                                  <?php endif; ?>
                                </td>
                              <?php else: ?>
                                <td colspan="2" class="text-center">
                                  <small><button class="btn btn-danger btn-sm" disabled style="font-size: 0.45rem;">Soal Nihil</button></small>
                                </td>
                              <?php endif; ?>
                            </tr>
                          <?php $no++; endforeach; ?>
                        </tbody>
                      </table>

                      <!-- Pagination -->
                      <?php if ($total_pages > 1): ?>
                      <?php
                          $max_links = 7;
                          $start = max(1, $page - floor($max_links / 2));
                          $end = min($total_pages, $start + $max_links - 1);
                          if ($end - $start + 1 < $max_links) {
                              $start = max(1, $end - $max_links + 1);
                          }
                          // Base URL dengan parameter pencarian dan per_page agar konsisten
                          $base_url = '/dashboard/pegawai-jadwal-ujian?' . urlencode($search) . '&per_page=' . $per_page . '&page=';
                      ?>
                      <nav>
                        <ul class="pagination justify-content-center mt-3">
                          <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= $base_url ?>1">&laquo;</a>
                          </li>
                          <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= $base_url . max(1, $page - 1) ?>">&lsaquo;</a>
                          </li>
                          <?php for ($i = $start; $i <= $end; $i++): ?>
                            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                              <a class="page-link" href="<?= $base_url . $i ?>"><?= $i ?></a>
                            </li>
                          <?php endfor; ?>
                          <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= $base_url . min($total_pages, $page + 1) ?>">&rsaquo;</a>
                          </li>
                          <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= $base_url . $total_pages ?>">&raquo;</a>
                          </li>
                        </ul>
                      </nav>
                      <?php endif; ?>

                    </div>
                  </div>      
                </div>      
              </div>      
            </div>      
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
function showPopup(event) {
    event.preventDefault(); // Cegah redirect default
    alert("Dosen belum dijadwalkan");
    window.location.href = "/dashboard/pegawai-jadwal-ujian";
}

function setPageSize(size) {
	// Implementasi pagination di sini sesuai dengan jumlah data yang diinginkan
}

function setPageSize(size) {
	window.location.href = "/dashboard/pegawai-jadwal-ujian?page=1&per_page=" + size; // Redirect dengan page size baru
}

function filterTable() {
	// Filter pencarian berdasarkan input nama dosen atau mata kuliah
	const input = document.getElementById('searchInput').value.toLowerCase();
	const table = document.getElementById('jadwalTable');
	const rows = table.getElementsByTagName('tr');

	for (let i = 1; i < rows.length; i++) {
		const cells = rows[i].getElementsByTagName('td');
		const namaMK = cells[2].innerText.toLowerCase();
		const namaDosen = cells[3].innerText.toLowerCase();

		if (namaMK.includes(input) || namaDosen.includes(input)) {
			rows[i].style.display = '';
		} else {
			rows[i].style.display = 'none';
		}
	}
}
</script>

<!-- Modal Tambah Jadwal Ujian -->
<div class="modal fade" id="tambahJadwalModal" tabindex="-1" aria-labelledby="tambahJadwalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="tambahJadwalLabel">Tambah Jadwal Ujian</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form method="post" action="/dashboard/pegawai-jadwal-ujian/simpan">
          
<!-- Dosen AJAX Search -->
<div class="mb-3 position-relative">
  <label for="nama_dosen" class="form-label">Cari Dosen</label>
  <input 
    type="text" 
    id="nama_dosen" 
    class="form-control" 
    placeholder="Ketik nama dosen atau MK..."
    autocomplete="off"
    required
  >
  <input type="hidden" name="id_dmk" id="id_dmk">
  <div id="suggestions" class="list-group position-absolute w-100" style="z-index: 1050;"></div>
</div>

          <div class="mb-3">
            <label for="tgl_mulai_ujian" class="form-label">Tanggal Ujian</label>
            <input type="date" name="tgl_mulai_ujian" class="form-control" required>
          </div>

          <!-- Jam Mulai -->
          <div class="mb-3">
            <label for="jam_mulai" class="form-label">Jam Mulai</label>
            <div class="input-group">
              <select class="form-select" id="jam" name="jam" required>
                <option value="">Jam</option>
                <?php for ($i = 0; $i < 24; $i++): ?>
                  <option value="<?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>"
                    <?= $i == 7 ? 'selected' : '' ?>>
                    <?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>
                  </option>
                <?php endfor; ?>
              </select>
              <span class="input-group-text">:</span>
              <select class="form-select" id="menit" name="menit" required>
                <option value="">Menit</option>
                <?php for ($i = 0; $i < 60; $i++): ?>
                  <option value="<?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>"
                    <?= $i == 0 ? 'selected' : '' ?>>
                    <?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>
                  </option>
                <?php endfor; ?>
              </select>
            </div>
          </div>

          <!-- Jam Berakhir -->
          <div class="mb-3">
            <label for="jam_berakhir" class="form-label">Jam Berakhir</label>
            <div class="input-group">
              <select class="form-select" id="jama" name="jama" required>
                <option value="">Jam</option>
                <?php for ($i = 0; $i < 24; $i++): ?>
                  <option value="<?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>"
                    <?= $i == 23 ? 'selected' : '' ?>>
                    <?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>
                  </option>
                <?php endfor; ?>
              </select>
              <span class="input-group-text">:</span>
              <select class="form-select" id="menita" name="menita" required>
                <option value="">Menit</option>
                <?php for ($i = 0; $i < 60; $i++): ?>
                  <option value="<?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>"
                    <?= $i == 0 ? 'selected' : '' ?>>
                    <?= str_pad($i, 2, '0', STR_PAD_LEFT) ?>
                  </option>
                <?php endfor; ?>
              </select>
            </div>
          </div>

          <div class="mb-3">
            <label for="jenis_soal" class="form-label">Jenis Ujian</label>
            <select name="jenis_soal" class="form-select" required>
              <?php foreach ($jenis_soal as $js): ?>
                <option value="<?= $js['jenis_soal'] ?>"><?= $js['jenis_soal'] ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <button type="submit" name="tambah_jadwal" class="btn btn-primary">Tambah Jadwal Ujian</button>
        </form>
      </div>
    </div>
  </div>
</div>


<?php if (!empty($jadwal_edit)): ?>
<div class="modal fade show" id="editJadwalModal" tabindex="-1" style="display:block;" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" action="/dashboard/pegawai-jadwal-ujian/edit">
        <div class="modal-header">
          <h5 class="modal-title">Edit Jadwal Ujian</h5>
          <a href="/dashboard/pegawai-jadwal-ujian" class="btn-close" aria-label="Close"></a>
        </div>
        <div class="modal-body">
          <input type="hidden" name="id_jadwal_u" value="<?= $jadwal_edit['id_jadwal_u'] ?>">
          <!-- Dosen MK -->
          <div class="mb-3">
            <label class="form-label">Dosen</label>
            <select name="id_dmk" class="form-select" required>
              <?php foreach ($dosenedit_mk ?? [] as $dm): ?>
                <option value="<?= $dm['id_dmk'] ?>" selected>
                  <?= $dm['nama_dosen'] . ' - ' . $dm['nama_mk'] . ' (' . $dm['kode_kelas'] . ')' ?>
                </option>
              <?php endforeach; ?>
              <?php foreach ($dosen_mk as $dm): ?>
                <option value="<?= $dm['id_dmk'] ?>">
                  <?= $dm['nama_dosen'] . ' - ' . $dm['nama_mk'] . ' (' . $dm['kode_kelas'] . ')' ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Tanggal Mulai</label>
            <input type="date" name="tgl_mulai_ujian" class="form-control" value="<?= $jadwal_edit['tgl_mulai_ujian'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Tanggal Berakhir</label>
            <input type="date" name="tgl_berakhir" class="form-control" value="<?= $jadwal_edit['tgl_berakhir'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Jam Mulai</label>
            <input type="time" name="jam_mulai" class="form-control" value="<?= $jadwal_edit['jam_mulai'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Jam Berakhir</label>
            <input type="time" name="jam_berakhir" class="form-control" value="<?= $jadwal_edit['jam_berakhir'] ?>" required>
          </div>
          <div class="mb-3">
            <label class="form-label">Jenis Soal</label>
            <select name="jenis_soal" class="form-select" readonly>
              <?php foreach ($jenis_soal as $js): ?>
                <option value="<?= $js['jenis_soal'] ?>" <?= $jadwal_edit['jenis_soal'] == $js['jenis_soal'] ? 'selected' : '' ?>>
                  <?= $js['jenis_soal'] ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="edit_jadwal" class="btn btn-primary">Simpan Perubahan</button>
        </div>
      </form>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- letakkan ini di bagian paling bawah sebelum </body> -->
<script src="/assets/vendor/jquery/jquery.min.js"></script>
<script src="/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/assets/js/sweetalert2.all.min.js"></script>

<script>
$(document).ready(function() {
  // Ketika user mengetik
  $('#nama_dosen').on('keyup', function() {
    const query = $(this).val().trim();

    if (query.length < 2) {
      $('#suggestions').hide();
      return;
    }

    $.ajax({
      url: '/dashboard/pegawai-jadwal-ujian/cari-dosen',
      data: { q: query },
      dataType: 'json',
      success: function(data) {
        let html = '';
        if (data.length > 0) {
          data.forEach(function(item) {
            html += `
              <button type="button" class="list-group-item list-group-item-action suggestion-item" 
                      data-id="${item.id}" data-text="${item.text}">
                ${item.text}
              </button>`;
          });
        } else {
          html = '<div class="list-group-item text-muted">Tidak ditemukan</div>';
        }
        $('#suggestions').html(html).show();
      },
      error: function(xhr, status, error) {
        $('#suggestions').html('<div class="list-group-item text-danger">Gagal memuat data</div>').show();
      }
    });
  });

  // 🟢 Saat user klik salah satu hasil
  $(document).on('click', '.suggestion-item', function() {
    const id = $(this).data('id');
    const text = $(this).data('text');

    // Tampilkan teks di input, simpan id di hidden input
    $('#nama_dosen').val(text);
    $('#id_dmk').val(id);

    // Sembunyikan hasil setelah dipilih
    $('#suggestions').hide();

    console.log("Dipilih:", id, text);
  });

  // 🟡 Kalau user klik di luar daftar, sembunyikan juga
  $(document).click(function(e) {
    if (!$(e.target).closest('#nama_dosen, #suggestions').length) {
      $('#suggestions').hide();
    }
  });
});
</script>


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