<?php

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/app/saas-mail.php';

$pdo = app_db_pdo();
$user = saas_require_login();
$errors = [];
$message = '';
$verificationLink = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    app_require_csrf();
    $result = saas_request_email_verification($pdo, (int)$user['user_id'], (int)$user['tenant_id']);

    if ($result['ok']) {
        if (!empty($result['already_verified'])) {
            $message = 'Die E-Mail-Adresse ist bereits bestätigt.';
        } else {
            $message = 'Der Verifizierungslink wurde vorbereitet.';
            if (saas_should_show_auth_links() && !empty($result['token'])) {
                $verificationLink = 'email-verifizieren.php?token=' . urlencode((string)$result['token']);
            }
            if (!empty($result['token'])) {
                saas_send_email_verification_mail((string)$user['email'], (string)$result['token']);
            }
        }
    } else {
        $errors = $result['errors'];
    }
}

include 'header.php';
include 'headerline.php';
include 'nav.php';
?>

<section id="banner">
    <div class="content">
        <h2>E-Mail verifizieren</h2>

        <?php if ($message !== ''): ?>
            <div class="hint-box success">
                <p><?php echo saas_html($message); ?></p>
                <?php if ($verificationLink !== null): ?>
                    <p><a href="<?php echo saas_html($verificationLink); ?>">Dev-Link zur Verifizierung</a></p>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($errors !== []): ?>
            <div class="hint-box error">
                <?php foreach ($errors as $error): ?>
                    <p><?php echo saas_html($error); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <form method="post" action="email-verifikation-senden.php">
            <?php echo app_csrf_field(); ?>
            <p><?php echo saas_html($user['email']); ?></p>
            <ul class="actions">
                <li><button type="submit">Verifizierungslink vorbereiten</button></li>
                <li><a href="konto.php" class="button alt">Zurück</a></li>
            </ul>
        </form>
    </div>
</section>

<?php include 'footer.php'; ?>
