<?php
namespace Misuzu;

use RuntimeException;
use Misuzu\Users\User;

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

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

if(empty($postId))
    $isNew = true;
else
    try {
        $isNew = false;
        $postInfo = $loadPostInfo();
    } catch(RuntimeException $ex) {
        echo render_error(404);
        return;
    }

if($_SERVER['REQUEST_METHOD'] === 'GET' && !empty($_GET['delete'])) {
    if(CSRF::validateRequest()) {
        $news->deletePost($postInfo);
        $msz->createAuditLog('NEWS_POST_DELETE', [$postInfo->getId()]);
        url_redirect('manage-news-posts');
    } else render_error(403);
    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, User::getCurrent());
    } 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
        }

        url_redirect('manage-news-post', ['post' => $postInfo->getId()]);
        return;
    } else $postInfo = $loadPostInfo();
    break;
}

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

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