<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';

if (!function_exists('getStudentEnrolledCourses')) {
    function getStudentEnrolledCourses(PDO $pdo, int $studentId): array
    {
        if ($studentId <= 0 || !tableExists($pdo, 'core_course_students') || !tableExists($pdo, 'core_courses')) return [];
        $teacherJoin = tableExists($pdo, 'core_teachers') ? 'LEFT JOIN core_teachers t ON t.id = c.teacher_id' : '';
        $teacherSelect = tableExists($pdo, 'core_teachers') ? ', COALESCE(t.full_name, t.name, "") AS teacher_name' : ', "" AS teacher_name';
        $stmt = $pdo->prepare("SELECT c.*, cs.status AS enrollment_status, cs.joined_at, cs.created_at AS enrollment_created_at {$teacherSelect}
            FROM core_course_students cs
            INNER JOIN core_courses c ON c.id = cs.course_id
            {$teacherJoin}
            WHERE cs.student_id = ? AND LOWER(COALESCE(cs.status, 'active')) IN ('active','approved','enrolled','accepted','1')
            ORDER BY COALESCE(c.start_date, cs.joined_at, cs.created_at) DESC, c.id DESC");
        $stmt->execute([$studentId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}

if (!function_exists('isStudentEnrolledInCourse')) {
    function isStudentEnrolledInCourse(PDO $pdo, int $studentId, int $courseId): bool
    {
        if ($studentId <= 0 || $courseId <= 0 || !tableExists($pdo, 'core_course_students')) return false;
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM core_course_students WHERE student_id = ? AND course_id = ? AND LOWER(COALESCE(status, 'active')) IN ('active','approved','enrolled','accepted','1')");
        $stmt->execute([$studentId, $courseId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('isStudentActiveInCourse')) {
    function isStudentActiveInCourse(PDO $pdo, int $studentId, int $courseId): bool
    {
        if ($studentId <= 0 || $courseId <= 0 || !tableExists($pdo, 'core_course_students')) return false;
        $archiveClause = columnExists($pdo, 'core_course_students', 'archive_status')
            ? "AND LOWER(COALESCE(cs.archive_status, 'active')) = 'active'"
            : '';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM core_course_students cs INNER JOIN core_courses c ON c.id=cs.course_id WHERE cs.student_id=? AND cs.course_id=? AND LOWER(COALESCE(cs.status,'active')) IN ('active','approved','enrolled','accepted','1') {$archiveClause} AND LOWER(COALESCE(c.status,'active')) IN ('open','active')");
        $stmt->execute([$studentId,$courseId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('getStudentCourse')) {
    function getStudentCourse(PDO $pdo, int $studentId, int $courseId): ?array
    {
        if (!isStudentEnrolledInCourse($pdo, $studentId, $courseId) || !tableExists($pdo, 'core_courses')) return null;
        $teacherJoin = tableExists($pdo, 'core_teachers') ? 'LEFT JOIN core_teachers t ON t.id = c.teacher_id' : '';
        $teacherSelect = tableExists($pdo, 'core_teachers') ? ', COALESCE(t.full_name, t.name, "") AS teacher_name' : ', "" AS teacher_name';
        $stmt = $pdo->prepare("SELECT c.*, cs.status AS enrollment_status, cs.joined_at {$teacherSelect}
            FROM core_course_students cs
            INNER JOIN core_courses c ON c.id = cs.course_id
            {$teacherJoin}
            WHERE cs.student_id = ? AND cs.course_id = ? LIMIT 1");
        $stmt->execute([$studentId, $courseId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }
}

if (!function_exists('setSelectedStudentCourse')) {
    function setSelectedStudentCourse(int $courseId): void
    {
        $_SESSION['selected_core_course_id'] = $courseId;
    }
}

if (!function_exists('clearSelectedStudentCourse')) {
    function clearSelectedStudentCourse(): void
    {
        unset($_SESSION['selected_core_course_id']);
    }
}

if (!function_exists('getSelectedStudentCourseId')) {
    function getSelectedStudentCourseId(PDO $pdo, int $studentId): ?int
    {
        $fromGet = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
        if ($fromGet > 0 && isStudentEnrolledInCourse($pdo, $studentId, $fromGet)) {
            setSelectedStudentCourse($fromGet);
            return $fromGet;
        }
        $fromSession = (int)($_SESSION['selected_core_course_id'] ?? 0);
        if ($fromSession > 0 && isStudentEnrolledInCourse($pdo, $studentId, $fromSession)) {
            return $fromSession;
        }
        clearSelectedStudentCourse();
        return null;
    }
}

if (!function_exists('requireStudentCourse')) {
    function requireStudentCourse(PDO $pdo, int $studentId): array
    {
        $courseId = getSelectedStudentCourseId($pdo, $studentId);
        if (!$courseId) {
            flash('error', 'Please choose a course first.');
            redirect('student/courses.php');
        }
        $course = getStudentCourse($pdo, $studentId, $courseId);
        if (!$course) {
            clearSelectedStudentCourse();
            flash('error', 'Invalid or unavailable course.');
            redirect('student/courses.php');
        }
        return $course;
    }
}

if (!function_exists('courseUrl')) {
    function courseUrl(string $page, int $courseId): string
    {
        $sep = str_contains($page, '?') ? '&' : '?';
        return $page . $sep . 'course_id=' . $courseId;
    }
}
