<?php
namespace Misuzu;

use RuntimeException;

$usersCtx = $msz->getUsersContext();
$redirect = filter_input(INPUT_GET, 'return') ?? $_SERVER['HTTP_REFERER'] ?? $msz->getURLs()->format('index');

if(!Tools::isLocalURL($redirect))
    Template::displayInfo('Possible request forgery detected.', 403);

if(!CSRF::validateRequest())
    Template::displayInfo("Couldn't verify this request, please refresh the page and try again.", 403);

$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
    Template::displayInfo('You must be logged in to manage comments.', 403);

$currentUserInfo = $authInfo->getUserInfo();

if($usersCtx->hasActiveBan($currentUserInfo))
    Template::displayInfo('You have been banned, check your profile for more information.', 403);

$comments = $msz->getComments();
$perms = $authInfo->getPerms('global');

$commentId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$commentMode = (string)filter_input(INPUT_GET, 'm');
$commentVote = (int)filter_input(INPUT_GET, 'v', FILTER_SANITIZE_NUMBER_INT);

if(!empty($commentId)) {
    try {
        $commentInfo = $comments->getPost($commentId);
    } catch(RuntimeException $ex) {
        Template::displayInfo('Post not found.', 404);
    }

    $categoryInfo = $comments->getCategory(postInfo: $commentInfo);
}

if($commentMode !== 'create' && empty($commentInfo))
    Template::throwError(400);

switch($commentMode) {
    case 'pin':
    case 'unpin':
        if(!$perms->check(Perm::G_COMMENTS_PIN) && !$categoryInfo->isOwner($currentUserInfo))
            Template::displayInfo("You're not allowed to pin comments.", 403);

        if($commentInfo->isDeleted())
            Template::displayInfo("This comment doesn't exist!", 400);

        if($commentInfo->isReply())
            Template::displayInfo("You can't pin replies!", 400);

        $isPinning = $commentMode === 'pin';

        if($isPinning) {
            if($commentInfo->isPinned())
                Template::displayInfo('This comment is already pinned.', 400);

            $comments->pinPost($commentInfo);
        } else {
            if(!$commentInfo->isPinned())
                Template::displayInfo("This comment isn't pinned yet.", 400);

            $comments->unpinPost($commentInfo);
        }

        Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
        break;

    case 'vote':
        if(!$perms->check(Perm::G_COMMENTS_VOTE) && !$categoryInfo->isOwner($currentUserInfo))
            Template::displayInfo("You're not allowed to vote on comments.", 403);

        if($commentInfo->isDeleted())
            Template::displayInfo("This comment doesn't exist!", 400);

        if($commentVote > 0)
            $comments->addPostPositiveVote($commentInfo, $currentUserInfo);
        elseif($commentVote < 0)
            $comments->addPostNegativeVote($commentInfo, $currentUserInfo);
        else
            $comments->removePostVote($commentInfo, $currentUserInfo);

        Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
        break;

    case 'delete':
        $canDelete = $perms->check(Perm::G_COMMENTS_DELETE_OWN | Perm::G_COMMENTS_DELETE_ANY);
        if(!$canDelete && !$categoryInfo->isOwner($currentUserInfo))
            Template::displayInfo("You're not allowed to delete comments.", 403);

        $canDeleteAny = $perms->check(Perm::G_COMMENTS_DELETE_ANY);
        if($commentInfo->isDeleted())
            Template::displayInfo(
                $canDeleteAny ? 'This comment is already marked for deletion.' : "This comment doesn't exist.",
                400
            );

        $isOwnComment = $commentInfo->getUserId() === $currentUserInfo->getId();
        $isModAction  = $canDeleteAny && !$isOwnComment;

        if(!$isModAction && !$isOwnComment)
            Template::displayInfo("You're not allowed to delete comments made by others.", 403);

        $comments->deletePost($commentInfo);

        if($isModAction) {
            $msz->createAuditLog('COMMENT_ENTRY_DELETE_MOD', [
                $commentInfo->getId(),
                $commentUserId = $commentInfo->getUserId(),
                '<username>',
            ]);
        } else {
            $msz->createAuditLog('COMMENT_ENTRY_DELETE', [$commentInfo->getId()]);
        }

        Tools::redirect($redirect);
        break;

    case 'restore':
        if(!$perms->check(Perm::G_COMMENTS_DELETE_ANY))
            Template::displayInfo("You're not allowed to restore deleted comments.", 403);

        if(!$commentInfo->isDeleted())
            Template::displayInfo("This comment isn't in a deleted state.", 400);

        $comments->restorePost($commentInfo);

        $msz->createAuditLog('COMMENT_ENTRY_RESTORE', [
            $commentInfo->getId(),
            $commentUserId = $commentInfo->getUserId(),
            '<username>',
        ]);

        Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
        break;

    case 'create':
        if(!$perms->check(Perm::G_COMMENTS_CREATE) && !$categoryInfo->isOwner($currentUserInfo))
            Template::displayInfo("You're not allowed to post comments.", 403);

        if(empty($_POST['comment']) || !is_array($_POST['comment']))
            Template::displayInfo('Missing data.', 400);

        try {
            $categoryId = isset($_POST['comment']['category']) && is_string($_POST['comment']['category'])
                ? (int)$_POST['comment']['category']
                : 0;
            $categoryInfo = $comments->getCategory(categoryId: $categoryId);
        } catch(RuntimeException $ex) {
            Template::displayInfo('This comment category doesn\'t exist.', 404);
        }

        $canLock = $perms->check(Perm::G_COMMENTS_LOCK);
        if($categoryInfo->isLocked() && !$canLock)
            Template::displayInfo('This comment category has been locked.', 403);

        $commentText = !empty($_POST['comment']['text'])  && is_string($_POST['comment']['text']) ? $_POST['comment']['text'] : '';
        $commentReply = (string)(!empty($_POST['comment']['reply']) && is_string($_POST['comment']['reply']) ? (int)$_POST['comment']['reply'] : 0);
        $commentLock = !empty($_POST['comment']['lock']) && $canLock;
        $commentPin = !empty($_POST['comment']['pin']) && $perms->check(Perm::G_COMMENTS_PIN);

        if($commentLock) {
            if($categoryInfo->isLocked())
                $comments->unlockCategory($categoryInfo);
            else
                $comments->lockCategory($categoryInfo);
        }

        if(strlen($commentText) > 0) {
            $commentText = preg_replace("/[\r\n]{2,}/", "\n", $commentText);
        } else {
            if($canLock) {
                Template::displayInfo('The action has been processed.', 400);
            } else {
                Template::displayInfo('Your comment is too short.', 400);
            }
            break;
        }

        if(mb_strlen($commentText) > 5000)
            Template::displayInfo('Your comment is too long.', 400);

        if($commentReply > 0) {
            try {
                $parentInfo = $comments->getPost($commentReply);
            } catch(RuntimeException $ex) {}

            if(!isset($parentInfo) || $parentInfo->isDeleted())
                Template::displayInfo('The comment you tried to reply to does not exist.', 404);
        }

        $commentInfo = $comments->createPost(
            $categoryInfo,
            $parentInfo ?? null,
            $currentUserInfo,
            $commentText,
            $commentPin
        );

        Tools::redirect($redirect . '#comment-' . $commentInfo->getId());
        break;

    default:
        Template::displayInfo('Not found.', 404);
}
