<?php

use mystic\forum\orm\Topic;
use mystic\forum\orm\TopicLogMessage;
use mystic\forum\orm\User;
use mystic\forum\orm\UserPermissions;
use mystic\forum\utils\RequestUtils;

if (!$currentUser) {
    http_response_code(403);
    msg_error(__("You need to be logged in to update topics!"));
    exit;
}

$formId = "updatetopic";
$topicId = RequestUtils::getRequiredField("topic", $formId);
$title = RequestUtils::getRequiredField("title", $formId);

$topic = new Topic();
$topic->id = $topicId;

if (!$db->fetch($topic)) {
    http_response_code(404);
    msg_error(__("No topic exists with this id"));
    exit;
}

$topicAuthor = new User();
$topicAuthor->id = $topic->createdBy;

if (!$db->fetch($topicAuthor))
    $topicAuthor = null;

if ($topic->isLocked) {
    http_response_code(403);
    msg_error(__("This topic has been locked"));
    exit;
}

$canEdit = ($currentUser->id === $topicAuthor?->id && $topicAuthor?->hasPermission(UserPermissions::EDIT_OWN_TOPIC))
        || ($currentUser->hasPermission(UserPermissions::EDIT_OTHER_TOPIC));

if (!$canEdit) {
    http_response_code(403);
    msg_error(__("You don't have permission to update this topic"));
    exit;
}

$prevTitle = $topic->title;
$topic->title = $title;

$log = new TopicLogMessage();
$log->id = $db->generateId();
$log->topicId = $topic->id;
$log->authorId = $currentUser->id;
$log->params = [
    "old_value" => $prevTitle,
    "new_value" => $title,
];
$log->type = TopicLogMessage::TITLE_CHANGED;
$log->postDate = new \DateTimeImmutable();

$db->insert($log);

if (!$db->update($topic)) {
    http_response_code(500);
    msg_error(__("Failed to update topic"));
    exit;
}

header("Location: ./?_action=viewtopic&topic=" . urlencode($topicId));