<?php

require_once __DIR__ . '/functions.php';

$pdo = app_db_pdo();
$email = trim((string)($_POST['email'] ?? ''));
$tenantSlug = trim((string)($_POST['tenant_slug'] ?? ''));
$errors = [];
$message = '';
$resetLink = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    app_require_csrf();
    $result = saas_request_password_reset($pdo, $email, $tenantSlug);

    if ($result['ok']) {
        $message = $result['message'];
        if (saas_should_show_auth_links() && !empty($result['token'])) {
            $resetLink = 'passwort-zuruecksetzen.php?token=' . urlencode((string)$result['token']);
        }
    } else {
        $errors = $result['errors'];
    }
}

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

<section id="banner">
    <div class="content">
        <h2>Passwort vergessen</h2>

        <?php if ($message !== ''): ?>
            <div class="hint-box success">
                <p><?php echo saas_html($message); ?></p>
                <?php if ($resetLink !== null): ?>
                    <p><a href="<?php echo saas_html($resetLink); ?>">Dev-Link zum Zuruecksetzen</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="passwort-vergessen.php">
            <?php echo app_csrf_field(); ?>
            <div class="row">
                <div class="col-6 col-12-small">
                    <label for="email">E-Mail</label>
                    <input type="email" name="email" id="email" value="<?php echo saas_html($email); ?>" required>
                </div>
                <div class="col-6 col-12-small">
                    <label for="tenant_slug">Kundenkuerzel</label>
                    <input type="text" name="tenant_slug" id="tenant_slug" value="<?php echo saas_html($tenantSlug); ?>" placeholder="optional">
                </div>
            </div>
            <ul class="actions">
                <li><button type="submit">Link vorbereiten</button></li>
                <li><a href="login.php" class="button alt">Zum Login</a></li>
            </ul>
        </form>
    </div>
</section>

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