<?php

declare(strict_types=1);

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

$service = myronPasswordResetService();
$flashMessages = myronConsumeFlashMessages();
$token = trim((string) ($_GET['token'] ?? ''));

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

        if ($action === 'request-reset') {
            $service->requestReset(trim((string) ($_POST['email'] ?? '')));
            myronRedirectWithFlash(
                myronBuildAdminUrl('auth.passwordReset'),
                'If an account exists for that email address, a reset link has been sent.',
                'success'
            );
        }

        if ($action === 'reset-password') {
            $token = trim((string) ($_POST['token'] ?? ''));
            $password = (string) ($_POST['password'] ?? '');
            $confirm = (string) ($_POST['password_confirm'] ?? '');
            if ($password !== $confirm) {
                throw new RuntimeException('Passwords must match.');
            }

            $service->resetPassword($token, $password);
            myronRedirectWithFlash(
                myronBuildAdminUrl('auth.login'),
                'Your password has been reset. Please sign in.',
                'success'
            );
        }

        throw new RuntimeException('Unknown password reset action.');
    } catch (Throwable $exception) {
        $flashMessages[] = myronCreateFlashMessage($exception->getMessage(), 'error');
    }
}

$csrfToken = myronCsrfToken();
$tokenState = $token !== '' ? $service->validateToken($token) : null;
?>
<!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('Password Reset')) ?></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 myron-password-recovery-request-form">
      <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"><?= $token !== '' ? 'Create a New Password' : 'Forgot Password' ?></h1>
        </div>
        <p class="mc-workspace__subtitle">
          <?= $token !== '' ? 'Enter a new password to finish the magic-link reset flow.' : 'Enter your email address and we will send a magic link if the account exists.' ?>
        </p>
      </div>

      <?php if ($token !== '' && $tokenState === null): ?>
      <div class="sg-status sg-status--error" role="status">That password reset link is invalid or expired.</div>
      <div class="sg-card__actions">
        <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('auth.passwordReset')) ?>">Request a new link</a>
      </div>
      <?php elseif ($token !== ''): ?>
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="reset-password">
        <input type="hidden" name="token" value="<?= myronEscape($token) ?>">

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

        <label class="sg-field">
          <span class="sg-field__label">Confirm Password</span>
          <input class="sg-field__control" type="password" name="password_confirm" required placeholder="Repeat password">
        </label>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Reset Password</button>
        </div>
      </form>
      <?php else: ?>
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="request-reset">

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

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Send Reset Link</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>
