<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

/**
 * Course Controller
 *
 * Handles course listing and detail pages for the public website.
 */
class CourseController extends Controller
{
    /**
     * Display all active courses with categories.
     *
     * @return void
     */
    public function index(): void
    {
        $courseModel = $this->model('Course');

        $courses = $courseModel->where('active', 1);
        $categories = $courseModel->getCategories();

        $this->view('courses/index', [
            'title'      => 'Our Courses - Gmind Institute',
            'courses'    => $courses,
            'categories' => $categories,
            'currentPage' => 'courses',
        ]);
    }

    /**
     * Display a single course detail page with related courses.
     *
     * @param int $id The course ID
     * @return void
     */
    public function show(int $id): void
    {
        $courseModel = $this->model('Course');

        $course = $courseModel->find($id);

        if ($course === null || !(bool) $course['active']) {
            http_response_code(404);
            $this->view('courses/index', [
                'title' => 'Course Not Found - Gmind Institute',
                'courses' => [],
                'categories' => [],
                'currentPage' => 'courses',
            ]);
            return;
        }

        // Get related courses in the same category
        $relatedCourses = $courseModel->getByCategory($course['category']);

        // Filter out the current course from related list
        $relatedCourses = array_filter($relatedCourses, function (array $c) use ($id): bool {
            return (int) $c['id'] !== $id;
        });

        $this->view('courses/show', [
            'title'           => $course['name'] . ' - Gmind Institute',
            'course'          => $course,
            'relatedCourses'  => array_values($relatedCourses),
            'currentPage'     => 'courses',
        ]);
    }
}
