<?php
require_once '../config/config.php';
requireRole('employee');

$pageTitle = 'QR Code - PSAU GAD';
$db = getDB();
$userId = getCurrentUserId();

$registrationId = $_GET['id'] ?? 0;

// Get registration details
$stmt = $db->prepare("
    SELECT 
        ar.*,
        a.title,
        a.activity_date,
        a.start_time,
        a.end_time,
        a.venue,
        a.category
    FROM activity_registrations ar
    JOIN activities a ON ar.activity_id = a.activity_id
    WHERE ar.registration_id = ? AND ar.user_id = ? AND ar.status = 'approved'
");
$stmt->execute([$registrationId, $userId]);
$registration = $stmt->fetch();

if (!$registration) {
    header('Location: my-activities.php');
    exit;
}

// Generate QR code if not already generated
if (!$registration['qr_code']) {
    require_once '../includes/classes/QRCode.php';
    $qrCode = new QRCode();
    $result = $qrCode->generateForRegistration($registrationId);

    if ($result['success']) {
        // Refresh registration data
        $stmt->execute([$registrationId, $userId]);
        $registration = $stmt->fetch();
    }
}

// Get employee profile
$stmt = $db->prepare("SELECT * FROM employee_profiles WHERE user_id = ?");
$stmt->execute([$userId]);
$profile = $stmt->fetch();

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <div class="mb-6">
            <a href="my-activities.php" class="text-employee hover:text-green-700 font-semibold"><i class="fas fa-arrow-left mr-2"></i>Back to My Activities</a>
        </div>

        <div class="max-w-2xl mx-auto">
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <!-- Header -->
                <div class="bg-gradient-to-r from-employee to-green-600 p-6 text-white text-center">
                    <h1 class="text-2xl font-bold mb-2">Attendance QR Code</h1>
                    <p class="text-green-100">Show this QR code at the event for attendance</p>
                </div>

                <!-- Activity Info -->
                <div class="p-6 bg-gray-50 border-b border-gray-200">
                    <h2 class="text-xl font-bold text-gray-900 mb-4"><?php echo htmlspecialchars($registration['title']); ?></h2>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="flex items-center text-sm text-gray-600">
                            <i class="fas fa-calendar w-6 text-employee"></i>
                            <span><?php echo formatDate($registration['activity_date']); ?></span>
                        </div>
                        <div class="flex items-center text-sm text-gray-600">
                            <i class="fas fa-clock w-6 text-employee"></i>
                            <span><?php echo formatTime($registration['start_time']); ?> - <?php echo formatTime($registration['end_time']); ?></span>
                        </div>
                        <div class="flex items-center text-sm text-gray-600">
                            <i class="fas fa-map-marker-alt w-6 text-employee"></i>
                            <span><?php echo htmlspecialchars($registration['venue']); ?></span>
                        </div>
                        <div class="flex items-center text-sm text-gray-600">
                            <i class="fas fa-tag w-6 text-employee"></i>
                            <span><?php echo htmlspecialchars($registration['category']); ?></span>
                        </div>
                    </div>
                </div>

                <!-- QR Code -->
                <div class="p-8 text-center">
                    <div class="bg-white border-4 border-employee rounded-xl p-6 inline-block">
                        <?php
                        // Generate QR code URL from registration data
                        $qrData = base64_encode(json_encode([
                            'reg_id' => $registration['registration_id'],
                            'timestamp' => time(),
                            'hash' => hash('sha256', $registration['registration_id'] . SITE_NAME . time())
                        ]));
                        $qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($qrData);
                        ?>
                        <img src="<?php echo $qrCodeUrl; ?>" alt="QR Code" class="w-64 h-64 mx-auto" id="qr-code-image">
                    </div>
                    <p class="text-gray-600 mt-4 font-semibold">Registration ID: <?php echo $registration['registration_id']; ?></p>
                </div>

                <!-- Participant Info -->
                <div class="p-6 bg-gray-50 border-t border-gray-200">
                    <h3 class="font-bold text-gray-900 mb-3">Participant Information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                        <div>
                            <span class="text-gray-600">Name:</span>
                            <span class="font-semibold text-gray-900 ml-2"><?php echo htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']); ?></span>
                        </div>
                        <div>
                            <span class="text-gray-600">Category:</span>
                            <span class="font-semibold text-gray-900 ml-2"><?php echo htmlspecialchars($profile['category']); ?></span>
                        </div>
                        <div>
                            <span class="text-gray-600">Gender:</span>
                            <span class="font-semibold text-gray-900 ml-2"><?php echo htmlspecialchars($profile['gender']); ?></span>
                        </div>
                        <div>
                            <span class="text-gray-600">Registration Date:</span>
                            <span class="font-semibold text-gray-900 ml-2"><?php echo formatDate($registration['registration_date']); ?></span>
                        </div>
                    </div>
                </div>

                <!-- Instructions -->
                <div class="p-6 bg-blue-50 border-t border-blue-200">
                    <h3 class="font-bold text-blue-900 mb-3"><i class="fas fa-info-circle mr-2"></i>Instructions</h3>
                    <ul class="space-y-2 text-sm text-blue-800">
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-600 mr-2 mt-1"></i>
                            <span>Present this QR code at the event registration desk</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-600 mr-2 mt-1"></i>
                            <span>Arrive on time - attendance is marked as "Late" after 20 minutes from start time</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-600 mr-2 mt-1"></i>
                            <span>You can save this page or take a screenshot for offline access</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-blue-600 mr-2 mt-1"></i>
                            <span>Do not share your QR code with others</span>
                        </li>
                    </ul>
                </div>

                <!-- Actions -->
                <div class="p-6 flex flex-col sm:flex-row gap-3">
                    <button onclick="window.print()" class="flex-1 bg-employee text-white px-6 py-3 rounded-lg hover:bg-green-700 transition font-semibold">
                        <i class="fas fa-print mr-2"></i>Print QR Code
                    </button>
                    <button onclick="downloadQRCode()" class="flex-1 bg-gray-200 text-gray-700 text-center px-6 py-3 rounded-lg hover:bg-gray-300 transition font-semibold">
                        <i class="fas fa-download mr-2"></i>Download QR Code
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
@media print {
    body * {
        visibility: hidden;
    }
    .container, .container * {
        visibility: visible;
    }
    .container {
        position: absolute;
        left: 0;
        top: 0;
    }
    nav, footer, button, a {
        display: none !important;
    }
}
</style>

<script>
function downloadQRCode() {
    const qrImage = document.getElementById('qr-code-image');
    const link = document.createElement('a');
    link.href = qrImage.src;
    link.download = 'qr-code-<?php echo $registration['registration_id']; ?>.png';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>

<?php include '../includes/footer.php'; ?>

