<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Sistem Absensi Digital</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/html5-qrcode"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {
      background-color: #f8f9fa;
      padding: 20px;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .container {
      max-width: 1400px;
      margin: 0 auto;
    }
    #reader {
      width: 100%;
      max-width: 500px;
      border: 2px solid #007bff;
      border-radius: 10px;
      overflow: hidden;
      margin: 0 auto;
    }
    .scan-info {
      background-color: #e9ecef;
      border-radius: 5px;
      padding: 10px;
      margin-bottom: 15px;
      text-align: center;
    }
    .camera-select {
      margin-bottom: 15px;
    }
    .scanner-active {
      border: 3px solid #28a745 !important;
    }
    .scan-result-container {
      max-height: 500px;
      overflow-y: auto;
      border: 1px solid #dee2e6;
      border-radius: 5px;
      padding: 15px;
      background-color: #f8f9fa;
    }
    .scan-result-item {
      padding: 15px;
      margin-bottom: 10px;
      border-radius: 8px;
      border-left: 4px solid #007bff;
    }
    .scan-result-item.success {
      border-left-color: #28a745;
      background-color: #d4edda;
    }
    .scan-result-item.error {
      border-left-color: #dc3545;
      background-color: #f8d7da;
    }
    .scan-result-item.warning {
      border-left-color: #ffc107;
      background-color: #fff3cd;
    }
    .scan-result-item.info {
      border-left-color: #17a2b8;
      background-color: #d1ecf1;
    }
    .scanner-column {
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .single-result {
      text-align: center;
      padding: 20px;
    }
    .result-icon {
      font-size: 3rem;
      margin-bottom: 15px;
    }
    .result-title {
      font-size: 1.5rem;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .result-details {
      margin-top: 15px;
      padding: 10px;
      background-color: rgba(255, 255, 255, 0.7);
      border-radius: 5px;
    }
    .scanner-controls {
      margin-top: 20px;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #dee2e6;
    }
    .scanner-wrapper {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    /* New styles for motivation and clock */
    .motivation-column {
      background-color: #fff;
      border-radius: 8px;
      padding: 15px;
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
      height: 100%;
      display: flex;
      flex-direction: column;
    }
    .digital-clock {
      font-family: 'Courier New', monospace;
      font-size: 2.2rem;
      font-weight: bold;
      text-align: center;
      background: linear-gradient(135deg, #2c3e50, #4a6491);
      color: #ecf0f1;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .date-display {
      font-size: 1.1rem;
      text-align: center;
      margin-top: 5px;
      color: #bdc3c7;
    }
    .motivation-title {
      font-size: 1.2rem;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 2px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .motivation-text {
      font-size: 1.3rem;
      font-weight: bold;
      color: #2c3e50;
      line-height: 1.6;
      font-style: italic;
      text-align: center;
      padding: 20px;
      border-left: 4px solid #3498db;
      background-color: #f8f9fa;
      border-radius: 8px;
      margin-bottom: 20px;
    }
    .motivation-author {
      text-align: right;
      font-style: normal;
      color: #7f8c8d;
      margin-top: 15px;
      font-size: 1rem;
    }
    .scan-buttons {
      display: flex;
      gap: 10px;
      justify-content: center;
      flex-wrap: wrap;
    }
    .scan-buttons .btn {
      min-width: 120px;
    }
    .card-header {
      background-color: #3b5998 !important;
    }
    .card-header-secondary {
      background-color: #6c757d !important;
    }
    /* Alignment improvements */
    .row {
      align-items: stretch;
    }
    .motivation-column, .scanner-column, .result-column {
      display: flex;
      flex-direction: column;
    }
    .scanner-column .scanner-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    .scanner-column .scanner-controls {
      margin-top: auto;
    }
    .status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }
    @media (max-width: 1199px) {
      .digital-clock {
        font-size: 2rem;
      }
    }
    @media (max-width: 991px) {
      .motivation-column {
        margin-bottom: 20px;
      }
      .digital-clock {
        font-size: 1.8rem;
      }
    }
    @media (max-width: 767px) {
      .scanner-column {
        margin-bottom: 20px;
      }
      .digital-clock {
        font-size: 1.6rem;
      }
      .scan-buttons {
        flex-direction: column;
        align-items: center;
      }
      .scan-buttons .btn {
        width: 100%;
        max-width: 200px;
      }
      .motivation-text {
        font-size: 1.1rem;
        padding: 15px;
      }
    }
  </style>
</head>
<body class="container mt-4">
  <div class="card shadow">
    <div class="card-header text-white">
      <h2 class="mb-0"><i class="fas fa-qrcode"></i> Sistem Absensi Digital</h2>
    </div>
    <div class="card-body">
      <a href="dashboard.php" class="btn btn-secondary mb-3"><i class="fas fa-arrow-left"></i> Kembali</a>

      <div class="row">
        <!-- Kolom kiri untuk jam digital dan motivasi -->
        <div class="col-lg-4 col-md-12 mb-4">
          <div class="motivation-column">
            <!-- Jam Digital -->
            <div class="digital-clock">
              <div id="clock">02:00:39</div>
              <div class="date-display" id="date">Kamis, 4 September 2025</div>
            </div>
            
            <!-- Pesan Motivasi -->
            <h4 class="motivation-title">
              <span><i class="fas fa-lightbulb"></i> Kata Motivasi</span>
            </h4>
            <div class="motivation-text">
              "Belajar tanpa disiplin hanyalah rutinitas, mengajar tanpa disiplin hanyalah formalitas. Dengan disiplin, keduanya menjadi bermakna."
              <div class="motivation-author">- Filosofi Pendidikan</div>
            </div>
          </div>
        </div>
        
        <!-- Kolom tengah untuk scanner -->
        <div class="col-lg-4 col-md-6 scanner-column mb-4">
          <div class="scanner-wrapper">
            <div id="reader" class="text-center"></div>
            
            <!-- Kontrol scanner dipindahkan ke bawah kamera -->
            <div class="scanner-controls w-100">
              <div class="scan-info">
                <p><strong>Mode Scan:</strong> QR Code Siswa (NISN) & Guru (NIP)</p>
                <p class="text-muted"><small>Pastikan QR Code dalam kondisi baik dan terlihat jelas oleh kamera</small></p>
              </div>

              <div class="camera-select mb-3">
                <label for="cameraSelect" class="form-label"><i class="fas fa-camera"></i> Pilih Kamera:</label>
                <select id="cameraSelect" class="form-select">
                  <option value="default" selected>Sony Visual Communication Camera (05ca:183d)</option>
                  <option value="front">Kamera Depan</option>
                  <option value="back">Kamera Belakang</option>
                </select>
              </div>

              <div class="text-center mb-3">
                <div class="scan-buttons">
                  <button type="button" class="btn btn-success" id="startScanner">
                    <i class="fas fa-play"></i> Mulai Scan
                  </button>
                  <button type="button" class="btn btn-danger" id="stopScanner" disabled>
                    <i class="fas fa-stop"></i> Stop Scan
                  </button>
                  <button type="button" class="btn btn-warning" id="resetScanner">
                    <i class="fas fa-redo"></i> Reset
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Kolom kanan untuk hasil scan -->
        <div class="col-lg-4 col-md-6 result-column">
          <div class="card h-100">
            <div class="card-header text-white card-header-secondary d-flex justify-content-between align-items-center">
              <h4 class="mb-0"><i class="fas fa-check-circle"></i> Status Absensi Terbaru</h4>
              <button type="button" class="btn btn-sm btn-outline-light" id="clearResults">
                <i class="fas fa-trash"></i> Hapus Status
              </button>
            </div>
            <div class="card-body p-0">
              <div class="scan-result-container">
                <div id="result" class="single-result">
                  <div class="scan-result-item error">
                    <div class="result-icon text-error">
                      <i class="fas fa-times-circle"></i>
                    </div>
                    <div class="result-title">Error</div>
                    <div class="result-message">QR Code tidak valid atau data tidak ditemukan</div>
                    <div class="result-details mt-3">Kode: <strong>9876543210</strong></div>
                    <div class="result-time mt-2"><small>Waktu: 02:00:10</small></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Suara beep -->
      <audio id="beepSound" preload="auto">
        <source src="beep.mp3" type="audio/mpeg">
      </audio>
    </div>
  </div>

  <script>
    let html5QrcodeScanner = null;
    let isScanning = false;
    let currentCameraId = '';

    // Fungsi untuk update jam digital
    function updateClock() {
      const now = new Date();
      
      // Format waktu
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
      
      // Format tanggal
      const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
      const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
      
      const day = days[now.getDay()];
      const date = now.getDate();
      const month = months[now.getMonth()];
      const year = now.getFullYear();
      
      document.getElementById('date').textContent = `${day}, ${date} ${month} ${year}`;
    }

    // Event listener untuk perubahan kamera
    document.getElementById('cameraSelect').addEventListener('change', function() {
      if (isScanning) {
        stopScanner();
        setTimeout(startScanner, 500);
      }
    });

    document.getElementById('startScanner').addEventListener('click', startScanner);
    document.getElementById('stopScanner').addEventListener('click', stopScanner);
    document.getElementById('resetScanner').addEventListener('click', resetScanner);
    document.getElementById('clearResults').addEventListener('click', clearResults);

    async function startScanner() {
      if (isScanning) return;

      try {
        document.getElementById('reader').innerHTML = '';
        document.getElementById('startScanner').disabled = true;
        document.getElementById('stopScanner').disabled = false;
        document.getElementById('resetScanner').disabled = false;
        
        html5QrcodeScanner = new Html5QrcodeScanner(
          "reader",
          { 
            fps: 10, 
            qrbox: { 
              width: 250, 
              height: 250 
            }
          },
          false
        );
        
        await html5QrcodeScanner.render(onScanSuccess, onScanFailure);
        isScanning = true;
        
        document.getElementById('reader').classList.add('scanner-active');
        
        addResultMessage('Scanner aktif. Arahkan kamera ke QR Code.', 'info');
        
      } catch (error) {
        console.error("Error memulai scanner:", error);
        addResultMessage('Error memulai scanner: ' + error.message, 'error');
      }
    }

    async function stopScanner() {
      if (!isScanning) return;
      
      try {
        if (html5QrcodeScanner) {
          await html5QrcodeScanner.clear();
        }
        document.getElementById('reader').classList.remove('scanner-active');
        document.getElementById('startScanner').disabled = false;
        document.getElementById('stopScanner').disabled = true;
        isScanning = false;
        
        addResultMessage('Scanner dihentikan.', 'warning');
      } catch (error) {
        console.error("Error menghentikan scanner:", error);
      }
    }

    function resetScanner() {
      stopScanner();
      clearResults();
      setTimeout(() => {
        document.getElementById('startScanner').disabled = false;
        document.getElementById('stopScanner').disabled = true;
        document.getElementById('resetScanner').disabled = true;
      }, 500);
    }

    function clearResults() {
      const resultDiv = document.getElementById("result");
      resultDiv.innerHTML = `
        <div class="text-center text-muted">
          <i class="fas fa-qrcode result-icon"></i>
          <p>Belum ada hasil scan. Silakan scan QR Code untuk melakukan absensi.</p>
        </div>
      `;
    }

    function onScanSuccess(qrMessage) {
      console.log("QR Code terdeteksi:", qrMessage);
      
      // Cek dulu format kode (harus numeric)
      if (!/^\d+$/.test(qrMessage)) {
        addResultMessage('QR Code tidak valid. Harus berisi angka saja.', 'error');
        playBeepSound();
        return;
      }
      
      // Kirim ke endpoint rekam_absen_wa_api.php untuk proses absensi
      fetch('rekam_absen_wa_api.php?code=' + encodeURIComponent(qrMessage))
        .then(response => {
          // Cek jika response adalah HTML (error)
          const contentType = response.headers.get('content-type');
          if (contentType && contentType.includes('text/html')) {
            return response.text().then(text => {
              throw new Error('Server mengembalikan HTML bukan JSON. Mungkin ada error PHP.');
            });
          }
          return response.json();
        })
        .then(data => {
          if (data.status && data.message) {
            addResultMessage(data.message, data.status, qrMessage);
          } else {
            addResultMessage('Response tidak valid dari server: ' + JSON.stringify(data), 'error');
          }
          playBeepSound();
        })
        .catch(error => {
          console.error('Error:', error);
          addResultMessage('Error: ' + error.message, 'error');
          playBeepSound();
        });
    }

    function onScanFailure(error) {
      // Abaikan error scan yang umum terjadi
      if (!error.includes('NotFoundException')) {
        console.log("Scan attempt:", error);
      }
    }

    function addResultMessage(message, type = 'info', code = '') {
      const result = document.getElementById("result");
      
      let icon = 'fa-info-circle';
      let title = 'Informasi';
      
      switch(type) {
        case 'success':
          icon = 'fa-check-circle';
          title = 'Absensi Berhasil';
          break;
        case 'warning':
          icon = 'fa-exclamation-triangle';
          title = 'Peringatan';
          break;
        case 'error':
          icon = 'fa-times-circle';
          title = 'Error';
          break;
        default:
          icon = 'fa-info-circle';
          title = 'Informasi';
      }
      
      result.innerHTML = `
        <div class="scan-result-item ${type}">
          <div class="result-icon text-${type}">
            <i class="fas ${icon}"></i>
          </div>
          <div class="result-title">${title}</div>
          <div class="result-message">${message}</div>
          ${code ? `<div class="result-details mt-3">Kode: <strong>${code}</strong></div>` : ''}
          <div class="result-time mt-2"><small>Waktu: ${new Date().toLocaleTimeString()}</small></div>
        </div>
      `;
    }

    function playBeepSound() {
      const beepSound = document.getElementById("beepSound");
      if (beepSound) {
        beepSound.play().catch(e => console.log("Error memainkan suara:", e));
      }
    }

    // Inisialisasi saat halaman dimuat
    document.addEventListener('DOMContentLoaded', function() {
      // Mulai jam digital
      updateClock();
      setInterval(updateClock, 1000);
    });
  </script>
</body>
</html>