<!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, user-scalable=yes">
  <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></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: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      padding: 20px;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    .container {
      max-width: 1400px;
      margin: 0 auto;
    }
    .card {
      border-radius: 20px;
      border: none;
      overflow: hidden;
      box-shadow: 0 20px 35px -10px rgba(0, 0, 0, 0.2);
    }
    .card-header {
      background: linear-gradient(135deg, #3b5998 0%, #4a69bd 100%);
      padding: 15px 20px;
    }
    .card-header-secondary {
      background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    }
    
    #reader {
      width: 100%;
      min-height: 450px;
      border-radius: 12px;
      overflow: hidden;
      background: #000;
      position: relative;
    }
    
    #reader video {
      width: 100% !important;
      height: auto !important;
      min-height: 450px !important;
      object-fit: cover !important;
    }
    
    #reader__scan_region {
      min-height: 450px !important;
    }
    
    #reader__dashboard_section {
      padding: 10px !important;
    }
    
    #reader__dashboard_section button {
      margin: 5px !important;
      padding: 8px 15px !important;
      border-radius: 8px !important;
    }
    
    .scan-info {
      background-color: #e9ecef;
      border-radius: 10px;
      padding: 12px;
      margin-bottom: 15px;
      text-align: center;
    }
    .camera-select {
      margin-bottom: 15px;
    }
    .scanner-active {
      border: 3px solid #28a745 !important;
      box-shadow: 0 0 10px rgba(40,167,69,0.3);
    }
    .scan-result-container {
      max-height: 550px;
      overflow-y: auto;
      border-radius: 12px;
      padding: 15px;
      background-color: #f8f9fa;
    }
    .scan-result-item {
      padding: 15px;
      margin-bottom: 12px;
      border-radius: 12px;
      border-left: 4px solid #007bff;
      transition: all 0.3s ease;
    }
    .scan-result-item.success {
      border-left-color: #28a745;
      background: linear-gradient(135deg, #d4edda 0%, #c8e6d9 100%);
    }
    .scan-result-item.error {
      border-left-color: #dc3545;
      background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
    }
    .scan-result-item.warning {
      border-left-color: #ffc107;
      background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
    }
    .scan-result-item.info {
      border-left-color: #17a2b8;
      background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
    }
    .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;
    }
    .scanner-controls {
      margin-top: 20px;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 12px;
      border: 1px solid #dee2e6;
    }
    .scanner-wrapper {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .scanner-type-selector {
      margin-bottom: 15px;
      padding: 12px;
      background: linear-gradient(135deg, #e9f7fe 0%, #d6eeff 100%);
      border-radius: 12px;
      border: 1px solid #b8e6ff;
      width: 100%;
    }
    .scanner-type-selector .form-check {
      display: inline-block;
      margin-right: 20px;
    }
    .external-scanner-section {
      margin-top: 15px;
      padding: 20px;
      background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
      border-radius: 16px;
      border: 2px dashed #6c757d;
      width: 100%;
    }
    .external-scanner-input {
      font-size: 1.2rem;
      text-align: center;
      letter-spacing: 2px;
      border-radius: 10px;
      padding: 12px;
    }
    .motivation-column {
      background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
      border-radius: 16px;
      padding: 20px;
      box-shadow: 0 10px 25px -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, #1a252f);
      color: #a5f3fc;
      padding: 20px;
      border-radius: 16px;
      margin-bottom: 20px;
      box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    }
    .date-display {
      font-size: 1rem;
      text-align: center;
      margin-top: 8px;
      color: #94a3b8;
    }
    .motivation-title {
      font-size: 1.2rem;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 2px solid #e5e7eb;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .motivation-text {
      font-size: 1.1rem;
      font-weight: 500;
      color: #1e293b;
      line-height: 1.6;
      font-style: italic;
      text-align: center;
      padding: 20px;
      border-left: 4px solid #3b5998;
      background-color: #f1f5f9;
      border-radius: 12px;
      margin-bottom: 20px;
    }
    .motivation-author {
      text-align: right;
      font-style: normal;
      color: #64748b;
      margin-top: 12px;
      font-size: 0.9rem;
    }
    .scan-buttons {
      display: flex;
      gap: 10px;
      justify-content: center;
      flex-wrap: wrap;
    }
    .scan-buttons .btn {
      min-width: 120px;
      padding: 10px 20px;
      font-weight: 600;
    }
    .recent-scans {
      margin-top: 20px;
      max-height: 220px;
      overflow-y: auto;
    }
    .recent-scan-item {
      padding: 10px 12px;
      margin-bottom: 8px;
      background-color: #f8f9fa;
      border-radius: 10px;
      border-left: 3px solid #3b5998;
      font-size: 0.85rem;
    }
    .recent-scan-item.success {
      border-left-color: #28a745;
      background-color: #e8f5e9;
    }
    .recent-scan-item.error {
      border-left-color: #dc3545;
      background-color: #ffebee;
    }
    .scanner-status {
      padding: 10px;
      border-radius: 10px;
      margin-top: 10px;
      text-align: center;
      font-weight: bold;
    }
    .status-active {
      background-color: #d4edda;
      color: #155724;
      border: 1px solid #c3e6cb;
    }
    .status-inactive {
      background-color: #f8d7da;
      color: #721c24;
      border: 1px solid #f5c6cb;
    }
    .status-external {
      background-color: #d1ecf1;
      color: #0c5460;
      border: 1px solid #bee5eb;
    }
    .profile-photo-container {
      display: flex;
      justify-content: center;
      margin-bottom: 15px;
    }
    .profile-photo {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      object-fit: cover;
      border: 4px solid #fff;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .foto-placeholder {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      background-color: #e9ecef;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #6c757d;
      font-size: 2rem;
      border: 4px solid #fff;
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .profile-info {
      text-align: center;
      margin-bottom: 15px;
    }
    .profile-name {
      font-size: 1.2rem;
      font-weight: bold;
      margin-bottom: 5px;
    }
    .badge-siswa {
      background-color: #17a2b8;
      color: white;
      padding: 3px 10px;
      border-radius: 15px;
      font-size: 0.75rem;
      display: inline-block;
    }
    .badge-guru {
      background-color: #28a745;
      color: white;
      padding: 3px 10px;
      border-radius: 15px;
      font-size: 0.75rem;
      display: inline-block;
    }
    .badge-hadir {
      background-color: #28a745;
      color: white;
      padding: 3px 10px;
      border-radius: 15px;
      font-size: 0.8rem;
    }
    .badge-terlambat {
      background-color: #ffc107;
      color: #212529;
      padding: 3px 10px;
      border-radius: 15px;
      font-size: 0.8rem;
    }
    .time-info {
      display: flex;
      justify-content: space-around;
      margin: 15px 0;
      padding: 10px;
      background-color: rgba(0,0,0,0.05);
      border-radius: 10px;
    }
    .time-label {
      font-size: 0.8rem;
      color: #6c757d;
    }
    .time-value {
      font-size: 1rem;
      font-weight: bold;
    }
    .wa-status {
      padding: 8px 12px;
      background-color: #25d366;
      color: white;
      border-radius: 8px;
      margin-top: 10px;
      font-size: 0.85rem;
    }
    .wa-status.error {
      background-color: #dc3545;
    }
    .wa-status.warning {
      background-color: #ffc107;
      color: #212529;
    }
    .scanned-code-display {
      margin-top: 10px;
      padding: 10px;
      background-color: #e8f5e8;
      border-radius: 8px;
      border: 1px solid #c3e6cb;
      font-family: monospace;
      font-size: 1rem;
      text-align: center;
    }
    .login-mode-badge {
      position: absolute;
      top: 15px;
      right: 15px;
      z-index: 10;
    }
    .login-mode-badge .badge {
      font-size: 0.8rem;
      padding: 8px 12px;
    }
    
    .notif-status {
      padding: 10px 15px;
      border-radius: 8px;
      margin-top: 10px;
      font-size: 0.9rem;
    }
    .notif-status.success {
      background-color: #d4edda;
      border: 1px solid #c3e6cb;
      color: #155724;
    }
    .notif-status.error {
      background-color: #f8d7da;
      border: 1px solid #f5c6cb;
      color: #721c24;
    }
    .notif-status.info {
      background-color: #d1ecf1;
      border: 1px solid #bee5eb;
      color: #0c5460;
    }
    .badge-telegram-success {
      background-color: #28a745;
      color: white;
      padding: 2px 8px;
      border-radius: 12px;
      font-size: 0.75rem;
    }
    .badge-telegram-fail {
      background-color: #dc3545;
      color: white;
      padding: 2px 8px;
      border-radius: 12px;
      font-size: 0.75rem;
    }
    .debug-box {
      background: #1a1a2e;
      color: #00ff88;
      padding: 10px;
      border-radius: 8px;
      font-family: monospace;
      font-size: 12px;
      max-height: 200px;
      overflow: auto;
      margin-top: 10px;
    }
    
    @media (max-width: 991px) {
      .motivation-column {
        margin-bottom: 20px;
      }
      #reader, #reader video, #reader__scan_region {
        min-height: 380px !important;
      }
      .digital-clock {
        font-size: 1.8rem;
      }
    }
    @media (max-width: 767px) {
      .scanner-column {
        margin-bottom: 20px;
      }
      #reader, #reader video, #reader__scan_region {
        min-height: 320px !important;
      }
      .digital-clock {
        font-size: 1.5rem;
        padding: 15px;
      }
      .scan-buttons .btn {
        min-width: 100px;
        padding: 8px 15px;
        font-size: 0.9rem;
      }
      .motivation-text {
        font-size: 0.95rem;
        padding: 15px;
      }
    }
    @media (max-width: 480px) {
      #reader, #reader video, #reader__scan_region {
        min-height: 280px !important;
      }
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
      border: none;
    }
    .btn-success {
      background: linear-gradient(135deg, #10b981 0%, #059669 100%);
      border: none;
    }
    .btn-danger {
      background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
      border: none;
    }
    .btn-warning {
      background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
      border: none;
      color: white;
    }
    .btn-info {
      background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
      border: none;
      color: white;
    }
    .btn-telegram {
      background: linear-gradient(135deg, #0088cc 0%, #006699 100%);
      border: none;
      color: white;
    }
    .btn-telegram:hover {
      color: white;
      opacity: 0.9;
    }
    .btn-debug {
      background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
      border: none;
      color: #00ff88;
    }
    .btn-debug:hover {
      color: #00ff88;
      opacity: 0.9;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="card shadow position-relative">
      <!-- Login Mode Badge -->
      <div class="login-mode-badge">
        <span class="badge bg-secondary" id="modeBadge">
          <i class="fas fa-globe"></i> Mode Publik
        </span>
      </div>
      
      <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>
        <a href="index.php" class="btn btn-primary mb-3 ms-2">
          <i class="fas fa-home"></i> Halaman Utama
        </a>
        <button type="button" class="btn btn-info mb-3 ms-2" id="toggleModeBtn">
          <i class="fas fa-exchange-alt"></i> Switch ke Mode Login
        </button>
        <button type="button" class="btn btn-telegram mb-3 ms-2" id="testTelegramBtn">
          <i class="fab fa-telegram"></i> Test Telegram
        </button>
        <button type="button" class="btn btn-debug mb-3 ms-2" id="debugBtn">
          <i class="fas fa-bug"></i> Debug
        </button>

        <div class="row">
          <!-- Kolom kiri untuk jam digital dan motivasi -->
          <div class="col-lg-4 col-md-12 mb-4">
            <div class="motivation-column">
              <div class="digital-clock">
                <div id="clock">--:--:--</div>
                <div class="date-display" id="date">--, -- --- ----</div>
              </div>
              
              <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 class="recent-scans">
                <h6><i class="fas fa-history"></i> Scan Terakhir</h6>
                <div id="recentScansList">
                  <p class="text-muted text-center">Belum ada scan</p>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Kolom tengah untuk scanner -->
          <div class="col-lg-4 col-md-6 scanner-column mb-4">
            <div class="scanner-wrapper">
              <!-- Notification Status -->
              <div id="notifStatusContainer"></div>
              
              <div class="scanner-type-selector">
                <label class="form-label"><strong><i class="fas fa-scanner"></i> Mode Scanner:</strong></label>
                <div class="form-check">
                  <input class="form-check-input" type="radio" name="scannerType" id="webcamScanner" value="webcam">
                  <label class="form-check-label" for="webcamScanner">
                    <i class="fas fa-camera"></i> Kamera
                  </label>
                </div>
                <div class="form-check">
                  <input class="form-check-input" type="radio" name="scannerType" id="externalScanner" value="external" checked>
                  <label class="form-check-label" for="externalScanner">
                    <i class="fas fa-keyboard"></i> Input Manual / Alat Scan
                  </label>
                </div>
              </div>

              <div id="scannerStatus" class="scanner-status status-external">
                <i class="fas fa-keyboard"></i> Mode Input Manual - Masukkan NISN/NIP lalu tekan Enter
              </div>

              <!-- Area Webcam Scanner (default hidden) -->
              <div id="webcam-scanner-section" style="display: none;">
                <div id="reader" class="text-center"></div>
              </div>

              <!-- Area External Scanner (default active) -->
              <div id="external-scanner-section" class="external-scanner-section">
                <div class="text-center mb-3">
                  <i class="fas fa-keyboard fa-3x text-primary mb-2"></i>
                  <h5>Input Manual / Alat Scan Barcode</h5>
                  <p class="text-muted">Masukkan NISN/NIP secara manual atau gunakan alat scan barcode</p>
                </div>
                <div class="mb-3">
                  <input type="text" 
                         id="externalScannerInput" 
                         class="form-control external-scanner-input" 
                         placeholder="Masukkan NISN/NIP (bisa dari alat scan barcode)..." 
                         autocomplete="off"
                         autofocus>
                  <div class="form-text">Masukkan NISN untuk siswa atau NIP untuk guru, lalu tekan Enter. Atau scan barcode menggunakan alat scan.</div>
                </div>
                
                <div id="scannedCodeDisplay" class="scanned-code-display" style="display: none;">
                  <strong>Kode Terakhir:</strong> <span id="lastScannedCode"></span>
                </div>
              </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>Pastikan QR Code dalam kondisi baik dan terlihat jelas</small></p>
                </div>

                <div class="camera-select mb-3" id="cameraSelectSection" style="display: none;">
                  <label for="cameraSelect" class="form-label"><i class="fas fa-camera"></i> Pilih Kamera:</label>
                  <select id="cameraSelect" class="form-select">
                    <option value="">Memuat daftar kamera...</option>
                  </select>
                </div>

                <div class="text-center mb-3">
                  <div class="scan-buttons">
                    <button type="button" class="btn btn-success" id="startScanner" style="display: none;">
                      <i class="fas fa-play"></i> Mulai Scan Kamera
                    </button>
                    <button type="button" class="btn btn-danger" id="stopScanner" disabled style="display: none;">
                      <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>
                
                <!-- Informasi Telegram -->
                <div class="alert alert-info mt-3 mb-0">
                  <i class="fab fa-telegram"></i> <strong>Notifikasi Telegram:</strong> 
                  Setiap absensi akan otomatis dikirim ke Telegram siswa (jika terdaftar) dan admin.
                </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
                </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"></i>
                      <p>Belum ada hasil scan. Silakan input NISN/NIP atau scan QR Code.</p>
                    </div>
                  </div>
                  <!-- Debug Box -->
                  <div id="debugBox" class="debug-box" style="display:none;">
                    <strong>🔍 DEBUG LOG:</strong><br>
                    <div id="debugContent">Menunggu...</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

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

  <script>
    let html5QrCode = null;
    let isScanning = false;
    let currentScannerType = 'external';
    let currentCameraId = '';
    let lastScannedCode = '';
    let recentScans = [];
    let camerasList = [];
    let debugMode = false;
    
    // Mode: 'public' (tanpa login) atau 'login' (dengan login)
    let apiMode = 'public';
    
    // API endpoints
    const API_PUBLIC = 'rekam_absen_public.php';
    const API_LOGIN = 'rekam_absen_wa_api.php';
    
    function getCurrentApiEndpoint() {
      return apiMode === 'public' ? API_PUBLIC : API_LOGIN;
    }

    // Fungsi untuk update jam digital
    function updateClock() {
      const now = new Date();
      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}`;
      
      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}`;
    }

    function updateScannerStatus(message, type = 'info') {
      const statusDiv = document.getElementById('scannerStatus');
      statusDiv.innerHTML = `<i class="fas ${type === 'external' ? 'fa-keyboard' : 'fa-camera'}"></i> ${message}`;
      statusDiv.className = 'scanner-status';
      
      if (type === 'active') statusDiv.classList.add('status-active');
      else if (type === 'inactive') statusDiv.classList.add('status-inactive');
      else if (type === 'external') statusDiv.classList.add('status-external');
    }

    function showScannedCode(code) {
      document.getElementById('scannedCodeDisplay').style.display = 'block';
      document.getElementById('lastScannedCode').textContent = code;
      setTimeout(() => {
        document.getElementById('scannedCodeDisplay').style.display = 'none';
      }, 3000);
    }

    function addToRecentScans(code, status, message, nama, foto) {
      const now = new Date();
      const timeString = now.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
      
      recentScans.unshift({
        code: code, status: status, message: message, nama: nama, foto: foto, time: timeString
      });
      
      if (recentScans.length > 10) recentScans.pop();
      updateRecentScansDisplay();
    }

    function updateRecentScansDisplay() {
      const container = document.getElementById('recentScansList');
      if (recentScans.length === 0) {
        container.innerHTML = '<p class="text-muted text-center">Belum ada scan</p>';
        return;
      }
      
      let html = '';
      recentScans.forEach(scan => {
        const statusClass = scan.status === 'success' ? 'success' : (scan.status === 'error' ? 'error' : 'info');
        html += `
          <div class="recent-scan-item ${statusClass}">
            <div class="d-flex align-items-center justify-content-between">
              <div><strong>${scan.nama || scan.code}</strong><br><small class="text-muted">${scan.time}</small></div>
              <i class="fas ${scan.status === 'success' ? 'fa-check-circle text-success' : 'fa-times-circle text-danger'}"></i>
            </div>
            <div class="small text-truncate mt-1">${scan.message.substring(0, 40)}...</div>
          </div>
        `;
      });
      container.innerHTML = html;
    }

    // Load cameras
    async function loadCameras() {
      try {
        camerasList = await Html5Qrcode.getCameras();
        const select = document.getElementById('cameraSelect');
        
        if (camerasList && camerasList.length > 0) {
          select.innerHTML = camerasList.map((cam, index) => {
            const label = cam.label || `Kamera ${index + 1}`;
            return `<option value="${cam.id}">${label}</option>`;
          }).join('');
          
          const backCamera = camerasList.find(cam => 
            cam.label.toLowerCase().includes('back') || 
            cam.label.toLowerCase().includes('rear') ||
            cam.label.toLowerCase().includes('environment')
          );
          if (backCamera) {
            select.value = backCamera.id;
            currentCameraId = backCamera.id;
          } else {
            currentCameraId = camerasList[0].id;
          }
          updateScannerStatus('Kamera siap. Pilih mode Kamera untuk memulai scan.', 'inactive');
        } else {
          select.innerHTML = '<option value="">Tidak ada kamera ditemukan</option>';
          updateScannerStatus('Tidak ada kamera yang terdeteksi. Gunakan input manual.', 'external');
        }
      } catch (error) {
        console.error('Error loading cameras:', error);
        updateScannerStatus('Error: ' + error.message, 'inactive');
      }
    }

    // Toggle mode antara publik dan login
    function toggleApiMode() {
      if (apiMode === 'public') {
        apiMode = 'login';
        document.getElementById('modeBadge').innerHTML = '<i class="fas fa-lock"></i> Mode Login';
        document.getElementById('modeBadge').className = 'badge bg-warning text-dark';
        document.getElementById('toggleModeBtn').innerHTML = '<i class="fas fa-exchange-alt"></i> Switch ke Mode Publik';
        addResultMessage('Berpindah ke Mode Login (memerlukan akun yang sudah login)', 'info');
        showDebug('Mode berubah ke LOGIN');
      } else {
        apiMode = 'public';
        document.getElementById('modeBadge').innerHTML = '<i class="fas fa-globe"></i> Mode Publik';
        document.getElementById('modeBadge').className = 'badge bg-secondary';
        document.getElementById('toggleModeBtn').innerHTML = '<i class="fas fa-exchange-alt"></i> Switch ke Mode Login';
        addResultMessage('Berpindah ke Mode Publik (tanpa login)', 'info');
        showDebug('Mode berubah ke PUBLIK');
      }
    }

    // Test Telegram
    async function testTelegram() {
      const btn = document.getElementById('testTelegramBtn');
      btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Mengirim...';
      btn.disabled = true;
      
      try {
        const response = await fetch('test_telegram.php');
        const data = await response.json();
        
        if (data.status === 'success') {
          showNotifStatus('✅ ' + data.message, 'success');
        } else {
          showNotifStatus('⚠️ ' + data.message, 'error');
        }
      } catch (error) {
        showNotifStatus('⚠️ Error: ' + error.message, 'error');
      }
      
      btn.innerHTML = '<i class="fab fa-telegram"></i> Test Telegram';
      btn.disabled = false;
    }

    function showNotifStatus(message, type = 'info') {
      const container = document.getElementById('notifStatusContainer');
      const icon = type === 'success' ? 'fa-check-circle' : (type === 'error' ? 'fa-times-circle' : 'fa-info-circle');
      
      container.innerHTML = `
        <div class="notif-status ${type}">
          <i class="fas ${icon}"></i> ${message}
          <button type="button" class="btn-close float-end" onclick="this.parentElement.remove()"></button>
        </div>
      `;
      
      setTimeout(() => {
        container.innerHTML = '';
      }, 10000);
    }

    // Debug functions
    function toggleDebug() {
      debugMode = !debugMode;
      const box = document.getElementById('debugBox');
      box.style.display = debugMode ? 'block' : 'none';
      document.getElementById('debugBtn').innerHTML = debugMode ? 
        '<i class="fas fa-bug"></i> Debug ON' : 
        '<i class="fas fa-bug"></i> Debug';
      showDebug('Debug mode ' + (debugMode ? 'diaktifkan' : 'dinonaktifkan'));
    }

    function showDebug(message) {
      if (!debugMode) return;
      const content = document.getElementById('debugContent');
      const time = new Date().toLocaleTimeString();
      content.innerHTML = `<span style="color:#ff6b6b;">[${time}]</span> ${message}<br>` + content.innerHTML;
      // Batasi jumlah baris
      const lines = content.innerHTML.split('<br>');
      if (lines.length > 50) {
        content.innerHTML = lines.slice(0, 50).join('<br>');
      }
    }

    // Event listeners
    document.querySelectorAll('input[name="scannerType"]').forEach(radio => {
      radio.addEventListener('change', function() {
        currentScannerType = this.value;
        switchToScannerMode(currentScannerType);
      });
    });

    document.getElementById('cameraSelect').addEventListener('change', function() {
      currentCameraId = this.value;
      if (isScanning && currentScannerType === 'webcam') {
        stopScanner();
        setTimeout(() => startScanner(), 500);
      }
    });

    document.getElementById('externalScannerInput').addEventListener('keypress', function(e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        const value = this.value.trim();
        showDebug('Input: ' + value);
        if (value.length >= 6) {
          processQRCode(value);
          this.value = '';
          setTimeout(() => this.focus(), 100);
        } else if (value.length > 0) {
          addResultMessage('NISN/NIP minimal 6 digit!', 'warning');
          this.value = '';
          this.focus();
        }
      }
    });

    document.getElementById('externalScannerInput').focus();

    document.getElementById('startScanner').addEventListener('click', startScanner);
    document.getElementById('stopScanner').addEventListener('click', stopScanner);
    document.getElementById('resetScanner').addEventListener('click', resetScanner);
    document.getElementById('clearResults').addEventListener('click', clearResults);
    document.getElementById('toggleModeBtn').addEventListener('click', toggleApiMode);
    document.getElementById('testTelegramBtn').addEventListener('click', testTelegram);
    document.getElementById('debugBtn').addEventListener('click', toggleDebug);

    function switchToScannerMode(mode) {
      showDebug('Switch ke mode: ' + mode);
      if (mode === 'webcam') {
        document.getElementById('webcam-scanner-section').style.display = 'block';
        document.getElementById('external-scanner-section').style.display = 'none';
        document.getElementById('cameraSelectSection').style.display = 'block';
        document.getElementById('startScanner').style.display = 'inline-block';
        document.getElementById('stopScanner').style.display = 'inline-block';
        updateScannerStatus('Webcam siap. Klik "Mulai Scan Kamera" untuk memulai.', 'inactive');
        if (isScanning) {
          stopScanner();
          setTimeout(startScanner, 500);
        }
      } else {
        document.getElementById('webcam-scanner-section').style.display = 'none';
        document.getElementById('external-scanner-section').style.display = 'block';
        document.getElementById('cameraSelectSection').style.display = 'none';
        document.getElementById('startScanner').style.display = 'none';
        document.getElementById('stopScanner').style.display = 'none';
        if (isScanning) stopScanner();
        setTimeout(() => {
          document.getElementById('externalScannerInput').focus();
        }, 100);
        updateScannerStatus('Mode input manual. Masukkan NISN/NIP lalu tekan Enter. Dukung alat scan barcode.', 'external');
      }
    }

    async function startScanner() {
      if (isScanning || currentScannerType !== 'webcam') return;
      if (!currentCameraId) {
        addResultMessage('Tidak ada kamera yang tersedia. Gunakan input manual.', 'error');
        return;
      }

      try {
        document.getElementById('startScanner').disabled = true;
        document.getElementById('stopScanner').disabled = false;
        
        html5QrCode = new Html5Qrcode("reader");
        
        await html5QrCode.start(
          currentCameraId,
          {
            fps: 15,
            qrbox: { width: 300, height: 300 },
            aspectRatio: 1.0
          },
          onScanSuccess,
          onScanFailure
        );
        
        isScanning = true;
        document.getElementById('reader').classList.add('scanner-active');
        updateScannerStatus('Scanner aktif. Arahkan kamera ke QR Code.', 'active');
        showDebug('Scanner webcam aktif');
        
      } catch (error) {
        console.error("Error:", error);
        let errorMsg = error.message;
        if (errorMsg.includes('NotAllowedError')) errorMsg = 'Izin kamera ditolak. Silakan izinkan akses kamera.';
        else if (errorMsg.includes('NotFoundError')) errorMsg = 'Tidak ada kamera yang terdeteksi.';
        else if (errorMsg.includes('NotReadableError')) errorMsg = 'Kamera sedang digunakan oleh aplikasi lain.';
        
        addResultMessage('Error: ' + errorMsg, 'error');
        updateScannerStatus('Error: ' + errorMsg, 'inactive');
        document.getElementById('startScanner').disabled = false;
        document.getElementById('stopScanner').disabled = true;
      }
    }

    async function stopScanner() {
      if (!isScanning || currentScannerType !== 'webcam') return;
      
      try {
        if (html5QrCode) {
          await html5QrCode.stop();
          await html5QrCode.clear();
        }
        document.getElementById('reader').classList.remove('scanner-active');
        document.getElementById('startScanner').disabled = false;
        document.getElementById('stopScanner').disabled = true;
        isScanning = false;
        updateScannerStatus('Scanner dihentikan.', 'inactive');
        showDebug('Scanner dihentikan');
      } catch (error) {
        console.error("Error:", error);
      }
    }

    function resetScanner() {
      showDebug('Reset scanner');
      if (currentScannerType === 'webcam') {
        stopScanner();
        document.getElementById('externalScannerInput').value = '';
      } else {
        document.getElementById('externalScannerInput').value = '';
        document.getElementById('externalScannerInput').focus();
      }
      clearResults();
      updateScannerStatus('Scanner direset. ' + (currentScannerType === 'webcam' ? 'Klik Mulai Scan' : 'Masukkan NISN/NIP'), currentScannerType === 'webcam' ? 'inactive' : 'external');
    }

    function clearResults() {
      document.getElementById("result").innerHTML = `
        <div class="text-center text-muted">
          <i class="fas fa-qrcode result-icon"></i>
          <p>Belum ada hasil scan. Silakan input NISN/NIP atau scan QR Code.</p>
        </div>
      `;
      document.getElementById('debugContent').innerHTML = 'Menunggu...';
    }

    function processQRCode(qrMessage) {
      showDebug('QR Code: ' + qrMessage + ', Mode: ' + apiMode);
      lastScannedCode = qrMessage;
      
      if (currentScannerType === 'webcam') showScannedCode(qrMessage);
      
      if (!/^\d+$/.test(qrMessage)) {
        addResultMessage('QR Code tidak valid. Harus berisi angka saja.', 'error');
        addToRecentScans(qrMessage, 'error', 'QR Code tidak valid', '', '');
        playBeepSound();
        return;
      }
      
      document.getElementById("result").innerHTML = `
        <div class="scan-result-item info">
          <div class="profile-photo-container"><div class="foto-placeholder"><i class="fas fa-spinner fa-spin"></i></div></div>
          <div class="result-title">Memproses...</div>
          <div class="result-message">Memproses absensi untuk kode: <strong>${qrMessage}</strong><br>Mode: ${apiMode === 'public' ? 'Publik (tanpa login)' : 'Login (memerlukan akun)'}</div>
        </div>
      `;
      
      const apiEndpoint = getCurrentApiEndpoint();
      showDebug('Memanggil API: ' + apiEndpoint);
      
      fetch(apiEndpoint + '?code=' + encodeURIComponent(qrMessage))
        .then(response => {
          showDebug('Response status: ' + response.status);
          const contentType = response.headers.get('content-type');
          if (contentType && contentType.includes('text/html')) {
            return response.text().then(text => {
              showDebug('Response HTML: ' + text.substring(0, 200));
              if (text.includes('Unauthorized')) {
                throw new Error('Anda belum login. Silakan login terlebih dahulu atau gunakan Mode Publik.');
              }
              throw new Error('Server error: ' + text.substring(0, 200));
            });
          }
          return response.json();
        })
        .then(data => {
          showDebug('Data response: ' + JSON.stringify(data));
          if (data.status && data.message) {
            addResultWithPhoto(data, qrMessage);
            addToRecentScans(qrMessage, data.status, data.message, data.nama || '', data.foto || '');
            
            if (data.message.includes('Telegram berhasil')) {
              showNotifStatus('📨 Notifikasi Telegram berhasil dikirim!', 'success');
              showDebug('✅ Telegram berhasil dikirim');
            } else if (data.message.includes('Telegram')) {
              showDebug('⚠️ Telegram: ' + data.message.match(/Telegram[^|]*/)?.[0]);
            }
          } else if (data.status === 'error' && data.message === 'Unauthorized') {
            addResultMessage('❌ Anda belum login. Silakan login terlebih dahulu atau gunakan Mode Publik', 'error');
            addToRecentScans(qrMessage, 'error', 'Unauthorized - Silakan login', '', '');
            showDebug('❌ Unauthorized - Silakan login');
          } else {
            addResultMessage('Response tidak valid', 'error');
            showDebug('❌ Response tidak valid: ' + JSON.stringify(data));
          }
          playBeepSound();
        })
        .catch(error => {
          console.error('Error:', error);
          showDebug('❌ Error: ' + error.message);
          addResultMessage('Error: ' + error.message, 'error');
          addToRecentScans(qrMessage, 'error', error.message, '', '');
          playBeepSound();
        });
    }

    function addResultWithPhoto(data, code = '') {
      let badgeClass = data.status === 'success' ? 'success' : (data.status === 'warning' ? 'warning' : (data.status === 'error' ? 'error' : 'info'));
      let title = data.status === 'success' ? '✅ Absensi Berhasil' : (data.status === 'warning' ? '⚠️ Peringatan' : '❌ Gagal');
      
      const typeBadge = data.tipe === 'siswa' ? '<span class="badge-siswa"><i class="fas fa-user-graduate"></i> Siswa</span>' : 
                        (data.tipe === 'guru' ? '<span class="badge-guru"><i class="fas fa-chalkboard-teacher"></i> Guru</span>' : '');
      
      let statusBadge = '';
      if (data.status_kehadiran) {
        if (data.status_kehadiran.includes('Tepat')) statusBadge = '<span class="badge-hadir ms-2"><i class="fas fa-clock"></i> Tepat Waktu</span>';
        else if (data.status_kehadiran.includes('Terlambat')) statusBadge = '<span class="badge-terlambat ms-2"><i class="fas fa-clock"></i> Terlambat</span>';
      }
      
      let timeInfoHtml = '';
      if (data.jam_masuk && data.jam_pulang) {
        timeInfoHtml = `<div class="time-info"><div class="time-item"><div class="time-label">Masuk</div><div class="time-value">${data.jam_masuk}</div></div><div class="time-item"><div class="time-label">Pulang</div><div class="time-value">${data.jam_pulang}</div></div></div>`;
      } else if (data.jam) {
        timeInfoHtml = `<div class="time-info"><div class="time-item"><div class="time-label">Jam Absen</div><div class="time-value">${data.jam}</div></div></div>`;
      }
      
      let fotoHtml = (data.foto && data.foto !== 'assets/images/default-avatar.png') ? 
        `<img src="${data.foto}" class="profile-photo" onerror="this.src='data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 24 24%27 fill=%27%236c757d%27%3E%3Cpath d=%27M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z%27/%3E%3C/svg%3E';">` :
        `<div class="foto-placeholder"><i class="fas fa-user"></i></div>`;
      
      let modeInfo = apiMode === 'public' ? '<div class="small text-muted mt-2"><i class="fas fa-globe"></i> Mode Publik</div>' : '';
      
      // Ekstrak status notifikasi Telegram dari message
      let telegramStatus = '';
      if (data.message) {
        const adminMatch = data.message.match(/Admin:\s*(✅[^|]*)/);
        const siswaMatch = data.message.match(/Siswa:\s*(✅[^|]*)/);
        if (adminMatch || siswaMatch) {
          telegramStatus = '<div class="mt-2">';
          if (adminMatch) telegramStatus += `<span class="badge-telegram-success"><i class="fab fa-telegram"></i> Admin: ${adminMatch[1].trim()}</span> `;
          if (siswaMatch) telegramStatus += `<span class="badge-telegram-success"><i class="fab fa-telegram"></i> Siswa: ${siswaMatch[1].trim()}</span>`;
          telegramStatus += '</div>';
        }
      }
      
      // Debug info
      let debugInfo = '';
      if (data.debug) {
        debugInfo = `<div class="mt-2 small text-muted">
          <i class="fas fa-code"></i> Debug: 
          Telegram ID: ${data.debug.telegram_id || 'KOSONG'}, 
          No WA: ${data.debug.no_wa || 'KOSONG'}
        </div>`;
      }
      
      document.getElementById("result").innerHTML = `
        <div class="scan-result-item ${badgeClass}">
          <div class="profile-photo-container">${fotoHtml}</div>
          <div class="profile-info">
            <div class="profile-name">${data.nama || 'Tidak diketahui'}</div>
            <div>${typeBadge} ${statusBadge}</div>
            ${data.kelas ? `<div class="profile-details mt-1">Kelas: ${data.kelas}</div>` : ''}
          </div>
          ${timeInfoHtml}
          <div class="result-message">${data.message.replace(/\n/g, '<br>')}</div>
          ${telegramStatus}
          ${debugInfo}
          ${modeInfo}
          <div class="result-time mt-2"><small><i class="far fa-clock"></i> ${new Date().toLocaleTimeString()}</small></div>
        </div>
      `;
    }

    function addResultMessage(message, type = 'info', code = '') {
      let icon = type === 'success' ? 'fa-check-circle' : (type === 'warning' ? 'fa-exclamation-triangle' : (type === 'error' ? 'fa-times-circle' : 'fa-info-circle'));
      let title = type === 'success' ? 'Berhasil' : (type === 'warning' ? 'Peringatan' : (type === 'error' ? 'Gagal' : 'Informasi'));
      
      let modeInfo = apiMode === 'public' ? '<div class="small text-muted mt-2"><i class="fas fa-globe"></i> Mode Publik</div>' : '';
      
      document.getElementById("result").innerHTML = `
        <div class="scan-result-item ${type}">
          <div class="result-icon"><i class="fas ${icon}"></i></div>
          <div class="result-title">${title}</div>
          <div class="result-message">${message.replace(/\n/g, '<br>')}</div>
          ${code ? `<div class="result-details mt-3">Kode: <strong>${code}</strong></div>` : ''}
          ${modeInfo}
          <div class="result-time mt-2"><small>Waktu: ${new Date().toLocaleTimeString()}</small></div>
        </div>
      `;
    }

    function onScanSuccess(qrMessage) {
      processQRCode(qrMessage);
    }

    function onScanFailure(error) {
      if (!error.includes('NotFoundException')) {
        console.log("Scan error:", error);
      }
    }

    function playBeepSound() {
      const beep = document.getElementById("beepSound");
      if (beep) beep.play().catch(e => console.log("Beep error:", e));
    }

    // ============================================
    // INISIALISASI
    // ============================================
    document.addEventListener('DOMContentLoaded', async function() {
      updateClock();
      setInterval(updateClock, 1000);
      await loadCameras();
      switchToScannerMode('external');
      updateRecentScansDisplay();
      
      showNotifStatus('📨 Notifikasi Telegram aktif untuk siswa dan admin', 'info');
      showDebug('Sistem siap, mode: ' + apiMode);
    });

    document.addEventListener('visibilitychange', function() {
      if (document.hidden && isScanning) stopScanner();
    });
  </script>
</body>
</html>