<?php
namespace Misuzu;

use RuntimeException;

if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
    die('Script must be called through the Misuzu route dispatcher.');

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

if(CSRF::validateRequest() && !empty($_GET['emote'])) {
    $emoteId = !empty($_GET['emote']) && is_scalar($_GET['emote']) ? (string)$_GET['emote'] : '';

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

    if(!empty($_GET['delete'])) {
        $msz->emotesCtx->emotes->deleteEmote($emoteInfo);
        $msz->createAuditLog('EMOTICON_DELETE', [$emoteInfo->id]);
    } else {
        if(isset($_GET['order'])) {
            $order = !empty($_GET['order']) && is_scalar($_GET['order']) ? (string)$_GET['order'] : '';
            $offset = $order === 'i' ? 10 : ($order === 'd' ? -10 : 0);
            $msz->emotesCtx->emotes->updateEmoteOrderOffset($emoteInfo, $offset);
            $msz->createAuditLog('EMOTICON_ORDER', [$emoteInfo->id]);
        }

        if(isset($_GET['alias'])) {
            $alias = !empty($_GET['alias']) && is_scalar($_GET['alias']) ? (string)$_GET['alias'] : '';
            if($msz->emotesCtx->emotes->checkEmoteString($alias) === '') {
                $msz->emotesCtx->emotes->addEmoteString($emoteInfo, $alias);
                $msz->createAuditLog('EMOTICON_ALIAS', [$emoteInfo->id, $alias]);
            }
        }
    }

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

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