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

$db = getDB();
$userId = getCurrentUserId();

// Get registration_id from URL
$registrationId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

// Get registration details with all requirements
$stmt = $db->prepare("
    SELECT 
        ar.*,
        a.title,
        a.description,
        a.activity_date,
        a.start_time,
        a.end_time,
        a.venue,
        a.category,
        u.first_name,
        u.last_name,
        u.email,
        u.department,
        aa.status as attendance_status,
        aa.check_in_time,
        ptr.passed as pre_test_passed,
        potr.passed as post_test_passed,
        er.response_id as evaluation_submitted
    FROM activity_registrations ar
    JOIN activities a ON ar.activity_id = a.activity_id
    JOIN users u ON ar.user_id = u.user_id
    LEFT JOIN activity_attendance aa ON ar.registration_id = aa.registration_id
    LEFT JOIN pre_tests pt ON a.activity_id = pt.activity_id AND pt.is_active = 1
    LEFT JOIN pre_test_responses ptr ON pt.test_id = ptr.test_id AND ptr.user_id = ar.user_id
    LEFT JOIN post_tests pot ON a.activity_id = pot.activity_id AND pot.is_active = 1
    LEFT JOIN post_test_responses potr ON pot.test_id = potr.test_id AND potr.user_id = ar.user_id
    LEFT JOIN evaluation_forms ef ON a.activity_id = ef.activity_id AND ef.is_active = 1
    LEFT JOIN evaluation_responses er ON ef.form_id = er.form_id AND er.user_id = ar.user_id
    WHERE ar.registration_id = ? AND ar.user_id = ?
");
$stmt->execute([$registrationId, $userId]);
$registration = $stmt->fetch();

if (!$registration) {
    $_SESSION['error'] = 'Certificate not found.';
    header('Location: my-activities.php');
    exit;
}

// Check if eligible for certificate
$eligible = true;
$missingRequirements = [];

// Must be approved
if ($registration['status'] !== 'approved') {
    $eligible = false;
    $missingRequirements[] = 'Registration must be approved';
}

// Must have attended
if (!$registration['attendance_status'] || !in_array($registration['attendance_status'], ['present', 'late'])) {
    $eligible = false;
    $missingRequirements[] = 'Must have attended the activity';
}

// Must have submitted evaluation (if form exists)
if ($registration['evaluation_submitted'] === null && $registration['activity_date'] < date('Y-m-d')) {
    // Only require evaluation if activity has passed and form exists
    $stmt = $db->prepare("SELECT form_id FROM evaluation_forms WHERE activity_id = ? AND is_active = 1");
    $stmt->execute([$registration['activity_id']]);
    if ($stmt->fetch()) {
        $eligible = false;
        $missingRequirements[] = 'Must submit activity evaluation';
    }
}

// If download parameter is set and eligible, generate PDF
if (isset($_GET['download']) && $eligible) {
    generateCertificatePDF($registration);
    exit;
}

$pageTitle = 'Certificate - Employee - PSAU GAD';
include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gradient-to-br from-green-50 to-blue-50 py-8">
    <div class="container mx-auto px-4 max-w-4xl">
        <!-- Header -->
        <div class="mb-6">
            <div class="flex items-center">
                <a href="my-activities.php" class="text-employee hover:text-green-700 mr-4">
                    <i class="fas fa-arrow-left text-xl"></i>
                </a>
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-certificate text-employee mr-2"></i>Certificate of Participation
                    </h1>
                    <p class="text-gray-600"><?php echo htmlspecialchars($registration['title']); ?></p>
                </div>
            </div>
        </div>

        <?php if (!$eligible): ?>
            <!-- Not Eligible Message -->
            <div class="bg-yellow-50 border-l-4 border-yellow-500 p-6 rounded-lg mb-6">
                <div class="flex items-start">
                    <i class="fas fa-exclamation-triangle text-yellow-500 text-2xl mr-4 mt-1"></i>
                    <div>
                        <h3 class="text-lg font-bold text-yellow-900 mb-2">Certificate Not Available</h3>
                        <p class="text-yellow-800 mb-3">You must complete the following requirements:</p>
                        <ul class="list-disc list-inside text-yellow-800 space-y-1">
                            <?php foreach ($missingRequirements as $req): ?>
                                <li><?php echo htmlspecialchars($req); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- Certificate Preview -->
        <div class="bg-white rounded-xl shadow-2xl overflow-hidden">
            <!-- Certificate Design -->
            <div id="certificate" class="p-12 bg-gradient-to-br from-blue-50 to-green-50" style="min-height: 600px;">
                <!-- Border -->
                <div class="border-8 border-double border-employee p-8 h-full">
                    <!-- Header -->
                    <div class="text-center mb-8">
                        <div class="text-4xl font-bold text-gray-800 mb-2">PAMPANGA STATE AGRICULTURAL UNIVERSITY</div>
                        <div class="text-xl text-gray-600 mb-4">Gender and Development Office</div>
                        <div class="w-32 h-1 bg-employee mx-auto mb-6"></div>
                        <div class="text-3xl font-bold text-employee mb-2">CERTIFICATE OF PARTICIPATION</div>
                    </div>

                    <!-- Body -->
                    <div class="text-center mb-8">
                        <p class="text-lg text-gray-700 mb-6">This is to certify that</p>
                        
                        <div class="text-4xl font-bold text-gray-900 mb-2">
                            <?php echo strtoupper(htmlspecialchars($registration['first_name'] . ' ' . $registration['last_name'])); ?>
                        </div>
                        <div class="w-64 h-0.5 bg-gray-400 mx-auto mb-6"></div>
                        
                        <p class="text-lg text-gray-700 mb-4">
                            has successfully participated in
                        </p>
                        
                        <div class="text-2xl font-bold text-employee mb-2">
                            <?php echo strtoupper(htmlspecialchars($registration['title'])); ?>
                        </div>
                        
                        <p class="text-lg text-gray-700 mb-6">
                            held on <strong><?php echo date('F j, Y', strtotime($registration['activity_date'])); ?></strong>
                            <?php if ($registration['venue']): ?>
                                at <strong><?php echo htmlspecialchars($registration['venue']); ?></strong>
                            <?php endif; ?>
                        </p>
                        
                        <?php if ($registration['category']): ?>
                            <div class="inline-block bg-employee text-white px-4 py-2 rounded-full text-sm font-semibold mb-6">
                                <?php echo strtoupper(htmlspecialchars($registration['category'])); ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Footer -->
                    <div class="mt-12 pt-8 border-t border-gray-300">
                        <div class="flex justify-between items-end">
                            <div class="text-center">
                                <div class="w-48 h-0.5 bg-gray-400 mb-2"></div>
                                <div class="text-sm font-semibold text-gray-700">GAD Focal Person</div>
                            </div>
                            
                            <div class="text-center">
                                <div class="text-xs text-gray-500 mb-2">
                                    Certificate ID: PSAU-GAD-<?php echo str_pad($registration['registration_id'], 6, '0', STR_PAD_LEFT); ?>
                                </div>
                                <div class="text-xs text-gray-500">
                                    Issued: <?php echo date('F j, Y'); ?>
                                </div>
                            </div>
                            
                            <div class="text-center">
                                <div class="w-48 h-0.5 bg-gray-400 mb-2"></div>
                                <div class="text-sm font-semibold text-gray-700">University President</div>
                            </div>
                        </div>
                    </div>

                    <!-- QR Code -->
                    <div class="text-center mt-6">
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=<?php echo urlencode(BASE_URL . '/verify-certificate.php?id=' . $registration['registration_id']); ?>" 
                             alt="QR Code" class="mx-auto">
                        <p class="text-xs text-gray-500 mt-2">Scan to verify certificate authenticity</p>
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <?php if ($eligible): ?>
                <div class="bg-gray-50 p-6 flex justify-center space-x-4">
                    <a href="certificate.php?id=<?php echo $registration['registration_id']; ?>&download=1" 
                       class="bg-employee text-white px-8 py-3 rounded-lg hover:bg-green-700 transition font-semibold">
                        <i class="fas fa-download mr-2"></i>Download PDF
                    </a>
                    <button onclick="window.print()" 
                            class="bg-gray-600 text-white px-8 py-3 rounded-lg hover:bg-gray-700 transition font-semibold">
                        <i class="fas fa-print mr-2"></i>Print Certificate
                    </button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
@media print {
    body * {
        visibility: hidden;
    }
    #certificate, #certificate * {
        visibility: visible;
    }
    #certificate {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
    }
}
</style>

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

