<?php
declare(strict_types=1);

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

if (!function_exists('getTeacherCourses')) {
    function getTeacherCourses(PDO $pdo, int $teacherId): array
    {
        if ($teacherId <= 0 || !tableExists($pdo, 'core_courses')) return [];
        $stmt = $pdo->prepare('SELECT * FROM core_courses WHERE teacher_id = ? ORDER BY COALESCE(start_date, created_at) DESC, id DESC');
        $stmt->execute([$teacherId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}

if (!function_exists('teacherOwnsCourse')) {
    function teacherOwnsCourse(PDO $pdo, int $teacherId, int $courseId): bool
    {
        if ($teacherId <= 0 || $courseId <= 0 || !tableExists($pdo, 'core_courses')) return false;
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM core_courses WHERE id = ? AND teacher_id = ?');
        $stmt->execute([$courseId, $teacherId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('requireTeacherCourse')) {
    function requireTeacherCourse(PDO $pdo, int $teacherId, int $courseId): array
    {
        if (!teacherOwnsCourse($pdo, $teacherId, $courseId)) {
            http_response_code(403);
            die('Access denied.');
        }
        $stmt = $pdo->prepare('SELECT * FROM core_courses WHERE id = ? AND teacher_id = ? LIMIT 1');
        $stmt->execute([$courseId, $teacherId]);
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    }
}

if (!function_exists('teacherOwnsExam')) {
    function teacherOwnsExam(PDO $pdo, int $teacherId, int $examId): bool
    {
        if (!tableExists($pdo, 'core_exams') || !tableExists($pdo, 'core_courses')) return false;
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM core_exams e INNER JOIN core_courses c ON c.id = e.course_id WHERE e.id = ? AND c.teacher_id = ?');
        $stmt->execute([$examId, $teacherId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('teacherOwnsHomework')) {
    function teacherOwnsHomework(PDO $pdo, int $teacherId, int $homeworkId): bool
    {
        if (!tableExists($pdo, 'core_homework') || !tableExists($pdo, 'core_courses')) return false;
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM core_homework h INNER JOIN core_courses c ON c.id = h.course_id WHERE h.id = ? AND c.teacher_id = ?');
        $stmt->execute([$homeworkId, $teacherId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

if (!function_exists('teacherCanAccessStudentCourse')) {
    function teacherCanAccessStudentCourse(PDO $pdo, int $teacherId, int $studentId, int $courseId): bool
    {
        if (!tableExists($pdo, 'core_course_students')) return false;
        $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 c.teacher_id = ?');
        $stmt->execute([$studentId, $courseId, $teacherId]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
