<?php
session_start();
require_once 'db.php';
date_default_timezone_set('Asia/Jakarta');

// Cek login siswa
if (!isset($_SESSION['is_siswa_logged_in']) || $_SESSION['is_siswa_logged_in'] !== true) {
    header("Location: login_siswa.php");
    exit;
}

$siswa_id = $_SESSION['siswa_id'];

// Ambil data siswa
$stmt_siswa = $pdo->prepare("SELECT s.*, k.nama_kelas FROM siswa s JOIN kelas k ON s.kelas_id = k.id WHERE s.siswa_id = ?");
$stmt_siswa->execute([$siswa_id]);
$siswa = $stmt_siswa->fetch(PDO::FETCH_ASSOC);

if (!$siswa) {
    session_destroy();
    header("Location: login_siswa.php?error=siswa_not_found");
    exit;
}

// Fungsi untuk validasi token QR dinamis
function validateQRToken($token, $pdo) {
    try {
        $stmt = $pdo->prepare("SELECT token, expiry_time, is_used FROM qr_tokens WHERE token = ? AND expiry_time > NOW()");
        $stmt->execute([$token]);
        $token_data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$token_data) {
            return ['valid' => false, 'message' => 'QR Code sudah kadaluarsa atau tidak valid'];
        }
        
        if ($token_data['is_used']) {
            return ['valid' => false, 'message' => 'QR Code sudah digunakan'];
        }
        
        // Tandai token sebagai digunakan
        $stmt = $pdo->prepare("UPDATE qr_tokens SET is_used = TRUE WHERE token = ?");
        $stmt->execute([$token]);
        
        return ['valid' => true, 'message' => 'Token valid'];
        
    } catch (PDOException $e) {
        return ['valid' => false, 'message' => 'Error validasi token: ' . $e->getMessage()];
    }
}

// Fungsi untuk proses absensi
function processAttendance($siswa_id, $pdo) {
    $tanggal_hari_ini = date('Y-m-d');
    $bulan_hari_ini = date('Y-m');
    
    try {
        // Cek apakah sudah absen hari ini
        $stmt_cek = $pdo->prepare("SELECT status FROM kehadiran WHERE siswa_id = ? AND tanggal = ?");
        $stmt_cek->execute([$siswa_id, $tanggal_hari_ini]);
        $status_kehadiran = $stmt_cek->fetchColumn();
        
        if ($status_kehadiran) {
            return [
                'success' => false,
                'message' => "Anda sudah absen hari ini dengan status: " . $status_kehadiran,
                'status' => $status_kehadiran
            ];
        } else {
            // Jika belum, masukkan data kehadiran
            $stmt_insert = $pdo->prepare("INSERT INTO kehadiran (siswa_id, tanggal, status, bulan) VALUES (?, ?, 'H', ?)");
            if ($stmt_insert->execute([$siswa_id, $tanggal_hari_ini, $bulan_hari_ini])) {
                return [
                    'success' => true,
                    'message' => "Absensi berhasil! Status: Hadir",
                    'status' => 'H'
                ];
            } else {
                return [
                    'success' => false,
                    'message' => "Gagal menyimpan data kehadiran",
                    'status' => null
                ];
            }
        }
    } catch (PDOException $e) {
        return [
            'success' => false,
            'message' => "Terjadi kesalahan database: " . $e->getMessage(),
            'status' => null
        ];
    }
}

