<?php

declare(strict_types=1);

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

$auth = myronAuthRepository();
$mailSettings = myronMailSettingsRepository();
$flashMessages = myronConsumeFlashMessages();
$token = trim((string) ($_GET['token'] ?? ''));

if (myronCurrentUser() !== null) {
    myronRedirect(myronBuildAdminUrl('content.pages'));
}

if ($token !== '' && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    try {
        $auth->activateRegistration($token);
        myronRedirectWithFlash(
            myronBuildAdminUrl('auth.login'),
            'Your registration has been verified. You can now sign in.',
            'success'
        );
    } catch (Throwable $exception) {
        $flashMessages[] = myronCreateFlashMessage($exception->getMessage(), 'error');
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        if (!$mailSettings->isConfigured()) {
            throw new RuntimeException('Registration is unavailable until mail delivery is configured.');
        }

        $user = $auth->createPendingRegistration($_POST);
        $verificationToken = $auth->issueRegistrationToken((string) $user['id']);
        $settings = $mailSettings->getSettings();
        if (!is_array($settings)) {
            throw new RuntimeException('Mail settings are unavailable.');
        }

        $verificationUrl = myronBuildAbsoluteAdminUrl('auth.register', ['token' => $verificationToken]);
        $subject = 'Verify your MyronCMS registration';
        $htmlBody = '<p>Your MyronCMS registration is almost complete.</p>'
            . '<p><a href="' . myronEscape($verificationUrl) . '">Verify your email address</a></p>'
            . '<p>This link expires in 1 hour.</p>';
        $textBody = "Your MyronCMS registration is almost complete.\n\nVerify your email address: {$verificationUrl}\n\nThis link expires in 1 hour.";

        $result = myronMailTransportRegistry()->activeTransport()->send(new MailEnvelope(
            to: (string) $user['email'],
            subject: $subject,
            htmlBody: $htmlBody,
            textBody: $textBody,
            fromEmail: (string) ($settings['from_email'] ?? ''),
            fromName: (string) ($settings['from_name'] ?? ''),
        ));
        if (!$result->ok) {
            throw new RuntimeException($result->error ?? 'Verification email failed.');
        }

        myronRedirectWithFlash(
            myronBuildAdminUrl('auth.register'),
            'Check your email for a verification link to finish registration.',
            'success'
        );
    } catch (Throwable $exception) {
        $flashMessages[] = myronCreateFlashMessage($exception->getMessage(), 'error');
    }
}

$settings = $auth->getRegistrationSettings();
$registrationsEnabled = ($settings['registrations_enabled'] ?? false) === true;
$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('Register')) ?></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--wide">
      <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('Register for ' . $siteTitle) ?></h1>
        </div>
        <p class="mc-workspace__subtitle">Create an account to access the CMS. Registrations default to Viewer access and require email verification.</p>
      </div>

      <?php if (!$registrationsEnabled): ?>
      <div class="sg-status sg-status--error" role="status">Registration is currently closed.</div>
      <div class="sg-card__actions">
        <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('auth.login')) ?>">Back to Login</a>
      </div>
      <?php else: ?>
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">

        <label class="sg-field">
          <span class="sg-field__label">First Name</span>
          <input class="sg-field__control" type="text" name="first_name" value="<?= myronEscape((string) ($_POST['first_name'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Last Name</span>
          <input class="sg-field__control" type="text" name="last_name" value="<?= myronEscape((string) ($_POST['last_name'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Display Name</span>
          <input class="sg-field__control" type="text" name="display_name" required value="<?= myronEscape((string) ($_POST['display_name'] ?? '')) ?>">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Email</span>
          <input class="sg-field__control" type="email" name="email" required value="<?= myronEscape((string) ($_POST['email'] ?? '')) ?>">
        </label>

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

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Register</button>
          <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('auth.login')) ?>">Back to Login</a>
        </div>
      </form>
      <?php endif; ?>
    </section>
  </main>
</body>
</html>
