<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Services\CourseService;

class CourseManageController extends Controller
{
    private CourseService $courses;

    public function __construct()
    {
        $this->courses = new CourseService();
    }

    public function index(Request $request): string
    {
        $this->requireCreator();
        $filters = [
            'status' => (string) $request->input('status', ''),
            'search' => (string) $request->input('search', ''),
        ];

        return $this->view('courses/manage/index', [
            'title' => 'Meus cursos',
            'courses' => $this->courses->ownerCourses((int) current_user()['id'], (string) current_user()['role'], $filters),
            'filters' => $filters,
        ]);
    }

    public function create(): string
    {
        $this->requireCreator();

        return $this->view('courses/manage/form', [
            'title' => 'Criar curso',
            'course' => null,
            'publicationChecklist' => null,
            'categories' => $this->courses->categories(true),
            'action' => '/manage/courses/store',
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireCreator();
        $this->guardCsrf($request);

        $result = $this->courses->create($request->all(), current_user());

        if (!$result['ok']) {
            keep_old($request->all());
            flash('error', implode(' ', $result['errors']));
            app()->response()->back();
        }

        clear_old();
        flash('success', 'Curso criado em rascunho.');
        app()->response()->redirect('/manage/courses');
    }

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

        if (!$course || !$this->courses->canManage($course, current_user())) {
            flash('error', 'Curso nao encontrado.');
            app()->response()->redirect('/manage/courses');
        }

        return $this->view('courses/manage/form', [
            'title' => 'Editar curso',
            'course' => $course,
            'publicationChecklist' => $this->courses->publicationChecklist((int) $course['id']),
            'categories' => $this->courses->categories(true),
            'action' => '/manage/courses/update',
        ]);
    }

    public function update(Request $request): void
    {
        $this->requireCreator();
        $this->guardCsrf($request);

        $result = $this->courses->update((int) $request->post('id'), $request->all(), current_user());

        if (!$result['ok']) {
            keep_old($request->all());
            flash('error', implode(' ', $result['errors']));
            app()->response()->back();
        }

        clear_old();
        flash('success', 'Curso actualizado.');
        app()->response()->redirect('/manage/courses');
    }

    public function submit(Request $request): void
    {
        $this->requireCreator();
        $this->guardCsrf($request);

        $result = $this->courses->submit((int) $request->post('course_id'), current_user());

        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Curso submetido para aprovacao.' : $result['error']);
        app()->response()->back();
    }

    private function requireCreator(): void
    {
        require_auth();

        if (!in_array(current_user()['role'] ?? '', ['admin', 'instructor', 'institution'], true)) {
            flash('error', 'Apenas instrutores, instituicoes e admin podem gerir cursos.');
            app()->response()->redirect('/dashboard');
        }
    }

    private function guardCsrf(Request $request): void
    {
        if (!verify_csrf((string) $request->post('_csrf_token', ''))) {
            flash('error', 'Sessao expirada. Tente novamente.');
            app()->response()->back();
        }
    }
}