// Proses QR token jika ada
$result = [];
if (isset($_GET['qr_token'])) {
    $token = $_GET['qr_token'];
    $token_validation = validateQRToken($token, $pdo);
    
    if ($token_validation['valid']) {
        $result = processAttendance($siswa_id, $pdo);
    } else {
        $result = [
            'success' => false,
            'message' => $token_validation['message'],
            'status' => null
        ];
    }
} else {
    $result = [
        'success' => false,
        'message' => 'Token QR tidak ditemukan',
        'status' => null
    ];
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hasil Scan QR - Absensi</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .fade-in {
            animation: fadeIn 0.6s ease-out;
        }
        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% {transform: translateY(0);}
            40% {transform: translateY(-10px);}
            60% {transform: translateY(-5px);}
        }
        .bounce {
            animation: bounce 2s infinite;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-500 to-purple-600 min-h-screen flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-md fade-in">
        <div class="text-center">
            <?php if ($result['success']): ?>
                <!-- Success State -->
                <div class="text-green-500 text-6xl mb-4 bounce">
                    <i class="fas fa-check-circle"></i>
                </div>
                <h1 class="text-2xl font-bold text-green-600 mb-2">Absensi Berhasil!</h1>
                <p class="text-gray-700 mb-4"><?= $result['message'] ?></p>
                
                <div class="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-600">Nama:</span>
                        <span class="font-semibold"><?= htmlspecialchars($siswa['nama']) ?></span>
                    </div>
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-600">Kelas:</span>
                        <span class="font-semibold"><?= htmlspecialchars($siswa['nama_kelas']) ?></span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">Tanggal:</span>
                        <span class="font-semibold"><?= date('d/m/Y') ?></span>
                    </div>
                    <div class="flex items-center justify-between mt-2">
                        <span class="text-sm text-gray-600">Waktu:</span>
                        <span class="font-semibold"><?= date('H:i:s') ?></span>
                    </div>
                </div>
                
            <?php else: ?>
                <!-- Error State -->
                <div class="text-red-500 text-6xl mb-4">
                    <i class="fas fa-exclamation-circle"></i>
                </div>
                <h1 class="text-2xl font-bold text-red-600 mb-2">Absensi Gagal</h1>
                <p class="text-gray-700 mb-6"><?= $result['message'] ?></p>
                
                <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-600">Nama:</span>
                        <span class="font-semibold"><?= htmlspecialchars($siswa['nama']) ?></span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">Kelas:</span>
                        <span class="font-semibold"><?= htmlspecialchars($siswa['nama_kelas']) ?></span>
                    </div>
                </div>
            <?php endif; ?>
            
            <div class="flex space-x-4">
                <a href="dashboard_siswa.php" class="flex-1 bg-indigo-600 text-white py-3 rounded-lg font-semibold hover:bg-indigo-700 transition text-center">
                    <i class="fas fa-home mr-2"></i>Dashboard
                </a>
                <?php if ($result['success']): ?>
                <a href="dashboard_siswa.php#riwayat" class="flex-1 bg-green-600 text-white py-3 rounded-lg font-semibold hover:bg-green-700 transition text-center">
                    <i class="fas fa-history mr-2"></i>Lihat Riwayat
                </a>
                <?php endif; ?>
            </div>
            
            <?php if (!$result['success'] && $result['status']): ?>
                <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                    <p class="text-yellow-700 text-sm">
                        <i class="fas fa-info-circle mr-1"></i>
                        Status terakhir: <span class="font-bold"><?= $result['status'] ?></span>
                    </p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Auto redirect ke dashboard setelah 5 detik jika sukses
        <?php if ($result['success']): ?>
        setTimeout(() => {
            window.location.href = 'dashboard_siswa.php';
        }, 5000);
        <?php endif; ?>
        
        // Tambahkan efek confetti jika sukses
        <?php if ($result['success']): ?>
        document.addEventListener('DOMContentLoaded', function() {
            // Simple confetti effect
            const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'];
            for (let i = 0; i < 50; i++) {
                setTimeout(() => {
                    const confetti = document.createElement('div');
                    confetti.style.cssText = `
                        position: fixed;
                        width: 10px;
                        height: 10px;
                        background: ${colors[Math.floor(Math.random() * colors.length)]};
                        border-radius: 50%;
                        top: -10px;
                        left: ${Math.random() * 100}%;
                        animation: fall linear forwards;
                        z-index: 1000;
                    `;
                    document.body.appendChild(confetti);
                    
                    const style = document.createElement('style');
                    style.textContent = `
                        @keyframes fall {
                            to {
                                transform: translateY(100vh) rotate(${Math.random() * 360}deg);
                                opacity: 0;
                            }
                        }
                    `;
                    document.head.appendChild(style);
                    
                    setTimeout(() => confetti.remove(), 2000);
                }, i * 100);
            }
        });
        <?php endif; ?>
    </script>
</body>
</html>