<?php
function generateCertificatePDF($registration) {
    // Simple HTML to PDF conversion using browser print
    // For production, use TCPDF or similar library
    header('Content-Type: text/html; charset=utf-8');
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Certificate - <?php echo htmlspecialchars($registration['first_name'] . ' ' . $registration['last_name']); ?></title>
        <style>
            @page { size: landscape; margin: 0; }
            body { 
                margin: 0; 
                padding: 40px;
                font-family: 'Times New Roman', serif;
                background: linear-gradient(135deg, #e0f2fe 0%, #dcfce7 100%);
            }
            .certificate {
                border: 12px double #10b981;
                padding: 60px;
                background: white;
                min-height: 700px;
            }
            .header { text-align: center; margin-bottom: 40px; }
            .university { font-size: 36px; font-weight: bold; color: #1f2937; margin-bottom: 10px; }
            .office { font-size: 20px; color: #6b7280; margin-bottom: 20px; }
            .divider { width: 150px; height: 3px; background: #10b981; margin: 20px auto; }
            .title { font-size: 32px; font-weight: bold; color: #10b981; margin-bottom: 40px; }
            .body { text-align: center; margin: 40px 0; }
            .label { font-size: 18px; color: #4b5563; margin: 20px 0; }
            .name { font-size: 42px; font-weight: bold; color: #1f2937; margin: 20px 0; border-bottom: 2px solid #9ca3af; display: inline-block; padding: 0 40px; }
            .activity { font-size: 28px; font-weight: bold; color: #10b981; margin: 20px 0; }
            .date { font-size: 18px; color: #4b5563; margin: 20px 0; }
            .category { display: inline-block; background: #10b981; color: white; padding: 8px 20px; border-radius: 20px; font-size: 14px; margin: 20px 0; }
            .footer { margin-top: 60px; padding-top: 30px; border-top: 2px solid #e5e7eb; display: flex; justify-content: space-between; }
            .signature { text-align: center; }
            .signature-line { width: 200px; height: 2px; background: #9ca3af; margin: 0 auto 10px; }
            .signature-label { font-size: 14px; font-weight: bold; color: #4b5563; }
            .cert-id { text-align: center; margin-top: 20px; font-size: 12px; color: #6b7280; }
        </style>
    </head>
    <body onload="window.print(); setTimeout(function(){ window.close(); }, 100);">
        <div class="certificate">
            <div class="header">
                <div class="university">PAMPANGA STATE AGRICULTURAL UNIVERSITY</div>
                <div class="office">Gender and Development Office</div>
                <div class="divider"></div>
                <div class="title">CERTIFICATE OF PARTICIPATION</div>
            </div>
            
            <div class="body">
                <div class="label">This is to certify that</div>
                <div class="name"><?php echo strtoupper(htmlspecialchars($registration['first_name'] . ' ' . $registration['last_name'])); ?></div>
                <div class="label">has successfully participated in</div>
                <div class="activity"><?php echo strtoupper(htmlspecialchars($registration['title'])); ?></div>
                <div class="date">
                    held on <strong><?php echo date('F j, Y', strtotime($registration['activity_date'])); ?></strong>
                    <?php if ($registration['venue']): ?>
                        at <strong><?php echo htmlspecialchars($registration['venue']); ?></strong>
                    <?php endif; ?>
                </div>
                <?php if ($registration['category']): ?>
                    <div class="category"><?php echo strtoupper(htmlspecialchars($registration['category'])); ?></div>
                <?php endif; ?>
            </div>
            
            <div class="footer">
                <div class="signature">
                    <div class="signature-line"></div>
                    <div class="signature-label">GAD Focal Person</div>
                </div>
                <div class="signature">
                    <div class="signature-line"></div>
                    <div class="signature-label">University President</div>
                </div>
            </div>
            
            <div class="cert-id">
                Certificate ID: PSAU-GAD-<?php echo str_pad($registration['registration_id'], 6, '0', STR_PAD_LEFT); ?><br>
                Issued: <?php echo date('F j, Y'); ?>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}
?>

