<?php
namespace Misuzu;

use RuntimeException;

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

$urls = $msz->getURLs();
$news = $msz->getNews();
$postId = (string)filter_input(INPUT_GET, 'p', FILTER_SANITIZE_NUMBER_INT);
$loadPostInfo = fn() => $news->getPost($postId);

if(empty($postId))
    $isNew = true;
else
    try {
        $isNew = false;
        $postInfo = $loadPostInfo();
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }

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

    $news->deletePost($postInfo);
    $msz->createAuditLog('NEWS_POST_DELETE', [$postInfo->getId()]);
    Tools::redirect($urls->format('manage-news-posts'));
    return;
}

while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $title = trim((string)filter_input(INPUT_POST, 'np_title'));
    $category = (string)filter_input(INPUT_POST, 'np_category', FILTER_SANITIZE_NUMBER_INT);
    $featured = !empty($_POST['np_featured']);
    $body = trim((string)filter_input(INPUT_POST, 'np_body'));

    if($isNew) {
        $postInfo = $news->createPost($category, $title, $body, $featured, $authInfo->getUserInfo());
    } else {
        if($category === $postInfo->getCategoryId())
            $category = null;
        if($title === $postInfo->getTitle())
            $title = null;
        if($body === $postInfo->getBody())
            $body = null;
        if($featured === $postInfo->isFeatured())
            $featured = null;

        if($category !== null || $title !== null || $body !== null || $featured !== null)
            $news->updatePost($postInfo, $category, $title, $body, $featured);
    }

    $msz->createAuditLog(
        $isNew ? 'NEWS_POST_CREATE' : 'NEWS_POST_EDIT',
        [$postInfo->getId()]
    );

    if($isNew) {
        if($postInfo->isFeatured()) {
            // Twitter integration used to be here, replace with Railgun Pulse integration
        }

        Tools::redirect($urls->format('manage-news-post', ['post' => $postInfo->getId()]));
        return;
    } else $postInfo = $loadPostInfo();
    break;
}

$categories = [];
foreach($news->getCategories() as $categoryInfo)
    $categories[$categoryInfo->getId()] = $categoryInfo->getName();

Template::render('manage.news.post', [
    'categories' => $categories,
    'post_new' => $isNew,
    'post_info' => $postInfo ?? null,
]);