<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/ChronooAuth.php';
require_once dirname(__DIR__) . '/lib/ChronooUi.php';
require_once dirname(__DIR__) . '/lib/MailNotifier.php';
require_once dirname(__DIR__) . '/lib/SmartcalConfig.php';

$error = null;
$ok = null;
if (ChronooAuth::accountId() !== null) {
    header('Location: /account/');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!ChronooAuth::verifyCsrf($_POST['csrf'] ?? null)) {
        $error = 'Session expirée, réessayez.';
    } else {
        $email = (string) ($_POST['email'] ?? '');
        $res = ChronooAuth::resendVerification($email);
        if ($res['sent']) {
            $verifyUrl = ChronooAuth::publicBaseUrl() . '/account/verify.php?token=' . urlencode((string) $res['verify_token']);
            $mailer = new MailNotifier(SmartcalConfig::fromEmail(), SmartcalConfig::fromName());
            $mailer->sendAccountVerification((string) $res['email'], (string) $res['name'], $verifyUrl);
        }
        // Message générique dans tous les cas (compte inexistant ou déjà vérifié inclus) : anti-énumération.
        $ok = "Si un compte existe avec cet email et n'est pas encore vérifié, un nouveau lien vient d'être envoyé.";
    }
}

ChronooAuth::startSession();
ChronooUi::layoutStart('Renvoyer la vérification');
?>
<div class="auth-card panel">
  <h1>Renvoyer le lien de vérification</h1>
  <p class="lede">Recevez un nouveau lien de confirmation par email.</p>
  <?php ChronooUi::flash($error, $ok); ?>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= htmlspecialchars(ChronooAuth::csrfToken(), ENT_QUOTES, 'UTF-8') ?>">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" required autocomplete="email">
    <button type="submit">Renvoyer le lien</button>
  </form>
  <p class="muted-link" style="margin-top:18px"><a href="/account/login.php">Retour à la connexion</a></p>
</div>
<?php
ChronooUi::layoutEnd();
