<?php
require_once __DIR__ . '/../includes/functions.php';
requireLogin();

if (isStudent()) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$student_id = intval($_POST['student_id'] ?? 0);
requireStudentAccess($student_id);
$course_code = trim($_POST['course_code'] ?? '');
$course_name = trim($_POST['course_name'] ?? '');
$credits = floatval($_POST['credits'] ?? 0);
$lecture = intval($_POST['lecture'] ?? 0);
$practice = intval($_POST['practice'] ?? 0);
$self_study = intval($_POST['self_study'] ?? 0);
$group_id = intval($_POST['group_id'] ?? 0);
$grade = trim($_POST['grade'] ?? '');
$course_type = trim($_POST['course_type'] ?? '');
$semester = trim($_POST['semester'] ?? '');
$academic_year = trim($_POST['academic_year'] ?? '');
$notes = trim($_POST['notes'] ?? '');

$student = getStudent($student_id);
if (!$student || empty($course_code) || empty($course_name) || $credits <= 0) {
    header('Location: ' . BASE_URL . '/students/view.php?id=' . $student_id . '&error=invalid_data');
    exit;
}

try {
    $db = getDB();

    // Try to find existing course in the curriculum
    $course_id = null;
    $curriculum_course = findCourseInCurriculum($student['curriculum_id'], $course_code);

    if ($curriculum_course) {
        $course_id = $curriculum_course['id'];
    } elseif ($group_id > 0) {
        // Check if course already exists under selected group
        $stmt = $db->prepare("SELECT id FROM courses WHERE group_id = ? AND code = ?");
        $stmt->execute([$group_id, $course_code]);
        $existing = $stmt->fetch();

        if ($existing) {
            $course_id = $existing['id'];
        } else {
            // Create a new course record under the selected group
            $stmt = $db->prepare("
                INSERT INTO courses (group_id, code, name_th, credits, lecture_hours, practice_hours, self_study_hours, sort_order)
                VALUES (?, ?, ?, ?, ?, ?, ?, 0)
            ");
            $stmt->execute([$group_id, $course_code, $course_name, $credits, $lecture, $practice, $self_study]);
            $course_id = $db->lastInsertId();
        }
    }

    $stmt = $db->prepare("INSERT INTO student_courses (student_id, course_id, course_code, course_name_th, credits, lecture_hours, practice_hours, self_study_hours, grade, course_type, semester, academic_year, source_type, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'manual', ?)");
    $stmt->execute([$student_id, $course_id, $course_code, $course_name, $credits, $lecture, $practice, $self_study, $grade ?: null, $course_type ?: null, $semester ?: null, $academic_year ?: null, $notes]);
    header('Location: ' . BASE_URL . '/students/view.php?id=' . $student_id . '&added=1');
} catch (PDOException $e) {
    header('Location: ' . BASE_URL . '/students/view.php?id=' . $student_id . '&error=' . urlencode($e->getMessage()));
}
exit;
