<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser = myronRequireAuthenticatedUser();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    myronRedirect(myronBuildAdminUrl('dashboard', ['tab' => 'personal']));
}

try {
    myronRequireCsrf($_POST['csrf_token'] ?? null);
    myronDashboardNotesRepository()->saveForUser(
        (string) $currentUser['id'],
        (string) ($_POST['title'] ?? ''),
        (string) ($_POST['content'] ?? ''),
        trim((string) ($_POST['note_id'] ?? '')) !== '' ? trim((string) ($_POST['note_id'] ?? '')) : null
    );

    myronRedirectWithFlash(myronBuildAdminUrl('dashboard', ['tab' => 'personal']), 'Note saved.', 'success');
} catch (Throwable $exception) {
    myronRedirectWithFlash(myronBuildAdminUrl('dashboard', ['tab' => 'personal']), $exception->getMessage(), 'error');
}
