<?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');

        // Get filter parameters
        $currentCat  = $_GET['category'] ?? 'all';
        $searchQuery = trim($_GET['q'] ?? '');

        // Get all active courses
        if ($currentCat !== 'all') {
            $courses = $courseModel->getByCategory($currentCat);
        } else {
            $courses = $courseModel->where('active', 1);
        }

        // Search filter
        if (!empty($searchQuery)) {
            $courses = array_filter($courses, function ($c) use ($searchQuery) {
                $name = $c['name'] ?? '';
                $desc = $c['description'] ?? '';
                $cat  = $c['category'] ?? '';
                return stripos($name, $searchQuery) !== false
                    || stripos($desc, $searchQuery) !== false
                    || stripos($cat, $searchQuery) !== false;
            });
            $courses = array_values($courses);
        }

        // Flatten categories from [ ['category' => 'computer'], ... ] to ['computer', ...]
        // Use a defensive loop in case getCategories() returns rows in different shapes.
        $rawCategories = $courseModel->getCategories();
        $categories = [];
        if (is_array($rawCategories)) {
            foreach ($rawCategories as $row) {
                if (is_array($row)) {
                    // Most likely shape: ['category' => 'computer']
                    if (isset($row['category']) && is_string($row['category'])) {
                        $categories[] = $row['category'];
                    } elseif (isset($row[0]) && is_string($row[0])) {
                        $categories[] = $row[0];
                    }
                } elseif (is_string($row)) {
                    // Already a flat string
                    $categories[] = $row;
                }
            }
            $categories = array_values(array_unique($categories));
        }

        $this->view('courses/index', [
            'title'       => 'Our Courses - Gmind Institute',
            'courses'     => $courses,
            'categories'  => $categories,
            'currentCat'  => $currentCat,
            'searchQuery' => $searchQuery,
            '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;
        });

        // Ensure content column exists — if not, use description as content
        $hasContentColumn = array_key_exists('content', $course);
        if (!$hasContentColumn) {
            $course['content'] = $course['description'] ?? '';
        }

        // One-time backfill: if description is empty but content has data,
        // copy content → description. And vice-versa. Wrapped in try-catch
        // so the page never breaks on a DB hiccup.
        try {
            if ((empty($course['description']) || trim($course['description']) === '') && !empty($course['content'])) {
                $syncStmt = $this->db->prepare('UPDATE `courses` SET `description` = :desc WHERE `id` = :id');
                $syncStmt->execute([':desc' => $course['content'], ':id' => $id]);
                $course['description'] = $course['content'];
            }

            if ((empty($course['content']) || trim($course['content']) === '') && !empty($course['description']) && $hasContentColumn) {
                $syncStmt = $this->db->prepare('UPDATE `courses` SET `content` = :content WHERE `id` = :id');
                $syncStmt->execute([':content' => $course['description'], ':id' => $id]);
                $course['content'] = $course['description'];
            }
        } catch (\Throwable $e) {
            // Silent — sync is best-effort
            error_log('Course content sync failed for ID=' . $id . ': ' . $e->getMessage());
        }

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