<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'wali_kelas') {
    header("Location: index.php");
    exit;
}

// Ambil kelas yang diampu oleh wali kelas
include 'config.php';
$username = $_SESSION['username'];
$wali_kelas = mysqli_fetch_assoc(mysqli_query($conn, "SELECT kelas FROM wali_kelas WHERE nip_wali='$username' LIMIT 1"));
$kelas_diampu = $wali_kelas['kelas'] ?? '';
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scan QR - Wali Kelas</title>
  <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 #198754;
      border-radius: 10px;
      overflow: hidden;
      margin: 0 auto;
    }
    .scan-info {
      background-color: #e9ecef;
      border-radius: 5px;
      padding: 10px;
      margin-bottom: 15px;
      text-align: center;
    }
    .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 #198754;
    }
    .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;
    }
    .kelas-info {
      background: linear-gradient(135deg, #198754, #146c43);
      color: white;
      padding: 10px 15px;
      border-radius: 8px;
      margin-bottom: 15px;
      text-align: center;
    }
    .scan-buttons {
      display: flex;
      gap: 10px;
      justify-content: center;
      flex-wrap: wrap;
    }
    .scan-buttons .btn {
      min-width: 120px;
    }
    .card-header {
      background: linear-gradient(135deg, #198754, #146c43) !important;
    }
    .card-header-secondary {
      background-color: #6c757d !important;
    }
    .access-info {
      background: linear-gradient(135deg, #0dcaf0, #0aa2c0);
      color: white;
      padding: 10px 15px;
      border-radius: 8px;
      margin-bottom: 15px;
      text-align: center;
    }
    @media (max-width: 767px) {
      .scan-buttons {
        flex-direction: column;
        align-items: center;
      }
      .scan-buttons .btn {
        width: 100%;
        max-width: 200px;
      }
    }
  </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> Scan QR - Wali Kelas</h2>
    </div>
    <div class="card-body">
      <a href="dashboard_wali_kelas.php" class="btn btn-secondary mb-3"><i class="fas fa-arrow-left"></i> Kembali ke Dashboard</a>

      <?php if($kelas_diampu): ?>
      <div class="kelas-info">
        <h5 class="mb-0"><i class="fas fa-chalkboard-teacher"></i> Kelas yang Diampu: <?php echo $kelas_diampu; ?></h5>
      </div>
      <?php endif; ?>

      <div class="access-info">
        <h6 class="mb-0"><i class="fas fa-info-circle"></i> Akses: Dapat melakukan absensi untuk seluruh siswa</h6>
      </div>

      <div class="row">
        <!-- Kolom kiri untuk scanner -->
        <div class="col-lg-6 col-md-12 scanner-column mb-4">
          <div class="scanner-wrapper">
            <div id="reader" class="text-center"></div>
            
            <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>Scan QR Code untuk melakukan absensi. Notifikasi WA akan otomatis dikirim ke orang tua.</small></p>
              </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-6 col-md-12 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="text-center text-muted">
                    <i class="fas fa-qrcode result-icon" style="font-size: 4rem;"></i>
                    <p>Belum ada hasil scan. Silakan scan QR Code untuk melakukan absensi.</p>
                    <small>Notifikasi WhatsApp akan otomatis dikirim ke orang tua/wali murid.</small>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Informasi tambahan -->
      <div class="row mt-4">
        <div class="col-12">
          <div class="alert alert-info">
            <h5><i class="fas fa-info-circle"></i> Petunjuk Penggunaan:</h5>
            <ul class="mb-0">
              <li>Scan QR Code siswa/guru untuk mencatat kehadiran</li>
              <li>Sistem akan otomatis mengirim notifikasi WhatsApp ke orang tua</li>
              <li>Absensi masuk: Siswa akan tercatat sebagai "Hadir"</li>
              <li>Absensi pulang: Siswa akan tercatat waktu pulang</li>
              <li><strong>Akses Wali Kelas:</strong> Dapat melakukan absensi untuk seluruh siswa</li>
              <li>Pastikan QR Code dalam kondisi baik dan terlihat jelas</li>
            </ul>
          </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;

    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" style="font-size: 4rem;"></i>
          <p>Belum ada hasil scan. Silakan scan QR Code untuk melakukan absensi.</p>
          <small>Notifikasi WhatsApp akan otomatis dikirim ke orang tua/wali murid.</small>
        </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 (NISN/NIP).', '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.replace(/<br>/g, '\n')}</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() {
      // Auto start scanner setelah 1 detik
      setTimeout(startScanner, 1000);
    });
  </script>
</body>
</html>