<?php
session_start();
require_once('../config.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];

if (isset($_GET['enroll']) && $role == 'student') {
    $course_id = (int) $_GET['enroll'];

    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE student_id = ? AND status IN ('enrolled', 'appeal_pending')");
        $stmt->execute([$user_id]);
        $active_enrollment_count = $stmt->fetchColumn();

        if ($active_enrollment_count >= 1) {
            header("Location: courses.php?error=max_enrolled");
            exit();
        }

        $stmt = $pdo->prepare("SELECT username, email FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $student = $stmt->fetch(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("
            SELECT status
            FROM applications
            WHERE email = ? AND course_id = ? AND status IN ('pending', 'accepted')
            ORDER BY created_at DESC
            LIMIT 1
        ");
        $stmt->execute([$student['email'], $course_id]);
        $existing_application_status = $stmt->fetchColumn();

        if ($existing_application_status == 'pending') {
            header("Location: courses.php?success=application_pending");
            exit();
        }

        if ($existing_application_status == 'accepted') {
            header("Location: courses.php?success=application_accepted");
            exit();
        }

        $stmt = $pdo->prepare("
            INSERT INTO applications (full_name, email, course_id, message, status)
            VALUES (?, ?, ?, ?, 'pending')
        ");
        $stmt->execute([
            $student['username'],
            $student['email'],
            $course_id,
            'Course application submitted from the student course catalogue.'
        ]);

        header("Location: courses.php?success=application_submitted");
        exit();

    } catch (PDOException $e) {
        header("Location: courses.php?error=application_failed");
        exit();
    }
}

include('../header/header.php');

$success_msg = '';
$error_msg = '';

if (isset($_GET['success'])) {
    if ($_GET['success'] == 'application_submitted') {
        $success_msg = "Application submitted successfully. An admin will review it before enrollment.";
    } elseif ($_GET['success'] == 'application_pending') {
        $success_msg = "You already have a pending application for this course.";
    } elseif ($_GET['success'] == 'application_accepted') {
        $success_msg = "Your application for this course is already approved. Check My Learning for enrollment details.";
    } else {
        $success_msg = "Request completed successfully.";
    }
} elseif (isset($_GET['error'])) {
    if ($_GET['error'] == 'max_enrolled') {
        $error_msg = "You can only have one active course at a time. Go to My Learning to manage your enrollment or request a change.";
    } elseif ($_GET['error'] == 'duplicate') {
        $error_msg = "You are already enrolled in this course.";
    } elseif ($_GET['error'] == 'application_failed') {
        $error_msg = "We could not submit your application. Please try again.";
    }
}

$category = isset($_GET['cat']) ? $_GET['cat'] : '';
$query = "SELECT c.*, u.username as lecturer_name FROM courses c LEFT JOIN users u ON c.lecturer_id = u.id";
$params = [];

if ($category) {
    $query .= " WHERE c.category = ?";
    $params[] = $category;
}

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

$enrolled_ids = [];
$application_statuses = [];
$active_enrollment_count = 0;
if ($role == 'student') {
    $stmt = $pdo->prepare("SELECT course_id FROM enrollments WHERE student_id = ? AND status IN ('enrolled', 'appeal_pending')");
    $stmt->execute([$user_id]);
    $enrolled_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $active_enrollment_count = count($enrolled_ids);

    $stmt = $pdo->prepare("
        SELECT course_id, status
        FROM applications
        WHERE email = (SELECT email FROM users WHERE id = ?)
        ORDER BY created_at DESC
    ");
    $stmt->execute([$user_id]);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $application) {
        if (!isset($application_statuses[$application['course_id']])) {
            $application_statuses[$application['course_id']] = $application['status'];
        }
    }
}
?>

<div class="container py-5">

    <div class="d-flex justify-content-between align-items-center mb-5">
        <h2 class="fw-bold">Available Courses</h2>
        <?php if ($role == 'lecturer'): ?>
            <a href="add_course.php" class="btn btn-primary">Create New Course</a>
        <?php endif; ?>
    </div>

    <?php if ($success_msg): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i><?php echo $success_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($error_msg): ?>
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i><?php echo $error_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if ($role == 'student' && $active_enrollment_count >= 1): ?>
        <div class="alert alert-info mb-4">
            <i class="fas fa-info-circle me-2"></i>
            You currently have <strong><?= $active_enrollment_count; ?></strong> active enrollment. You can only study one course at a time.
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <?php foreach ($all_courses as $course): ?>
            <div class="col-md-4">
                <div class="card h-100 shadow-sm border-0">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h4 class="fw-bold mb-0"><?php echo htmlspecialchars($course['course_name']); ?></h4>
                            <?php if (!empty($course['category'])): ?>
                                <span class="badge bg-secondary"><?= htmlspecialchars($course['category']); ?></span>
                            <?php endif; ?>
                        </div>
                        <p class="text-muted small mb-2">
                            <i class="fas fa-chalkboard-teacher me-1"></i>
                            Lecturer: <?php echo htmlspecialchars($course['lecturer_name'] ?? 'TBA'); ?>
                        </p>
                        <p class="text-muted">
                            <?php echo htmlspecialchars($course['description']); ?>
                        </p>
                    </div>

                    <div class="card-footer bg-transparent border-0 pb-4">
                        <?php if ($role == 'student'): ?>
                            <?php if (in_array($course['id'], $enrolled_ids)): ?>
                                <button class="btn btn-success w-100" disabled>
                                    <i class="fas fa-check-circle me-2"></i>Enrolled
                                </button>
                            <?php elseif (($application_statuses[$course['id']] ?? '') == 'pending'): ?>
                                <button class="btn btn-warning w-100" disabled>
                                    <i class="fas fa-clock me-2"></i>Application Pending
                                </button>
                            <?php elseif (($application_statuses[$course['id']] ?? '') == 'accepted'): ?>
                                <button class="btn btn-success w-100" disabled>
                                    <i class="fas fa-user-check me-2"></i>Application Accepted
                                </button>
                            <?php elseif ($active_enrollment_count >= 1): ?>
                                <button class="btn btn-secondary w-100" disabled>
                                    <i class="fas fa-lock me-2"></i>Course Locked
                                </button>
                            <?php else: ?>
                                <a href="courses.php?enroll=<?php echo $course['id']; ?>" 
                                   class="btn btn-primary w-100">
                                   <i class="fas fa-file-signature me-2"></i>Apply Now
                                </a>
                            <?php endif; ?>
                        <?php else: ?>
                            <a href="view_course.php?id=<?php echo $course['id']; ?>" 
                               class="btn btn-outline-primary w-100">
                               <i class="fas fa-eye me-2"></i>Manage Course
                            </a>
                        <?php endif; ?>
                    </div>

                </div>
            </div>
        <?php endforeach; ?>
    </div>

</div>

<?php include('../footer/footer.php'); ?>
