<?php
namespace Misuzu;

use RuntimeException;
use Misuzu\Users\User;

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

$emotes = $msz->getEmotes();

if(CSRF::validateRequest() && !empty($_GET['emote'])) {
    $emoteId = (string)filter_input(INPUT_GET, 'emote', FILTER_SANITIZE_NUMBER_INT);

    try {
        $emoteInfo = $emotes->getEmoteById($emoteId);
    } catch(RuntimeException $ex) {
        echo render_error(404);
        return;
    }

    if(!empty($_GET['delete'])) {
        $emotes->deleteEmote($emoteInfo);
        $msz->createAuditLog('EMOTICON_DELETE', [$emoteInfo->getId()]);
    } else {
        if(isset($_GET['order'])) {
            $order = filter_input(INPUT_GET, 'order');
            $offset = $order === 'i' ? 1 : ($order === 'd' ? -1 : 0);
            $emotes->updateEmoteOrderOffset($emoteInfo, $offset);
            $msz->createAuditLog('EMOTICON_ORDER', [$emoteInfo->getId()]);
        }

        if(isset($_GET['alias'])) {
            $alias = (string)filter_input(INPUT_GET, 'alias');
            if($emotes->checkEmoteString($alias) === '') {
                $emotes->addEmoteString($emoteInfo, $alias);
                $msz->createAuditLog('EMOTICON_ALIAS', [$emoteInfo->getId(), $alias]);
            }
        }
    }

    url_redirect('manage-general-emoticons');
    return;
}

Template::render('manage.general.emoticons', [
    'emotes' => $emotes->getAllEmotes(),
]);
