<?php
require_once '../config/config.php';

// Require admin login
requireRole('secretariat');

$pageTitle = 'Registration Approvals - Secretariat - PSAU GAD';
$db = getDB();

// Handle approval/rejection
if (isPost()) {
    $action = post('action');
    $registrationId = (int)post('registration_id');
    
    try {
        if ($action === 'approve') {
            // Update registration status
            $stmt = $db->prepare("
                UPDATE activity_registrations
                SET status = 'approved', is_approved = 1, approved_by = ?, approved_at = NOW()
                WHERE registration_id = ?
            ");
            $stmt->execute([getCurrentUserId(), $registrationId]);
            
            // Get registration details for email
            $stmt = $db->prepare("
                SELECT ar.*, a.title, a.activity_date, u.email
                FROM activity_registrations ar
                JOIN activities a ON ar.activity_id = a.activity_id
                JOIN users u ON ar.user_id = u.user_id
                WHERE ar.registration_id = ?
            ");
            $stmt->execute([$registrationId]);
            $registration = $stmt->fetch();
            
            // Generate QR code
            $qrCode = new QRCode();
            $result = $qrCode->generateQRCode($registrationId);

            if (!$result['success']) {
                setFlashMessage('error', 'Failed to generate QR code');
                redirect('registration-approvals.php');
            }
            
            // Send approval email with QR code (optional - can be enabled when email is configured)
            // $email = new Email();
            // $preTestLink = BASE_URL . '/employee/pre-test.php?activity_id=' . $registration['activity_id'];
            // $email->sendApprovalNotification($registration['user_id'], $registration['title'], $preTestLink);
            // $email->sendQRCode($registration['user_id'], $registration['title'], $result['filepath']);
            
            setFlashMessage('success', 'Registration approved and QR code sent');
        } elseif ($action === 'reject') {
            $stmt = $db->prepare("UPDATE activity_registrations SET status = 'rejected' WHERE registration_id = ?");
            $stmt->execute([$registrationId]);
            
            setFlashMessage('success', 'Registration rejected');
        }
    } catch (Exception $e) {
        setFlashMessage('error', 'Failed to process request');
        logError('Registration approval error: ' . $e->getMessage());
    }
    
    redirect('registration-approvals.php');
}

// Get pending registrations
$stmt = $db->query("
    SELECT 
        ar.*,
        a.title as activity_title,
        a.activity_date,
        a.start_time,
        a.venue,
        ep.first_name,
        ep.last_name,
        ep.category,
        u.email
    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 employee_profiles ep ON u.user_id = ep.user_id
    WHERE ar.status = 'pending'
    ORDER BY ar.registration_date DESC
");
$pendingRegistrations = $stmt->fetchAll();

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">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">
                <i class="fas fa-clipboard-list text-secretariat mr-3"></i>
                Registration Approvals
            </h1>
            <p class="text-gray-600">Review and approve activity registrations</p>
        </div>

        <?php displayFlashMessage(); ?>

        <!-- Pending Registrations -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <?php if (empty($pendingRegistrations)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-check-circle text-6xl text-green-300 mb-4"></i>
                    <h3 class="text-xl font-semibold text-gray-600 mb-2">All Caught Up!</h3>
                    <p class="text-gray-500">No pending registration approvals at the moment</p>
                </div>
            <?php else: ?>
                <div class="p-6">
                    <div class="mb-6">
                        <h2 class="text-xl font-bold text-gray-900">
                            Pending Registrations (<?php echo count($pendingRegistrations); ?>)
                        </h2>
                    </div>

                    <div class="space-y-4">
                        <?php foreach ($pendingRegistrations as $reg): ?>
                            <div class="border border-gray-200 rounded-lg p-6 hover:border-secretariat transition">
                                <div class="flex items-start justify-between">
                                    <!-- Registration Info -->
                                    <div class="flex-1">
                                        <!-- Employee Info -->
                                        <div class="flex items-center mb-4">
                                            <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center text-purple-600 font-semibold mr-4">
                                                <?php 
                                                if ($reg['first_name']) {
                                                    echo strtoupper(substr($reg['first_name'], 0, 1) . substr($reg['last_name'], 0, 1));
                                                } else {
                                                    echo strtoupper(substr($reg['email'], 0, 2));
                                                }
                                                ?>
                                            </div>
                                            <div>
                                                <h3 class="font-semibold text-gray-900 text-lg">
                                                    <?php 
                                                    if ($reg['first_name']) {
                                                        echo htmlspecialchars($reg['first_name'] . ' ' . $reg['last_name']);
                                                    } else {
                                                        echo 'Profile Incomplete';
                                                    }
                                                    ?>
                                                </h3>
                                                <p class="text-sm text-gray-600">
                                                    <i class="fas fa-envelope mr-1"></i>
                                                    <?php echo htmlspecialchars($reg['email']); ?>
                                                    <?php if ($reg['category']): ?>
                                                        <span class="mx-2">•</span>
                                                        <i class="fas fa-briefcase mr-1"></i>
                                                        <?php echo htmlspecialchars($reg['category']); ?>
                                                    <?php endif; ?>
                                                </p>
                                            </div>
                                        </div>

                                        <!-- Activity Info -->
                                        <div class="bg-gray-50 rounded-lg p-4 mb-4">
                                            <h4 class="font-semibold text-gray-900 mb-3">
                                                <i class="fas fa-calendar-alt text-secretariat mr-2"></i>
                                                <?php echo htmlspecialchars($reg['activity_title']); ?>
                                            </h4>
                                            <div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
                                                <div>
                                                    <p class="text-gray-600">
                                                        <i class="fas fa-calendar mr-1 text-secretariat"></i>
                                                        <?php echo formatDate($reg['activity_date']); ?>
                                                    </p>
                                                </div>
                                                <div>
                                                    <p class="text-gray-600">
                                                        <i class="fas fa-clock mr-1 text-secretariat"></i>
                                                        <?php echo formatTime($reg['start_time']); ?>
                                                    </p>
                                                </div>
                                                <div>
                                                    <p class="text-gray-600">
                                                        <i class="fas fa-map-marker-alt mr-1 text-secretariat"></i>
                                                        <?php echo htmlspecialchars($reg['venue']); ?>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Registration Details -->
                                        <div class="flex items-center text-sm text-gray-600">
                                            <i class="fas fa-clock mr-2"></i>
                                            Registered: <?php echo formatDateTime($reg['registration_date']); ?>
                                        </div>
                                    </div>

                                    <!-- Actions -->
                                    <div class="ml-6 flex flex-col space-y-2">
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="approve">
                                            <input type="hidden" name="registration_id" value="<?php echo $reg['registration_id']; ?>">
                                            <button type="submit" 
                                                    class="w-32 bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition text-sm font-semibold">
                                                <i class="fas fa-check mr-2"></i> Approve
                                            </button>
                                        </form>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="action" value="reject">
                                            <input type="hidden" name="registration_id" value="<?php echo $reg['registration_id']; ?>">
                                            <button type="submit" 
                                                    onclick="return confirm('Are you sure you want to reject this registration?')"
                                                    class="w-32 bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition text-sm font-semibold">
                                                <i class="fas fa-times mr-2"></i> Reject
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Recently Approved -->
        <?php
        $stmt = $db->query("
            SELECT 
                ar.*,
                a.title as activity_title,
                ep.first_name,
                ep.last_name,
                u.email
            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 employee_profiles ep ON u.user_id = ep.user_id
            WHERE ar.status = 'approved'
            ORDER BY ar.updated_at DESC
            LIMIT 5
        ");
        $recentlyApproved = $stmt->fetchAll();
        ?>

        <?php if (!empty($recentlyApproved)): ?>
            <div class="bg-white rounded-xl shadow-lg overflow-hidden mt-8">
                <div class="p-6">
                    <h2 class="text-xl font-bold text-gray-900 mb-4">
                        <i class="fas fa-check-circle text-green-500 mr-2"></i>
                        Recently Approved
                    </h2>
                    <div class="space-y-3">
                        <?php foreach ($recentlyApproved as $reg): ?>
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center">
                                    <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center text-green-600 font-semibold mr-3">
                                        <?php 
                                        if ($reg['first_name']) {
                                            echo strtoupper(substr($reg['first_name'], 0, 1) . substr($reg['last_name'], 0, 1));
                                        } else {
                                            echo strtoupper(substr($reg['email'], 0, 2));
                                        }
                                        ?>
                                    </div>
                                    <div>
                                        <h4 class="font-semibold text-gray-900">
                                            <?php 
                                            if ($reg['first_name']) {
                                                echo htmlspecialchars($reg['first_name'] . ' ' . $reg['last_name']);
                                            } else {
                                                echo htmlspecialchars($reg['email']);
                                            }
                                            ?>
                                        </h4>
                                        <p class="text-xs text-gray-600">
                                            <?php echo htmlspecialchars($reg['activity_title']); ?>
                                        </p>
                                    </div>
                                </div>
                                <span class="px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-700">
                                    <i class="fas fa-check mr-1"></i> Approved
                                </span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

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

