<?php
namespace Misuzu;

use RuntimeException;
use Misuzu\Users\User;

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

$changelog = $msz->getChangelog();
$tagId = (string)filter_input(INPUT_GET, 't', FILTER_SANITIZE_NUMBER_INT);
$loadTagInfo = fn() => $changelog->getTagById($tagId);

if(empty($tagId))
    $isNew = true;
else
    try {
        $isNew = false;
        $tagInfo = $loadTagInfo();
    } catch(RuntimeException $ex) {
        echo render_error(404);
        return;
    }

if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
    if(CSRF::validateRequest()) {
        $changelog->deleteTag($tagInfo);
        $msz->createAuditLog('CHANGELOG_TAG_DELETE', [$tagInfo->getId()]);
        url_redirect('manage-changelog-tags');
    } else render_error(403);
    return;
}

while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $name = trim((string)filter_input(INPUT_POST, 'ct_name'));
    $description = trim((string)filter_input(INPUT_POST, 'ct_desc'));
    $archive = !empty($_POST['ct_archive']);

    if($isNew) {
        $tagInfo = $changelog->createTag($name, $description, $archive);
    } else {
        if($name === $tagInfo->getName())
            $name = null;
        if($description === $tagInfo->getDescription())
            $description = null;
        if($archive === $tagInfo->isArchived())
            $archive = null;

        if($name !== null || $description !== null || $archive !== null)
            $changelog->updateTag($tagInfo, $name, $description, $archive);
    }

    $msz->createAuditLog(
        $isNew ? 'CHANGELOG_TAG_CREATE' : 'CHANGELOG_TAG_EDIT',
        [$tagInfo->getId()]
    );

    if($isNew) {
        url_redirect('manage-changelog-tag', ['tag' => $tagInfo->getId()]);
        return;
    } else $tagInfo = $loadTagInfo();
    break;
}

Template::render('manage.changelog.tag', [
    'tag_new' => $isNew,
    'tag_info' => $tagInfo ?? null,
]);
