<?php use App\Utils\Flasher; ?>

<?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">Presensi Mahasiswa</h5>
                    </div>

                    <div class="bg-white rounded shadow-sm p-4">
                      <div class="container">
                        <form method="POST" action="/dashboard/dosen-absen_mahasiswa">
                          <div class="row">
                            <!-- Bagian Pilih Mata Kuliah (Kiri) -->
                            <div class="col-md-6">
                              <div class="border rounded p-3">
                                <h5 class="mb-3">Pilih MK Untuk Melakukan Presensi</h5>
                                <div class="d-flex gap-2">
									<select name="id_dmk" class="form-control" required>
										<option value="">Pilih Mata Kuliah</option>
										<?php foreach ($matkul as $m): ?>
											<option value="<?= $m['id_dmk'] ?>">
												<?= $m['singkatan'] ?> / <?= $m['kode_kelas'] ?>
											</option>
										<?php endforeach; ?>
									</select>
                                  <button type="submit" class="btn btn-info" name="cari">Cari</button>
                                </div>
                              </div>
                            </div>

                            <!-- Bagian Edit Absensi (Kanan) -->
                            <div class="col-md-6">
                              <div class="border rounded p-3">
                                <h5 class="mb-3"><i class="bi bi-printer"></i> Cetak Presensi</h5>
                                <a href="/dashboard/dosen-editabsen_mahasiswa" class="btn btn-danger">Cetak Presensi</a>
                              </div>
                            </div>

                            <!-- Elemen Lokasi -->
                            <input type="hidden" id="latitude" name="latitude">
                            <input type="hidden" id="longitude" name="longitude">
                            <input type="hidden" id="keterangan_lokasi" name="keterangan_lokasi">
                            <div id="keterangan_lokasi_div" class="mt-3 text-muted">📍 Mendeteksi lokasi...</div>
                          </div>
                        </form>
                      </div>

                      <!-- Modal Bootstrap untuk error GPS -->
                      <div class="modal fade" id="gpsModal" tabindex="-1" aria-labelledby="gpsModalLabel" aria-hidden="true">
                        <div class="modal-dialog">
                          <div class="modal-content">
                            <div class="modal-header">
                              <h5 class="modal-title" id="gpsModalLabel">Aktifkan Lokasi</h5>
                            </div>
                            <div class="modal-body">
                              Kami tidak dapat mendeteksi lokasi Anda.<br>
                              Pastikan fitur lokasi/GPS di perangkat Anda telah diaktifkan dan beri izin akses lokasi di browser.
                            </div>
                            <div class="modal-footer">
                              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                            </div>
                          </div>
                        </div>
                      </div>

                      <script>
                        function getLocation() {
                          if (navigator.geolocation) {
                            navigator.geolocation.getCurrentPosition(savePosition, showError, {
                              enableHighAccuracy: true,
                              timeout: 5000,
                              maximumAge: 0
                            });
                          } else {
                            console.log("Geolocation tidak didukung oleh browser Anda.");
                            showModal();
                          }
                        }

                        function savePosition(position) {
                          let latitude = position.coords.latitude;
                          let longitude = position.coords.longitude;

                          let campusLat = -6.3825826;
                          let campusLng = 105.914975;
                          let radius = 400;

                          let distance = getDistanceFromLatLonInMeters(latitude, longitude, campusLat, campusLng);

                          let keterangan = (distance <= radius)
                            ? "Presensi dilakukan di kampus"
                            : "Presensi dilakukan di luar kampus";

                          let keterangan_div = (distance <= radius)
                            ? "🛰️ Presensi dilakukan di kampus"
                            : "🚫 Presensi dilakukan di luar kampus";

                          document.getElementById("latitude").value = latitude;
                          document.getElementById("longitude").value = longitude;
                          document.getElementById("keterangan_lokasi").value = keterangan;
                          document.getElementById("keterangan_lokasi_div").textContent = keterangan_div;

                          console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
                          console.log(`Jarak ke kampus: ${distance} meter`);
                          console.log(`Keterangan: ${keterangan}`);
                        }

                        function showError(error) {
                          console.log("Gagal mendapatkan lokasi.");
                          console.log(error);
                          showModal();
                        }

                        function showModal() {
                          let modal = new bootstrap.Modal(document.getElementById('gpsModal'));
                          modal.show();
                        }

                        function getDistanceFromLatLonInMeters(lat1, lon1, lat2, lon2) {
                          var R = 6371000;
                          var dLat = (lat2 - lat1) * Math.PI / 180;
                          var dLon = (lon2 - lon1) * Math.PI / 180;
                          var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
                            Math.sin(dLon / 2) * Math.sin(dLon / 2);
                          var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                          return R * c;
                        }

                        document.addEventListener("DOMContentLoaded", function () {
                          getLocation();
                        });
                      </script>
					  
						<style>
						.flash-message {
							padding: 10px;
							margin-bottom: 15px;
							color: #155724; 
							border-radius: 5px;
							transition: opacity 0.5s ease;
						}
						.flash-message.hide {
							opacity: 0;
							visibility: hidden;
						}
						</style>
						<script>
						document.addEventListener('DOMContentLoaded', function () {
							const flash = document.getElementById('flash-message');
							if (flash) {
								setTimeout(() => {
									flash.classList.add('hide');
								}, 3000); // 3000 ms = 3 detik
							}
						});
						</script>
						<!-- Salah: div selalu ada meskipun kosong -->
						<div class="flash-message" id="flash-message">
							<?php Flasher::flash(); ?>
						</div>

					  <?php if (!empty($mahasiswa)) : ?>
						<div class="alert alert-info mt-2">
							Kelas : <?= htmlspecialchars($kode_kelas) ?><br>
							<h6>Pertemuan Ke: <?= $pertemuan_ke + 1 ?></h6>
						</div>

						<form method="POST" action="/dashboard/dosen-absen_mahasiswa/simpan">
							<input type="hidden" name="id_matkul" value="<?= htmlspecialchars($selected) ?>">
							<input type="hidden" name="pertemuan" value="<?= $pertemuan_ke + 1 ?>">
							<input type="hidden" name="latitude" value="<?= $latitude ?>">
							<input type="hidden" name="longitude" value="<?= $longitude ?>">
							<input type="hidden" name="keterangan_lokasi" value="<?= $keterangan_lokasi ?>">

							<table class="table table-bordered mt-3">
								<thead>
									<tr>
										<th>No</th>
										<th>NIM</th>
										<th>Nama</th>
										<th>Status</th>
									</tr>
								</thead>
								<tbody>
									<?php $no = 1; foreach ($mahasiswa as $mhs): ?>
										<tr>
											<td><?= $no++ ?></td>
											<td><?= htmlspecialchars($mhs['nim']) ?></td>
											<td><?= htmlspecialchars($mhs['nama']) ?></td>
											<td>
												<input type="hidden" name="absensi[<?= $mhs['nim'] ?>]" value="Hadir">
												<select name="absensi[<?= $mhs['nim'] ?>]" class="form-control">
													<option value="Hadir">Hadir</option>
													<option value="Alfa">Alfa</option>
													<option value="Sakit">Sakit</option>
													<option value="Izin">Izin</option>
												</select>
											</td>
										</tr>
									<?php endforeach; ?>
								</tbody>
							</table>

							<?php if ($pertemuan_ke >= 16): ?>
								<button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#infoModal">
									Kelas Ini Sudah Mencapai 16 Kali Pertemuan
								</button>
							<?php else: ?>
								<button type="submit" class="btn btn-success" name="simpan_absensi">Simpan Presensi</button>
							<?php endif; ?>
						</form>

						<!-- Modal Info -->
						<div class="modal fade" id="infoModal" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true">
							<div class="modal-dialog"><div class="modal-content">
								<div class="modal-header">
									<h5 class="modal-title">Informasi</h5>
									<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								</div>
								<div class="modal-body">
									Kelas ini sudah memenuhi jumlah pertemuan sebanyak 16 kali. Tidak dapat menambahkan absensi lagi.
								</div>
								<div class="modal-footer">
									<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
								</div>
							</div></div>
						</div>
					<?php endif; ?>
					  
					  
                    </div>
                  </div>
                </div>
              </div>
            </div>

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

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