<?php
include 'config.php';

if (!isSiswa()) {
    redirect('login.php');
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['course_id'])) {
    $course_id = sanitize($_POST['course_id']);
    $user_id = $_SESSION['user_id'];
    
    // Cek apakah sudah terdaftar
    $sql_check = "SELECT * FROM lms_enrollments WHERE id_siswa = ? AND id_course = ?";
    $stmt_check = $conn->prepare($sql_check);
    $stmt_check->bind_param('ii', $user_id, $course_id);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();
    
    if ($result_check->num_rows == 0) {
        // Daftar ke kursus
        $sql_enroll = "INSERT INTO lms_enrollments (id_siswa, id_course) VALUES (?, ?)";
        $stmt_enroll = $conn->prepare($sql_enroll);
        $stmt_enroll->bind_param('ii', $user_id, $course_id);
        
        if ($stmt_enroll->execute()) {
            // Update total siswa di course
            $sql_update = "UPDATE lms_courses SET total_siswa = total_siswa + 1 WHERE id = ?";
            $stmt_update = $conn->prepare($sql_update);
            $stmt_update->bind_param('i', $course_id);
            $stmt_update->execute();
            
            $_SESSION['success'] = "Berhasil mendaftar ke kursus!";
        } else {
            $_SESSION['error'] = "Gagal mendaftar ke kursus!";
        }
    } else {
        $_SESSION['info'] = "Anda sudah terdaftar di kursus ini!";
    }
    
    redirect('courses.php');
} else {
    redirect('courses.php');
}
?>