<?php
namespace Misuzu;

use RuntimeException;

if(!$msz->getAuthInfo()->getPerms('global')->check(Perm::G_EMOTES_MANAGE))
    Template::throwError(403);

$emotes = $msz->getEmotes();

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

    try {
        $emoteInfo = $emotes->getEmote($emoteId);
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }

    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' ? 10 : ($order === 'd' ? -10 : 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]);
            }
        }
    }

    Tools::redirect($msz->getURLs()->format('manage-general-emoticons'));
    return;
}

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