<?php
// manage_enrollments.php
// Dedicated page for admin/instructor to review and manage enrollment requests and payments.

// 1. Setup and Authorization
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$user_role = $_SESSION['user_role'] ?? 'guest';
$user_id = $_SESSION['user_id'] ?? null;
$enrollments_to_review = [];
$message = $_SESSION['action_message'] ?? ''; // Retrieve message from verification page
$is_error = $_SESSION['action_is_error'] ?? false;

// Clear session messages after retrieving them
unset($_SESSION['action_message']);
unset($_SESSION['action_is_error']);

try {
    // 2. Optimized SQL Query to Fetch ALL Enrollment Details Needing Review
    $sql = "
        SELECT
            ce.id AS enrollment_id,
            ce.enrollment_date,
            ce.status,
            s.id AS student_id,
            s.username AS student_username,
            s.full_name AS student_full_name,
            s.email AS student_email,
            c.course_name,
            b.fees AS batch_fees,
            b.id AS batch_id,
            b.batch_name,
            p.id AS payment_id,
            p.slip_number,
            p.payment_amount,
            p.payment_date,
            p.slip_path
        FROM course_enrollments ce
        JOIN users s ON ce.student_id = s.id
        JOIN batches b ON ce.batch_id = b.id
        JOIN courses c ON b.course_id = c.id
        LEFT JOIN payments p ON ce.id = p.enrollment_id
        WHERE ce.status IN ('pending', 'payment_uploaded')
    ";
    $params = [];

    // Filter by instructor ID if the user is an instructor
    if ($user_role === 'instructor') {
        $sql .= " AND b.instructor_id = ?";
        $params[] = $user_id;
    }

    // Prioritize enrollments with payment slips for quicker review
    $sql .= " ORDER BY ce.status DESC, ce.enrollment_date ASC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $enrollments_to_review = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $message = "Database error fetching enrollments: " . $e->getMessage();
    $is_error = true;
    error_log("Enrollment Management Fetch Error: " . $e->getMessage());
}

?>

<div class="w-full max-w-7xl mx-auto p-6 bg-white rounded-lg shadow-xl">

    <div class="flex justify-between items-center mb-8 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900">
            Enrollment Management <span class="text-blue-600">(<?php echo count($enrollments_to_review); ?> Pending)</span>
        </h1>
    </div>

    <?php if (!empty($message)): ?>
        <div class="mb-6 p-4 rounded-md <?php echo $is_error ? 'bg-red-100 text-red-700 border border-red-200' : 'bg-green-100 text-green-700 border border-green-200'; ?>">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if (empty($enrollments_to_review)): ?>
        <div class="p-6 rounded-md text-center text-xl bg-green-50 text-green-700 border border-green-200">
            🎉 Great job! No enrollment requests or pending payments need your attention right now.
        </div>
    <?php else: ?>

        <div class="overflow-x-auto shadow-md rounded-lg">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Course / Batch</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Payment Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($enrollments_to_review as $enrollment): ?>
                    <tr class="<?php echo ($enrollment['status'] === 'payment_uploaded') ? 'bg-orange-50 hover:bg-orange-100' : 'hover:bg-gray-50'; ?>">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                <?php 
                                    if ($enrollment['status'] === 'payment_uploaded') echo 'bg-orange-100 text-orange-800';
                                    else if ($enrollment['status'] === 'pending') echo 'bg-yellow-100 text-yellow-800';
                                    else echo 'bg-gray-100 text-gray-800';
                                ?>">
                                <?php echo ucwords(str_replace('_', ' ', htmlspecialchars($enrollment['status']))); ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($enrollment['student_full_name']); ?></div>
                            <div class="text-sm text-gray-500"><?php echo htmlspecialchars($enrollment['student_email']); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-semibold text-blue-600"><?php echo htmlspecialchars($enrollment['course_name']); ?></div>
                            <div class="text-sm text-gray-500"><?php echo htmlspecialchars($enrollment['batch_name']); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <?php if (isset($enrollment['payment_id']) && $enrollment['payment_id']): ?>
                                <div class="text-sm font-medium text-indigo-700">Paid: $<?php echo number_format($enrollment['payment_amount'], 2); ?></div>
                                <div class="text-xs text-gray-500">Slip: <?php echo htmlspecialchars($enrollment['slip_number']); ?></div>
                                <a href="<?php echo htmlspecialchars($enrollment['slip_path']); ?>" target="_blank" class="text-xs text-blue-500 hover:text-blue-700 font-medium mt-1 inline-block">View Slip</a>
                            <?php else: ?>
                                <span class="text-sm text-red-500 font-medium">Payment Awaiting</span>
                                <div class="text-xs text-gray-500">Batch Fee: $<?php echo number_format($enrollment['batch_fees'], 2); ?></div>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <a href="index.php?page=enrollment_verification&enrollment_id=<?php echo htmlspecialchars($enrollment['enrollment_id']); ?>" class="text-blue-600 hover:text-blue-900 font-semibold transition duration-150">
                                Review & Verify
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
    <?php endif; ?>

</div>