<?php

declare(strict_types=1);

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

$auth = myronAuthRepository();
$hasUsers = myronHasUsers();
$registrationsEnabled = $auth->registrationsEnabled();
$flashMessages = myronConsumeFlashMessages();
$next = myronSanitizeAdminNext($_GET['next'] ?? null);

if (myronCurrentUser() !== null) {
    myronRedirect($next);
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $target = myronSanitizeAdminNext($_POST['next'] ?? null);

        if ($action === 'bootstrap-user') {
            $user = $auth->bootstrapFirstAdministrator(
                trim((string) ($_POST['display_name'] ?? '')),
                trim((string) ($_POST['email'] ?? '')),
                (string) ($_POST['password'] ?? '')
            );
            $auth->markLogin((string) $user['id']);
            myronLoginUser((string) $user['id']);
            myronRemoteUpdateCheckOnAdminLogin();
            myronRedirect($target);
        }

        if ($action === 'login') {
            $user = $auth->authenticate(
                trim((string) ($_POST['email'] ?? '')),
                (string) ($_POST['password'] ?? '')
            );

            if ($user === null) {
                throw new RuntimeException('The email/password combination was not recognized.');
            }

            $auth->markLogin((string) $user['id']);
            myronLoginUser((string) $user['id']);
            myronRemoteUpdateCheckOnAdminLogin();
            myronRedirect($target);
        }

        throw new RuntimeException('Unknown login action.');
    } catch (MyronCsrfFailureException $exception) {
        http_response_code(403);
        $flashMessages[] = myronCreateFlashMessage($exception->getMessage(), 'error');
        $next = $target ?? $next;
    } catch (Throwable $exception) {
        $flashMessages[] = myronCreateFlashMessage($exception->getMessage(), 'error');
        $next = $target;
    }
}

$csrfToken = myronCsrfToken();
$siteTitle = myronSiteTitle();
?>
<!DOCTYPE html>
<html lang="<?= myronEscape(myronSiteLanguage()) ?>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= myronEscape(myronComposeDocumentTitle($hasUsers ? 'Login' : 'Create first administrator')) ?></title>
  <?= myronRenderSiteFaviconLink() . "\n" ?>
  <?= myronRenderDefinitionFontHeadTags() . "\n" ?>
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/tokens.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/runtime-fonts.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/runtime-token-overrides.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/base.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/components.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/style-guide.css')) ?>">
  <script src="<?= myronEscape(myronBuildAssetUrl('runtime/js/interactive-atoms.min.js')) ?>" defer></script>
</head>
<body>
  <?php myronRenderFlashToastRegion($flashMessages); ?>
  <main class="mc-page-canvas mc-page-canvas--site mc-auth-layout">
    <section class="myron-auth-form myron-auth-form--standard">
      <div class="mc-workspace__header mc-workspace__header--auth">
        <span class="mc-workspace__eyebrow">Identity Foundation</span>
        <div class="mc-workspace__title-row">
          <h1 class="mc-workspace__title"><?= myronEscape($hasUsers ? 'Login to ' . $siteTitle : 'Create the first administrator') ?></h1>
        </div>
        <p class="mc-workspace__subtitle">
          <?= $hasUsers
            ? 'Sign in to continue into the MyronCMS workspace.'
            : 'This first-user bootstrap creates the initial administrator account and unlocks the protected shell.' ?>
        </p>
      </div>

      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="next" value="<?= myronEscape($next) ?>">
        <input type="hidden" name="action" value="<?= $hasUsers ? 'login' : 'bootstrap-user' ?>">

        <?php if (!$hasUsers): ?>
        <label class="sg-field">
          <span class="sg-field__label">Display Name</span>
          <input class="sg-field__control" type="text" name="display_name" required placeholder="Site Administrator">
        </label>
        <?php endif; ?>

        <label class="sg-field">
          <span class="sg-field__label">Email</span>
          <input class="sg-field__control" type="email" name="email" required placeholder="admin@example.com">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Password</span>
          <input class="sg-field__control" type="password" name="password" required placeholder="<?= $hasUsers ? 'Password' : 'At least 8 characters' ?>">
        </label>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit"><?= $hasUsers ? 'Login' : 'Create Administrator' ?></button>
          <?php if ($hasUsers): ?>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('auth.passwordReset')) ?>">Forgot Password</a>
          <?php if ($registrationsEnabled): ?>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('auth.register')) ?>">Register</a>
          <?php endif; ?>
          <?php endif; ?>
        </div>
      </form>
    </section>
  </main>
</body>
</html>
