<?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">
                <!-- Awal isi konten -->
                <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">Form Pendaftaran Sidang Skripsi</h5>
                    </div>

                    <div class="col"><br></div>

                    <?php if (isset($error)): ?>
                      <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
                    <?php endif; ?>

                    <?php if (!empty($data_sidang)): ?>
                      <div class="text-end">
                        <a href="/dashboard/mahasiswa/form-s-skripsi?nim=<?= htmlspecialchars($nim) ?>" class="btn btn-success" target="_BLANK">
                          <i class="bi bi-file-pdf"></i> Cetak Formulir Pendaftaran Sidang
                        </a>
                      </div>
					  
						<?php if (!empty($_SESSION['success'])): ?>
						  <div class="alert alert-success alert-dismissible fade show" id="alert-success">
							<?= $_SESSION['success']; unset($_SESSION['success']); ?>
						  </div>
						<?php endif; ?>

						<?php if (!empty($_SESSION['error'])): ?>
						  <div class="alert alert-danger alert-dismissible fade show" id="alert-error">
							<?= $_SESSION['error']; unset($_SESSION['error']); ?>
						  </div>
						<?php endif; ?>

						<script>
						  setTimeout(function() {
							const successAlert = document.getElementById('alert-success');
							const errorAlert = document.getElementById('alert-error');
							if (successAlert) successAlert.style.display = 'none';
							if (errorAlert) errorAlert.style.display = 'none';
						  }, 2000); // 2 detik
						</script>	
					
                      <form action="/dashboard/mahasiswa-daftarskripsi-update" method="post" class="needs-validation" novalidate>
                        <div class="mb-3">
                          <label for="nim" class="form-label">NIM</label>
                          <input type="text" class="form-control" id="nim" name="nim" value="<?= htmlspecialchars($data_sidang['nim'] ?? '') ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="nama" class="form-label">Nama Mahasiswa</label>
                          <input type="text" class="form-control" id="nama" name="nama" value="<?= htmlspecialchars($data_sidang['nama'] ?? '') ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="prodi" class="form-label">Program Studi</label>
                          <input type="text" class="form-control" id="prodi" name="prodi" value="<?= htmlspecialchars($data_sidang['prodi'] ?? '') ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="nik" class="form-label">NIK</label>
                          <input type="text" class="form-control" id="nik" name="nik" required pattern="\d{16}" maxlength="16" minlength="16" oninput="this.value = this.value.replace(/[^0-9]/g, '')" placeholder="Masukkan 16 digit NIK" value="<?= htmlspecialchars($data_sidang['nik'] ?? '') ?>">
                          <div class="invalid-feedback">NIK harus terdiri dari tepat 16 digit angka.</div>
                        </div>

                        <div class="mb-3">
                          <label for="ttl" class="form-label">TTL </label>
                          <input type="text" class="form-control" id="ttl" name="ttl" value="<?= htmlspecialchars($data_sidang['ttl'] ?? '') ?>" >
                        </div>

                        <div class="mb-3">
                          <label for="alamat" class="form-label">Alamat </label>
                          <textarea class="form-control" id="alamat" name="alamat"><?= htmlspecialchars($data_sidang['alamat'] ?? '') ?></textarea>
                        </div>
						
                        <div class="mb-3">
                          <label for="judul" class="form-label">Judul Skripsi</label>
                          <textarea class="form-control" id="judul" name="judul" required><?= htmlspecialchars($data_sidang['judul'] ?? '') ?></textarea>
                        </div>

                        <div class="mb-3">
                          <label for="apembimbing1" class="form-label">Dosen Pembimbing I</label>
                          <input class="form-control" name="pembimbing1" id="apembimbing1" autocomplete="off" required list="alist_dosen1" value="<?= htmlspecialchars($data_sidang['pembimbing1'] ?? '') ?>">
                          <datalist id="alist_dosen1"></datalist>
                        </div>

                        <div class="mb-3">
                          <label for="apembimbing2" class="form-label">Dosen Pembimbing II</label>
                          <input class="form-control" name="pembimbing2" id="apembimbing2" autocomplete="off" required list="alist_dosen2" value="<?= htmlspecialchars($data_sidang['pembimbing2'] ?? '') ?>">
                          <datalist id="alist_dosen2"></datalist>
                        </div>

                        <button type="submit" class="btn btn-primary">Update Formulir</button>
                      </form>
                    <script>
                        (function () {
                          'use strict';
                          var forms = document.querySelectorAll('.needs-validation');
                          Array.prototype.slice.call(forms)
                            .forEach(function (form) {
                              form.addEventListener('submit', function (event) {
                                if (!form.checkValidity()) {
                                  event.preventDefault();
                                  event.stopPropagation();
                                }
                                form.classList.add('was-validated');
                              }, false);
                            });
                        })();

                        function setupAutoSuggest(inputId, datalistId) {
                          const input = document.getElementById(inputId);
                          const datalist = document.getElementById(datalistId);

                          input.addEventListener('input', function () {
                            const keyword = this.value.trim();
                            if (keyword.length < 2) {
                              datalist.innerHTML = '';
                              return;
                            }

                            fetch('/dashboard/mahasiswa-search-dosen?keyword=' + encodeURIComponent(keyword))
                              .then(response => response.json())
                              .then(data => {
                                let options = '';
                                data.forEach(dosen => {
                                  options += `<option value="${dosen}">`;
                                });
                                datalist.innerHTML = options;
                              })
                              .catch(err => {
                                console.error('Fetch error:', err);
                                datalist.innerHTML = '';
                              });
                          });
                        }

                        setupAutoSuggest('apembimbing1', 'alist_dosen1');
                        setupAutoSuggest('apembimbing2', 'alist_dosen2');
                      </script>
					  
                    <?php elseif (!empty($token_required)): ?>
                      <form method="post" action="/dashboard/mahasiswa-daftarskripsi">
                        <div class="mb-3">
                          <label for="token" class="form-label">Masukkan Token Sidang Skripsi:</label>
                          <input type="text" name="token" class="form-control" id="token" placeholder="Token Sidang Skripsi" required>
                        </div>
                        <button type="submit" class="btn btn-primary" name="daftarsidang">Submit</button>
                      </form>

                    <?php elseif (!empty($form_submitted)): ?>
                      <form action="" method="post" class="needs-validation" novalidate>
                        <div class="mb-3">
                          <label for="nim" class="form-label">NIM</label>
                          <input type="text" class="form-control" id="nim" name="nim" value="<?= htmlspecialchars($nim) ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="nama" class="form-label">Nama Mahasiswa</label>
                          <input type="text" class="form-control" id="nama" name="nama" value="<?= htmlspecialchars($nama) ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="prodi" class="form-label">Program Studi</label>
                          <input type="text" class="form-control" id="prodi" name="prodi" value="<?= htmlspecialchars($prodi) ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="nik" class="form-label">NIK</label>
                          <input type="text" class="form-control" id="nik" name="nik" required pattern="\d{16}" maxlength="16" minlength="16" oninput="this.value = this.value.replace(/[^0-9]/g, '')" placeholder="Masukkan 16 digit NIK">
                          <div class="invalid-feedback">NIK harus terdiri dari tepat 16 digit angka.</div>
                        </div>

                        <div class="mb-3">
                          <label for="ttl" class="form-label">TTL <small><i>Untuk merubah ini silahkan ubah menu profile</i></small></label>
                          <input type="text" class="form-control" id="ttl" name="ttl" value="<?= htmlspecialchars($ttl) ?>" readonly>
                        </div>

                        <div class="mb-3">
                          <label for="alamat" class="form-label">Alamat <small><i>Untuk merubah ini silahkan ubah menu profile</i></small></label>
                          <textarea class="form-control" id="alamat" name="alamat" readonly><?= htmlspecialchars($alamat) ?></textarea>
                        </div>

                        <div class="mb-3">
                          <label for="judul" class="form-label">Judul Skripsi</label>
                          <textarea class="form-control" id="judul" name="judul" required></textarea>
                        </div>

                        <div class="mb-3">
                          <label for="pembimbing1" class="form-label">Dosen Pembimbing I</label>
                          <input class="form-control" name="pembimbing1" id="pembimbing1" autocomplete="off" required list="list_dosen1">
                          <datalist id="list_dosen1"></datalist>
                        </div>

                        <div class="mb-3">
                          <label for="pembimbing2" class="form-label">Dosen Pembimbing II</label>
                          <input class="form-control" name="pembimbing2" id="pembimbing2" autocomplete="off" required list="list_dosen2">
                          <datalist id="list_dosen2"></datalist>
                        </div>

                        <button type="submit" class="btn btn-primary">Daftar Skripsi</button>
                      </form>

                      <script>
                        (function () {
                          'use strict';
                          var forms = document.querySelectorAll('.needs-validation');
                          Array.prototype.slice.call(forms)
                            .forEach(function (form) {
                              form.addEventListener('submit', function (event) {
                                if (!form.checkValidity()) {
                                  event.preventDefault();
                                  event.stopPropagation();
                                }
                                form.classList.add('was-validated');
                              }, false);
                            });
                        })();

                        function setupAutoSuggest(inputId, datalistId) {
                          const input = document.getElementById(inputId);
                          const datalist = document.getElementById(datalistId);

                          input.addEventListener('input', function () {
                            const keyword = this.value.trim();
                            if (keyword.length < 2) {
                              datalist.innerHTML = '';
                              return;
                            }

                            fetch('/dashboard/mahasiswa-search-dosen?keyword=' + encodeURIComponent(keyword))
                              .then(response => response.json())
                              .then(data => {
                                let options = '';
                                data.forEach(dosen => {
                                  options += `<option value="${dosen}">`;
                                });
                                datalist.innerHTML = options;
                              })
                              .catch(err => {
                                console.error('Fetch error:', err);
                                datalist.innerHTML = '';
                              });
                          });
                        }

                        setupAutoSuggest('pembimbing1', 'list_dosen1');
                        setupAutoSuggest('pembimbing2', 'list_dosen2');
                      </script>

                    <?php else: ?>
                      <p>Data tidak ditemukan atau tidak ada aksi yang dapat dilakukan.</p>
                    <?php endif; ?>

                  </div> <!-- end p-4 -->
                </div> <!-- end tab-pane -->
              </div> <!-- end tab-content -->
            </div> <!-- end col-9 -->

          </div> <!-- end row -->
        </div> <!-- end p-0 -->
      </div> <!-- end shadow-sm -->
    </div> <!-- end col -->
  </div> <!-- end row -->
</div> <!-- end container -->

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