<?php
namespace Misuzu\Http\Handlers;

use Misuzu\CSRF;
use Misuzu\Template;
use Misuzu\Users\User;
use Misuzu\Users\UserSession;

final class ForumHandler extends Handler {
    public function markAsReadGET($response, $request) {
        if(!UserSession::hasCurrent() || !User::hasCurrent())
            return 403;

        $forumId = (int)$request->getParam('forum', FILTER_SANITIZE_NUMBER_INT);
        $response->setContent(Template::renderRaw('confirm', [
            'title' => 'Mark forum as read',
            'message' => 'Are you sure you want to mark ' . ($forumId === 0 ? 'the entire' : 'this') . ' forum as read?',
            'return' => url($forumId ? 'forum-category' : 'forum-index', ['forum' => $forumId]),
            'params' => [
                'forum' => $forumId,
            ]
        ]));
    }

    public function markAsReadPOST($response, $request) {
        if(!UserSession::hasCurrent() || !User::hasCurrent())
            return 403;

        if(!$request->isFormContent())
            return 400;

        $token = $request->getContent()->getParam('_csrf');
        if(empty($token) || !CSRF::validate($token))
            return 400;

        $forumId = (int)$request->getContent()->getParam('forum', FILTER_SANITIZE_NUMBER_INT);
        forum_mark_read($forumId, User::getCurrent()->getId());
        $redirect = url($forumId ? 'forum-category' : 'forum-index', ['forum' => $forumId]);

        $response->redirect($redirect, false);
    }
}
