<?php

declare(strict_types=1);

namespace App\Controllers;

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

class CommunicationController extends Controller
{
    private CommunicationService $communication;

    public function __construct()
    {
        $this->communication = new CommunicationService();
    }

    public function ask(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->communication->askQuestion(
            (int) $request->post('course_id'),
            (int) $request->post('lesson_id') ?: null,
            current_user(),
            (string) $request->post('body', '')
        );

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

    public function questions(Request $request): string
    {
        require_auth();
        $user = current_user();

        if (($user['role'] ?? '') === 'student') {
            return $this->view('communication/student-questions', [
                'title' => 'Minhas perguntas',
                'questions' => $this->communication->questionsForStudent((int) $user['id']),
            ]);
        }

        if (!in_array($user['role'] ?? '', ['admin', 'instructor', 'institution'], true)) {
            flash('error', 'Nao tem permissao para ver perguntas.');
            app()->response()->redirect('/dashboard');
        }

        $filters = [
            'search' => (string) $request->input('search', ''),
            'status' => (string) $request->input('status', ''),
        ];

        return $this->view('communication/manage-questions', [
            'title' => 'Perguntas dos alunos',
            'questions' => $this->communication->questionsForUser($user, $filters),
            'filters' => $filters,
        ]);
    }

    public function answer(Request $request): void
    {
        require_auth();
        $user = current_user();

        if (!in_array($user['role'] ?? '', ['admin', 'instructor', 'institution'], true)) {
            flash('error', 'Nao tem permissao para responder.');
            app()->response()->redirect('/dashboard');
        }

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

        $result = $this->communication->answerQuestion((int) $request->post('id'), $user, (string) $request->post('answer', ''));
        flash($result['ok'] ? 'success' : 'error', $result['ok'] ? 'Resposta enviada.' : $result['error']);
        app()->response()->back();
    }

    public function notifications(): string
    {
        require_auth();

        return $this->view('communication/notifications', [
            'title' => 'Notificacoes',
            'notifications' => $this->communication->notificationsForUser((int) current_user()['id']),
        ]);
    }

    public function markNotificationRead(Request $request): void
    {
        require_auth();

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

        $this->communication->markRead((int) $request->post('id'), (int) current_user()['id']);
        app()->response()->back();
    }

    public function markAllRead(Request $request): void
    {
        require_auth();

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

        $this->communication->markAllRead((int) current_user()['id']);
        app()->response()->back();
    }
}
