<?php
namespace Misuzu;

use RuntimeException;
use Index\XArray;

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);

$emoteId = !empty($_GET['e']) && is_scalar($_GET['e']) ? (string)$_GET['e'] : '';
$emoteInfo = [];
$emoteStrings = [];

if(empty($emoteId))
    $isNew = true;
else
    try {
        $isNew = false;
        $emoteInfo = $msz->emotesCtx->emotes->getEmote($emoteId);
        $emoteStrings = iterator_to_array($msz->emotesCtx->emotes->getEmoteStrings($emoteInfo));
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }

// make errors not echos lol
while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $order = !empty($_POST['em_order']) && is_scalar($_POST['em_order']) ? (int)$_POST['em_order'] : '';
    $minRank = !empty($_POST['em_minrank']) && is_scalar($_POST['em_minrank']) ? (int)$_POST['em_minrank'] : '';
    $url = !empty($_POST['em_url']) && is_scalar($_POST['em_url']) ? trim((string)$_POST['em_url']) : '';
    $strings = explode(' ', !empty($_POST['em_strings']) && is_scalar($_POST['em_strings']) ? trim((string)$_POST['em_strings']) : '');

    if($isNew || $url !== $emoteInfo->url) {
        $checkUrl = $msz->emotesCtx->emotes->checkEmoteUrl($url);
        if($checkUrl !== '') {
            echo match($checkUrl) {
                'empty' => 'URL may not be empty.',
                'spaces' => 'URL may not end or start with spaces.',
                'used' => 'This URL already belongs to another emoticon.',
                default => 'URL cannot be accepted: ' . $checkUrl,
            };
            break;
        }
    }

    if($order == 0)
        $order = null;

    if($isNew) {
        $emoteInfo = $msz->emotesCtx->emotes->createEmote($url, $minRank, $order);
    } else {
        if($order === $emoteInfo->order)
            $order = null;
        if($minRank === $emoteInfo->minRank)
            $minRank = null;
        if($url === $emoteInfo->url)
            $url = null;

        if($order !== null || $minRank !== null || $url !== null)
            $msz->emotesCtx->emotes->updateEmote($emoteInfo, $order, $minRank, $url);
    }

    $sCurrent = XArray::select($emoteStrings, fn($stringInfo) => $stringInfo->string);
    $sApply = $strings;
    $sRemove = [];

    foreach($sCurrent as $string)
        if(!in_array($string, $sApply)) {
            $sRemove[] = $string;
            $msz->emotesCtx->emotes->removeEmoteString($string);
        }

    $sCurrent = array_diff($sCurrent, $sRemove);

    foreach($sApply as $string)
        if(!in_array($string, $sCurrent)) {
            $checkString = $msz->emotesCtx->emotes->checkEmoteString($string);
            if($checkString === '') {
                $msz->emotesCtx->emotes->addEmoteString($emoteInfo, $string);
            } else {
                echo match($checkString) {
                    'empty' => 'String may not be empty.',
                    'spaces' => 'String may not end or start with spaces.',
                    'case' => 'String must be lowercase.',
                    'format' => 'String must follow proper formatting.',
                    'used' => 'This string has already been used for another emoticon.',
                    default => 'String cannot be accepted: ' . $checkString,
                };
                break;
            }

            $sCurrent[] = $string;
        }

    $msz->createAuditLog(
        $isNew ? 'EMOTICON_CREATE' : 'EMOTICON_EDIT',
        [$emoteInfo->id]
    );

    Tools::redirect($msz->urls->format('manage-general-emoticon', ['emote' => $emoteInfo->id]));
    return;
}

Template::render('manage.general.emoticon', [
    'emote_new' => $isNew,
    'emote_info' => $emoteInfo,
    'emote_strings' => $emoteStrings,
]);