<?php
namespace Misuzu;

use RuntimeException;

if(!$msz->isLoggedIn() || !perms_check_user(MSZ_PERMS_USER, $msz->getActiveUser()->getId(), MSZ_PERM_USER_MANAGE_NOTES)) {
    echo render_error(403);
    return;
}

$hasNoteId = filter_has_var(INPUT_GET, 'n');
$hasUserId = filter_has_var(INPUT_GET, 'u');

if((!$hasNoteId && !$hasUserId) || ($hasNoteId && $hasUserId)) {
    echo render_error(400);
    return;
}

$users = $msz->getUsers();
$modNotes = $msz->getModNotes();

if($hasUserId) {
    $isNew = true;

    try {
        $userInfo = $users->getUser(filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT), 'id');
    } catch(RuntimeException $ex) {
        echo render_error(404);
        return;
    }

    $authorInfo = $msz->getActiveUser();
} elseif($hasNoteId) {
    $isNew = false;

    try {
        $noteInfo = $modNotes->getNote((string)filter_input(INPUT_GET, 'n', FILTER_SANITIZE_NUMBER_INT));
    } catch(RuntimeException $ex) {
        echo render_error(404);
        return;
    }

    if($_SERVER['REQUEST_METHOD'] === 'GET' && filter_has_var(INPUT_GET, 'delete')) {
        if(CSRF::validateRequest()) {
            $modNotes->deleteNotes($noteInfo);
            $msz->createAuditLog('MOD_NOTE_DELETE', [$noteInfo->getId(), $noteInfo->getUserId()]);
            url_redirect('manage-users-notes', ['user' => $noteInfo->getUserId()]);
        } else render_error(403);
        return;
    }

    $userInfo = $users->getUser($noteInfo->getUserId(), 'id');
    $authorInfo = $noteInfo->hasAuthorId() ? $users->getUser($noteInfo->getAuthorId(), 'id') : null;
}

while($_SERVER['REQUEST_METHOD'] === 'POST' && CSRF::validateRequest()) {
    $title = trim((string)filter_input(INPUT_POST, 'mn_title'));
    $body = trim((string)filter_input(INPUT_POST, 'mn_body'));

    if($isNew) {
        $noteInfo = $modNotes->createNote($userInfo, $title, $body, $authorInfo);
    } else {
        if($title === $noteInfo->getTitle())
            $title = null;
        if($body === $noteInfo->getBody())
            $body = null;

        if($title !== null || $body !== null)
            $modNotes->updateNote($noteInfo, $title, $body);
    }

    $msz->createAuditLog(
        $isNew ? 'MOD_NOTE_CREATE' : 'MOD_NOTE_UPDATE',
        [$noteInfo->getId(), $userInfo->getId()]
    );

    // this is easier
    url_redirect('manage-users-note', ['note' => $noteInfo->getId()]);
    return;
}

Template::render('manage.users.note', [
    'note_new' => $isNew,
    'note_info' => $noteInfo ?? null,
    'note_user' => $userInfo,
    'note_user_colour' => $users->getUserColour($userInfo),
    'note_author' => $authorInfo,
    'note_author_colour' => $users->getUserColour($authorInfo),
]);
