<?php
namespace Misuzu;

use RuntimeException;

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

$urls = $msz->getURLs();
$news = $msz->getNews();
$categoryId = (string)filter_input(INPUT_GET, 'c', FILTER_SANITIZE_NUMBER_INT);
$loadCategoryInfo = fn() => $news->getCategory(categoryId: $categoryId);

if(empty($categoryId))
    $isNew = true;
else
    try {
        $isNew = false;
        $categoryInfo = $loadCategoryInfo();
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }

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

    $news->deleteCategory($categoryInfo);
    $msz->createAuditLog('NEWS_CATEGORY_DELETE', [$categoryInfo->getId()]);
    Tools::redirect($urls->format('manage-news-categories'));
    return;
}

while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $name = trim((string)filter_input(INPUT_POST, 'nc_name'));
    $description = trim((string)filter_input(INPUT_POST, 'nc_desc'));
    $hidden = !empty($_POST['nc_hidden']);

    if($isNew) {
        $categoryInfo = $news->createCategory($name, $description, $hidden);
    } else {
        if($name === $categoryInfo->getName())
            $name = null;
        if($description === $categoryInfo->getDescription())
            $description = null;
        if($hidden === $categoryInfo->isHidden())
            $hidden = null;

        if($name !== null || $description !== null || $hidden !== null)
            $news->updateCategory($categoryInfo, $name, $description, $hidden);
    }

    $msz->createAuditLog(
        $isNew ? 'NEWS_CATEGORY_CREATE' : 'NEWS_CATEGORY_EDIT',
        [$categoryInfo->getId()]
    );

    if($isNew) {
        Tools::redirect($urls->format('manage-news-category', ['category' => $categoryInfo->getId()]));
        return;
    } else $categoryInfo = $loadCategoryInfo();
    break;
}

Template::render('manage.news.category', [
    'category_new' => $isNew,
    'category_info' => $categoryInfo ?? null,
]);
