Your IP : 216.73.216.93


Current Path : /home/users/unlimited/www/nigeria.codeskitter.site/
Upload File :
Current File : /home/users/unlimited/www/nigeria.codeskitter.site/enroll.php

<?php
include 'includes/config.php';

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

if(!isset($_GET['course_id'])) {
    header("Location: courses.php");
    exit();
}

$course_id = $_GET['course_id'];

// Check if course is free
$course_sql = "SELECT * FROM courses WHERE id = ? AND current_price = 0";
$course_stmt = $conn->prepare($course_sql);
$course_stmt->bind_param("i", $course_id);
$course_stmt->execute();
$course_result = $course_stmt->get_result();

if($course_result->num_rows == 0) {
    $_SESSION['error'] = "Course not found or not free";
    header("Location: courses.php");
    exit();
}

$course = $course_result->fetch_assoc();

// Check if already enrolled
$enrollment_sql = "SELECT * FROM enrollments WHERE user_id = ? AND course_id = ?";
$enrollment_stmt = $conn->prepare($enrollment_sql);
$enrollment_stmt->bind_param("ii", $_SESSION['user_id'], $course_id);
$enrollment_stmt->execute();

if($enrollment_stmt->get_result()->num_rows > 0) {
    $_SESSION['info'] = "You are already enrolled in this course";
    header("Location: course-content.php?id=" . $course_id);
    exit();
}

// Enroll user
$enroll_sql = "INSERT INTO enrollments (user_id, course_id, enrolled_at) VALUES (?, ?, NOW())";
$enroll_stmt = $conn->prepare($enroll_sql);
$enroll_stmt->bind_param("ii", $_SESSION['user_id'], $course_id);

if($enroll_stmt->execute()) {
    $_SESSION['success'] = "Successfully enrolled in the course!";
    header("Location: course-content.php?id=" . $course_id);
    exit();
} else {
    $_SESSION['error'] = "Error enrolling in course";
    header("Location: course-details.php?id=" . $course_id);
    exit();
}
?>