<?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">Halaman Cetak & Edit Presensi Mahasiswa</h5>
                    </div>

                    <div class="bg-white rounded shadow-sm p-4">
                      <div class="container">
						<form method='POST' action="/dashboard/dosen-editabsen_mahasiswa">
							<div class="border rounded d-flex gap-1 p-2">
								<select name="id_dmk" class="form-control w-auto" required>
									<option value="">Pilih Kelas dan Matakuliah</option>
									<?php foreach ($matkuls as $mk): ?>
										<option value="<?= $mk['id_dmk'] ?>" <?= isset($selectedDmk) && $selectedDmk == $mk['id_dmk'] ? 'selected' : '' ?>>
											<?= $mk['kode_kelas'] ?> <?= $mk['singkatan'] ?? '' ?>
										</option>
									<?php endforeach; ?>
								</select>
								<select name="edit_pertemuan" class="form-control w-auto" required>
									<option value="">Pilih Pertemuan</option>
									<?php for ($i = 1; $i <= 16; $i++): ?>
										<option value="<?= $i ?>" <?= isset($selectedPertemuan) && $selectedPertemuan == $i ? 'selected' : '' ?>>
											Pertemuan <?= $i ?>
										</option>
									<?php endfor; ?>
								</select>
							
								<button type="submit" class="btn btn-warning" name="cari">Cari</button>
							</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>
						</form>
                      </div>
					  
						<?php if (!empty($error)): ?>
							<div id="errorAlert" class="alert alert-warning mt-3"><?= htmlspecialchars($error) ?></div>
							<script>
								setTimeout(() => {
									const alert = document.getElementById('errorAlert');
									if (alert) {
										alert.style.transition = 'opacity 0.5s ease';
										alert.style.opacity = '0';
										setTimeout(() => alert.remove(), 20000);
									}
								}, 20000);
							</script>
							<a href="/dashboard/dosen-absen_mahasiswa" class="btn btn-danger"><i class="bi bi-arrow-90deg-left"></i> Babck</a>
						<?php endif; ?>

                      <!-- 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($absensi) && $selectedDmk && $selectedPertemuan): ?>
                            <div class="mb-3 d-flex align-items-center gap-2 flex-wrap">
                                
                                <!-- Tombol PDF (selalu ada) -->
                                <a href="/dashboard/dosen-cetakpresensi-pdf?id_dmk=<?= $selectedDmk ?>&pertemuan=<?= $selectedPertemuan ?>"
                                   target="_blank"
                                   class="btn btn-danger">
                                    <i class="bi bi-printer"></i> Cetak Presensi (PDF)
                                </a>
                        
                                <!-- Tombol Excel (hanya pertemuan 16) -->
                                <?php if ($selectedPertemuan == 16): ?>
                                    <a href="/dashboard/dosen-cetakpresensi-excel?id_dmk=<?= $selectedDmk ?>"
                                       class="btn btn-success">
                                        <i class="bi bi-file-earmark-excel"></i> Rekap Presensi Excel
                                    </a>
                                <?php endif; ?>
                        
                            </div>
                        
                            <p class="text-muted">
                                Silahkan lakukan edit presensi jika terdapat ketidaksesuaian daftar presensi
                                pada kelas dan pertemuan ini.
                            </p>
                        <?php endif; ?>


                        <?php if (!empty($absensi)): ?>
                            <form method="POST" action="/dashboard/dosen-editabsen_mahasiswa/update">
                                <input type="hidden" name="id_dmk" value="<?= $selectedDmk ?>">
                                <input type="hidden" name="edit_pertemuan" value="<?= $selectedPertemuan ?>">
                                <input type="hidden" name="latitude" value="<?= $_POST['latitude'] ?? '' ?>">
                                <input type="hidden" name="longitude" value="<?= $_POST['longitude'] ?? '' ?>">
                                <input type="hidden" name="keterangan_lokasi" value="<?= $_POST['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 foreach ($absensi as $no => $m): ?>
                                        <tr>
                                            <td><?= $no + 1 ?></td>
                                            <td><?= $m['nim'] ?></td>
                                            <td><?= $m['nama'] ?></td>
                                            <td>
                                                <input type="hidden" name="nim[]" value="<?= $m['nim'] ?>">
                                                <select name="status_edit[]" class="form-control" required>
                                                    <option value="" disabled <?= is_null($m['status_absensi']) ? 'selected' : '' ?>>-- Pilih Status --</option>
                                                    <?php foreach (['Hadir', 'Alfa', 'Sakit', 'Izin'] as $status): ?>
                                                        <option value="<?= $status ?>" <?= ($m['status_absensi'] == $status) ? 'selected' : '' ?>>
                                                            <?= $status ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                        
                                <button type="submit" name="update_absensi" class="btn btn-success">Update Absensi</button>
                            </form>
                        <?php endif; ?>


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

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

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