<?php
// src/Controllers/CourseController.php

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

class CourseController {
    public static function getAllCourses(?string $search = null, ?string $category = null): array {
        $db = Database::getConnection();

        $query = "SELECT * FROM courses WHERE 1=1";
        $params = [];

        if (!empty($search)) {
            $query .= " AND (title_en LIKE ? OR title_ar LIKE ? OR description_en LIKE ? OR description_ar LIKE ? OR instructor_en LIKE ?)";
            $term = '%' . $search . '%';
            $params = [$term, $term, $term, $term, $term];
        }

        if (!empty($category) && $category !== 'All') {
            $query .= " AND (category_en = ? OR category_ar = ?)";
            $params[] = $category;
            $params[] = $category;
        }

        $query .= " ORDER BY created_at DESC";

        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $courses = $stmt->fetchAll();

        // Fetch modules for each course
        $stmtMods = $db->prepare("SELECT module_index, title_en, title_ar FROM course_modules WHERE course_id = ? ORDER BY module_index ASC");

        foreach ($courses as &$course) {
            $stmtMods->execute([$course['id']]);
            $modules = $stmtMods->fetchAll();
            $course['modules_en'] = array_column($modules, 'title_en');
            $course['modules_ar'] = array_column($modules, 'title_ar');
        }

        return $courses;
    }

    public static function getCategories(): array {
        $db = Database::getConnection();
        $stmt = $db->query("SELECT DISTINCT category_en, category_ar FROM courses");
        return $stmt->fetchAll();
    }

    public static function getCourseById(string $id): ?array {
        $db = Database::getConnection();
        $stmt = $db->prepare("SELECT * FROM courses WHERE id = ?");
        $stmt->execute([$id]);
        $course = $stmt->fetch();

        if ($course) {
            $stmtMods = $db->prepare("SELECT module_index, title_en, title_ar FROM course_modules WHERE course_id = ? ORDER BY module_index ASC");
            $stmtMods->execute([$id]);
            $modules = $stmtMods->fetchAll();
            $course['modules_en'] = array_column($modules, 'title_en');
            $course['modules_ar'] = array_column($modules, 'title_ar');
        }

        return $course ?: null;
    }
}
