<?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('user')->check(Perm::U_WARNINGS_MANAGE))
    Template::throwError(403);

if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) {
    if(!CSRF::validateRequest())
        Template::throwError(403);

    try {
        $warnInfo = $msz->usersCtx->warnings->getWarning((string)filter_input(INPUT_GET, 'w'));
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }

    $msz->usersCtx->warnings->deleteWarnings($warnInfo);
    $msz->createAuditLog('WARN_DELETE', [$warnInfo->id, $warnInfo->userId]);
    Tools::redirect($msz->urls->format('manage-users-warnings', ['user' => $warnInfo->userId]));
    return;
}

try {
    $userInfo = $msz->usersCtx->users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
} catch(RuntimeException $ex) {
    Template::throwError(404);
}

$modInfo = $msz->authInfo->userInfo;

while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $body = trim((string)filter_input(INPUT_POST, 'uw_body'));
    Template::set('warn_value_body', $body);

    $warnInfo = $msz->usersCtx->warnings->createWarning(
        $userInfo, $body, modInfo: $modInfo
    );

    $msz->createAuditLog('WARN_CREATE', [$warnInfo->id, $userInfo->id]);
    Tools::redirect($msz->urls->format('manage-users-warnings', ['user' => $userInfo->id]));
    return;
}

Template::render('manage.users.warning', [
    'warn_user' => $userInfo,
]);