<?php

declare(strict_types=1);

namespace App\Controllers;

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

class ReviewController extends Controller
{
    private ReviewService $reviews;

    public function __construct()
    {
        $this->reviews = new ReviewService();
    }

    public function store(Request $request): void
    {
        require_role('student');

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

        $result = $this->reviews->createOrUpdate((int) $request->post('course_id'), current_user(), [
            'rating' => $request->post('rating'),
            'comment' => $request->post('comment'),
        ]);

        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Avaliacao guardada.' : $result['error']);
        app()->response()->back();
    }

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

        return $this->view('admin/reviews/index', [
            'title' => 'Avaliacoes',
            'reviews' => $this->reviews->all($filters),
            'filters' => $filters,
        ]);
    }

    public function hide(Request $request): void
    {
        $this->moderate($request, 'hidden');
    }

    public function activate(Request $request): void
    {
        $this->moderate($request, 'active');
    }

    private function moderate(Request $request, string $status): void
    {
        require_role('admin');

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

        $result = $this->reviews->updateStatus((int) $request->post('id'), $status, (int) current_user()['id']);
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Avaliacao actualizada.' : $result['error']);
        app()->response()->back();
    }
}
