<?php
namespace Misuzu;

use Misuzu\Users\User;

require_once '../../../misuzu.php';

if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_GENERAL, User::getCurrent()->getId(), MSZ_PERM_FORUM_TOPIC_REDIRS)) {
    echo render_error(403);
    return;
}

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    if(!CSRF::validateRequest())
        throw new \Exception("Request verification failed.");

    $rTopicId = (int)filter_input(INPUT_POST, 'topic_redir_id');
    $rTopicURL = trim((string)filter_input(INPUT_POST, 'topic_redir_url'));

    if($rTopicId < 1)
        throw new \Exception("Invalid topic id.");

    AuditLog::create(AuditLog::FORUM_TOPIC_REDIR_CREATE, [$rTopicId]);
    forum_topic_redir_create($rTopicId, User::getCurrent()->getId(), $rTopicURL);
    url_redirect('manage-forum-topic-redirs');
    return;
}

if(filter_input(INPUT_GET, 'm') === 'explode') {
    if(!CSRF::validateRequest())
        throw new \Exception("Request verification failed.");

    $rTopicId = (int)filter_input(INPUT_GET, 't');
    AuditLog::create(AuditLog::FORUM_TOPIC_REDIR_REMOVE, [$rTopicId]);
    forum_topic_redir_remove($rTopicId);
    url_redirect('manage-forum-topic-redirs');
    return;
}

$pagination = new Pagination(forum_topic_redir_count(), 20);
if(!$pagination->hasValidOffset()) {
    echo render_error(404);
    return;
}

$redirs = forum_topic_redir_all($pagination->getOffset(), $pagination->getRange());

Template::render('manage.forum.redirs', [
    'manage_redirs' => $redirs,
    'manage_redirs_pagination' => $pagination,
]);