<?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);
    $url = (string) ($_POST['url'] ?? '');
    $linkType = (string) ($_POST['link_type'] ?? '');
    if (str_contains($url, "\t")) {
        [$linkType, $url] = array_pad(explode("\t", $url, 2), 2, '');
    }

    myronDashboardLinksRepository()->saveForUser(
        (string) $currentUser['id'],
        (string) ($_POST['title'] ?? ''),
        $url,
        $linkType
    );

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