<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\CourseService;
use App\Services\EnrollmentService;
use App\Services\ReviewService;
use App\Services\PromotionService;

class PublicCourseController extends Controller
{
    private CourseService $courses;
    private EnrollmentService $enrollments;
    private ReviewService $reviews;
    private PromotionService $promotions;

    public function __construct()
    {
        $this->courses = new CourseService();
        $this->enrollments = new EnrollmentService();
        $this->reviews = new ReviewService();
        $this->promotions = new PromotionService();
    }

    public function index(Request $request): string
    {
        $filters = [
            'search' => (string) $request->input('search', ''),
            'category_id' => (int) $request->input('category_id', 0),
            'pricing' => (string) $request->input('pricing', ''),
        ];

        return $this->view('courses/public/index', [
            'title' => 'Cursos',
            'courses' => $this->courses->publicCourses($filters),
            'categories' => $this->courses->categories(true),
            'filters' => $filters,
        ]);
    }

    public function show(Request $request): string
    {
        $course = $this->courses->find((int) $request->input('id'));

        if (!$course || ($course['status'] ?? '') !== 'published') {
            flash('error', 'Curso nao encontrado ou indisponivel.');
            app()->response()->redirect('/courses');
        }

        $enrollment = auth_check() && has_role('student')
            ? $this->enrollments->findEnrollment((int) current_user()['id'], (int) $course['id'])
            : null;

        return $this->view('courses/public/show', [
            'title' => $course['title'],
            'course' => $course,
            'enrollment' => $enrollment,
            'reviews' => $this->reviews->activeForCourse((int) $course['id']),
            'ownReview' => auth_check() && has_role('student')
                ? $this->reviews->reviewForStudent((int) $course['id'], (int) current_user()['id'])
                : null,
            'pricing' => $this->promotions->pricingForCourse($course),
            'affiliateCode' => (string) $request->input('ref', ''),
        ]);
    }
}
