<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aplikasi Absen Otomatis - PHP Version</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcode.js/1.4.4/qrcode.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        .header h1 { font-size: 28px; margin-bottom: 10px; }
        .header p { font-size: 14px; opacity: 0.9; }
        .tabs { display: flex; border-bottom: 2px solid #eee; background: #f8f9fa; }
        .tab-button {
            flex: 1;
            padding: 15px 20px;
            border: none;
            background: none;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            color: #666;
            transition: all 0.3s;
        }
        .tab-button:hover { background: #e9ecef; color: #667eea; }
        .tab-button.active { color: #667eea; border-bottom: 3px solid #667eea; background: white; margin-bottom: -2px; }
        .tab-content { display: none; padding: 40px 20px; }
        .tab-content.active { display: block; }
        .qr-container { text-align: center; }
        #qrcode { display: inline-block; padding: 20px; background: white; border: 2px solid #667eea; border-radius: 10px; margin: 20px 0; }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; font-weight: 500; color: #333; }
        select, input { width: 100%; padding: 12px; border: 2px solid #eee; border-radius: 8px; font-size: 16px; }
        select:focus, input:focus { outline: none; border-color: #667eea; }
        button { width: 100%; padding: 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; margin-top: 10px; }
        button:hover { transform: translateY(-2px); box-shadow: 0 5px 20px rgba(102,126,234,0.4); }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
        th { background: #f8f9fa; font-weight: 600; }
        .status { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status.masuk { background: #d4edda; color: #155724; }
        .status.keluar { background: #cfe2ff; color: #084298; }
        .message { padding: 15px; border-radius: 8px; margin: 20px 0; text-align: center; font-weight: 500; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info-box { background: #e7f3ff; border-left: 4px solid #2196F3; padding: 15px; border-radius: 5px; margin: 20px 0; color: #0c5aa0; }
        .download-buttons { display: flex; gap: 10px; margin-top: 20px; }
        .download-buttons a { flex: 1; padding: 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; text-decoration: none; text-align: center; font-weight: 600; cursor: pointer; }
        .download-buttons a:hover { transform: translateY(-2px); }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📱 Sistem Absen Otomatis - PHP</h1>
            <p>QR Code Dinamis | Database Terintegrasi | Versi PHP</p>
        </div>

        <div class="tabs">
            <button class="tab-button active" onclick="switchTab('qr')">🔍 QR Scanner</button>
            <button class="tab-button" onclick="switchTab('form')">✍️ Form Absen</button>
            <button class="tab-button" onclick="switchTab('history')">📋 Riwayat</button>
        </div>

        <!-- TAB 1: QR Scanner -->
        <div id="qr" class="tab-content active">
            <div class="qr-container">
                <h2>📊 QR Code untuk Guru</h2>
                <p style="color: #666; margin: 15px 0;">Scan QR ini dengan aplikasi siswa (refresh otomatis setiap 20 detik)</p>
                <div id="qrcode"></div>
                <div class="info-box">
                    <strong>⏱️ Session ID:</strong> <span id="sessionId">Loading...</span><br>
                    <strong>🔄 Update:</strong> <span id="qrTimer">20s</span>
                </div>
            </div>
        </div>

        <!-- TAB 2: Form Absen -->
        <div id="form" class="tab-content">
            <h2>✍️ Form Absen Siswa</h2>
            <div class="form-group">
                <label for="nama">Nama Siswa</label>
                <select id="nama" required></select>
            </div>
            <div class="form-group">
                <label for="kelas">Kelas</label>
                <input type="text" id="kelas" readonly style="background: #f8f9fa;">
            </div>
            <button onclick="submitAbsen()">Kirim Absen</button>
            <div id="formMessage"></div>
        </div>

        <!-- TAB 3: Riwayat -->
        <div id="history" class="tab-content">
            <h2>📋 Riwayat Absen Hari Ini</h2>
            <div class="info-box">
                Auto-refresh setiap 3 detik • <span id="lastUpdate">-</span>
            </div>
            <div style="overflow-x: auto;">
                <table>
                    <thead>
                        <tr><th>No</th><th>Nama</th><th>Kelas</th><th>Status</th><th>Jam</th></tr>
                    </thead>
                    <tbody id="historyTable">
                        <tr><td colspan="5" style="text-align: center; color: #999;">Loading...</td></tr>
                    </tbody>
                </table>
            </div>
            <div class="download-buttons">
                <a href="api/download-csv.php">📥 Download CSV</a>
                <a href="api/download-excel.php">📊 Download Excel</a>
            </div>
        </div>
    </div>

    <script>
        let sessionId = '';
        let students = [];

        document.addEventListener('DOMContentLoaded', function() {
            loadStudents();
            generateQR();
            setInterval(generateQR, 20000);
            setInterval(loadHistory, 3000);
            setInterval(updateQRTimer, 1000);
            loadHistory();
        });

        function switchTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
            document.querySelectorAll('.tab-button').forEach(el => el.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');
        }

        function generateQR() {
            sessionId = 'SESSION_' + Math.random().toString(36).substr(2, 9).toUpperCase();
            const data = JSON.stringify({
                sessionId: sessionId,
                timestamp: new Date().getTime(),
                appName: 'ABSEN_SISTEM'
            });

            document.getElementById('qrcode').innerHTML = '';
            new QRCode(document.getElementById('qrcode'), {
                text: data,
                width: 300,
                height: 300,
                colorDark: '#667eea',
                colorLight: '#ffffff'
            });

            document.getElementById('sessionId').textContent = sessionId;
            document.getElementById('qrTimer').textContent = '20s';
        }

        let qrSeconds = 20;
        function updateQRTimer() {
            qrSeconds--;
            if (qrSeconds < 0) qrSeconds = 20;
            document.getElementById('qrTimer').textContent = qrSeconds + 's';
        }

        async function loadStudents() {
            try {
                const response = await fetch('api/get-students.php');
                students = await response.json();
                populateStudentSelect();
            } catch (error) {
                console.error('Error:', error);
            }
        }

        function populateStudentSelect() {
            const select = document.getElementById('nama');
            select.innerHTML = '<option value="">-- Pilih Nama --</option>';
            students.forEach(student => {
                const option = document.createElement('option');
                option.value = student.id;
                option.textContent = student.nama;
                option.dataset.kelas = student.kelas;
                select.appendChild(option);
            });

            select.addEventListener('change', function() {
                if (this.value) {
                    const selected = this.options[this.selectedIndex];
                    document.getElementById('kelas').value = selected.dataset.kelas || '';
                } else {
                    document.getElementById('kelas').value = '';
                }
            });
        }

        async function submitAbsen() {
            const siswaId = document.getElementById('nama').value;
            const nama = document.getElementById('nama').options[document.getElementById('nama').selectedIndex].text;
            const kelas = document.getElementById('kelas').value;

            if (!siswaId) {
                showMessage('form', 'Pilih nama siswa!', 'error');
                return;
            }

            try {
                const response = await fetch('api/submit-absen.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        siswa_id: siswaId,
                        nama: nama,
                        kelas: kelas,
                        session_id: sessionId
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showMessage('form', '✅ ' + result.message, 'success');
                    document.getElementById('nama').value = '';
                    document.getElementById('kelas').value = '';
                    loadHistory();
                } else {
                    showMessage('form', '❌ ' + (result.error || 'Gagal'), 'error');
                }
            } catch (error) {
                showMessage('form', '❌ Error: ' + error.message, 'error');
            }
        }

        async function loadHistory() {
            try {
                const response = await fetch('api/get-history.php');
                const data = await response.json();
                const tbody = document.getElementById('historyTable');

                if (data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: #999;">Belum ada data</td></tr>';
                } else {
                    tbody.innerHTML = data.map((item, index) => `
                        <tr>
                            <td>${index + 1}</td>
                            <td>${item.nama}</td>
                            <td>${item.kelas}</td>
                            <td><span class="status ${item.tipe_absen}">${item.tipe_absen.toUpperCase()}</span></td>
                            <td>${item.jam}</td>
                        </tr>
                    `).join('');
                }

                document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString('id-ID');
            } catch (error) {
                console.error('Error:', error);
            }
        }

        function showMessage(tabId, message, type) {
            let messageDiv = document.getElementById(tabId + 'Message');
            if (!messageDiv) {
                messageDiv = document.createElement('div');
                messageDiv.id = tabId + 'Message';
                document.getElementById(tabId).appendChild(messageDiv);
            }

            messageDiv.className = 'message ' + type;
            messageDiv.textContent = message;

            setTimeout(() => { messageDiv.textContent = ''; }, 3000);
        }
    </script>
</body>
</html>
