<?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">
                    <div class="mb-4">
                      <h5 class="mb-0 fw-bold">Manajemen Presensi Kegiatan</h5>
                    </div>

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

                    <!-- Form Presensi -->
                    <div class="card shadow-sm border-0 mb-4">
                      <div class="card-body">
                        <h6 class="fw-bold mb-3">Form Presensi</h6>

                        <form action="/dashboard/pegawai-presen-kegiatan/store" method="POST" class="mb-4">
                          <div class="mb-3">
                            <label for="nisn" class="form-label">NISN / Username (Manual)</label>
                            <input type="text" class="form-control" name="nisn" id="nisn" required>
                          </div>
                          <button type="submit" class="btn btn-primary">Simpan Manual</button>
                        </form>

                        <!-- Tombol Scan -->
                        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#scanModal">
                          Aktifkan Scan
                        </button>
                        <div id="scan-result" class="mt-3 text-success fw-bold"></div>
                      </div>
                    </div>

                    <!-- Tabel Presensi -->
                    <div class="card shadow-sm border-0">
                      <div class="card-body">
                        <h6 class="fw-bold mb-3">Daftar Kehadiran</h6>
                        <div class="table-responsive">
                          <table class="table table-bordered table-striped">
                            <thead>
                              <tr>
                                <th>No</th>
                                <th>Username</th>
                                <th>Nama</th>
                                <th>Kegiatan</th>
                                <th>Tanggal</th>
                                <th>Waktu Presensi</th>
                              </tr>
                            </thead>
                            <tbody>
                              <?php if (!empty($presensi)): ?>
                                <?php $no = 1; foreach ($presensi as $p): ?>
                                <tr>
                                  <td><?= $no++ ?></td>
                                  <td><?= htmlspecialchars($p['username']) ?></td>
                                  <td><?= htmlspecialchars($p['nama_peserta']) ?></td>
                                  <td><?= htmlspecialchars($p['nama_kegiatan']) ?></td>
                                  <td><?= htmlspecialchars($p['tanggal']) ?></td>
                                  <td><?= htmlspecialchars($p['waktu_presensi']) ?></td>
                                </tr>
                                <?php endforeach; ?>
                              <?php else: ?>
                                <tr><td colspan="6" class="text-center">Belum ada presensi</td></tr>
                              <?php endif; ?>
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>

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

          </div> <!-- row -->
        </div>
      </div>
    </div>
  </div>
</div>

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

<style>
.scan-overlay {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    pointer-events: none;
}
.scan-box {
    width: 70%;
    aspect-ratio: 1 / 1;
    border: 3px solid #4CAF50;
    position: relative;
}
.scan-line {
    position: absolute;
    left: 0;
    width: 100%;
    height: 3px;
    background: red;
    animation: scanAnim 2s infinite;
}
@keyframes scanAnim {
    0% { top: 0; }
    50% { top: 95%; }
    100% { top: 0; }
}
</style>



<!-- Modal -->
<div class="modal fade" id="scanModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-body">
      <div id="reader-container" style="position: relative; width:100%; max-width:350px; margin:auto;">
        
        <!-- kamera -->
        <video id="cameraPreview" autoplay playsinline style="width:100%; border-radius:10px;"></video>

        <!-- overlay detektor -->
        <div class="scan-overlay">
          <div class="scan-box">
            <div class="scan-line"></div>
          </div>
        </div>

      </div>
      <div id="scan-result" class="text-center mt-2 fw-bold text-success"></div>
    </div>
  </div>
</div>

<!-- lib jsQR -->
<script src="https://cdn.jsdelivr.net/npm/jsqr/dist/jsQR.js"></script>
<script>
let stream;
let scanInterval;

const video = document.getElementById('cameraPreview');
const resultBox = document.getElementById('scan-result');

// saat modal dibuka -> aktifkan kamera + scan
document.getElementById('scanModal').addEventListener('shown.bs.modal', async function () {
  try {
    stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
    video.srcObject = stream;

    // siapkan canvas untuk membaca frame
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    scanInterval = setInterval(() => {
      if (video.readyState === video.HAVE_ENOUGH_DATA) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        const code = jsQR(imageData.data, canvas.width, canvas.height, {
          inversionAttempts: "dontInvert",
        });

        if (code) {
          resultBox.textContent = "✅ Terdeteksi: " + code.data;

          // contoh: stop kamera setelah berhasil
          stopCamera();
        }
      }
    }, 300); // cek tiap 300ms
  } catch (err) {
    alert("Kamera gagal dibuka: " + err.message);
  }
});

// saat modal ditutup -> matikan kamera
document.getElementById('scanModal').addEventListener('hidden.bs.modal', function () {
  stopCamera();
});

function stopCamera() {
  if (stream) {
    stream.getTracks().forEach(track => track.stop());
    stream = null;
  }
  if (scanInterval) {
    clearInterval(scanInterval);
    scanInterval = null;
  }
}
</script>
