<?php

declare(strict_types=1);

namespace App\Controllers;

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

class AdminCourseController extends Controller
{
    private CourseService $courses;

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

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

        return $this->view('admin/courses/index', [
            'title' => 'Gestao de cursos',
            'courses' => $this->courses->adminCourses($filters),
            'categories' => $this->courses->categories(true),
            'stats' => $this->courses->stats(),
            'filters' => $filters,
        ]);
    }

    public function approve(Request $request): void
    {
        $this->guard();
        $result = $this->courses->approve((int) $request->post('course_id'), (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Curso aprovado e publicado.' : $result['error']);
        app()->response()->back();
    }

    public function reject(Request $request): void
    {
        $this->guard();
        $result = $this->courses->reject((int) $request->post('course_id'), (int) current_user()['id'], (string) $request->post('reason', ''));
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Curso rejeitado.' : $result['error']);
        app()->response()->back();
    }

    public function suspend(Request $request): void
    {
        $this->guard();
        $result = $this->courses->suspend((int) $request->post('course_id'), (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Curso suspenso.' : $result['error']);
        app()->response()->back();
    }

    public function categories(): string
    {
        require_role('admin');

        return $this->view('admin/courses/categories', [
            'title' => 'Categorias',
            'categories' => $this->courses->categories(),
        ]);
    }

    public function storeCategory(Request $request): void
    {
        $this->guard();
        $result = $this->courses->createCategory($request->all(), (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Categoria criada.' : $result['error']);
        app()->response()->back();
    }

    private function guard(): void
    {
        require_role('admin');

        if (!verify_csrf((string) ($_POST['_csrf_token'] ?? ''))) {
            flash('error', 'Sessao expirada. Tente novamente.');
            app()->response()->back();
        }
    }
}
