<?php
session_start();
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

$auth = new AuthController();
$token = $_GET['token'] ?? '';
$message = '';
$pageHelp = buildDefaultPageHelp('Passwort zurÃ¼cksetzen', '<form method="post" class="w-50">', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['token'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm'] ?? '';

    if (empty($password) || strlen($password) < 6) {
        $error = 'Das Passwort muss mindestens 6 Zeichen lang sein.';
    } elseif ($password !== $confirm) {
        $error = 'Die PasswÃ¶rter stimmen nicht Ã¼berein.';
    } elseif (!$auth->resetPassword($token, $password)) {
        $error = 'Der Link ist ungÃ¼ltig oder abgelaufen.';
    } else {
        $message = 'Passwort erfolgreich zurÃ¼ckgesetzt. Du kannst dich jetzt <a href="login.php">einloggen</a>.';
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Passwort zurÃ¼cksetzen</title>
    <link href="/assets/bootstrap/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-5">
    <h2 class="mb-4">Passwort zurÃ¼cksetzen</h2>
    <?= $pageHelp ?>

    <?php if ($message): ?>
        <div class="alert alert-success"><?= $message ?></div>
    <?php elseif ($error): ?>
        <div class="alert alert-danger"><?= $error ?></div>
    <?php endif; ?>

    <?php if (!$message): ?>
    <form method="post" class="w-50">
        <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

        <div class="mb-3">
            <label for="password" class="form-label">Neues Passwort</label>
            <input type="password" name="password" id="password" required class="form-control">
        </div>
        <div class="mb-3">
            <label for="confirm" class="form-label">Passwort bestÃ¤tigen</label>
            <input type="password" name="confirm" id="confirm" required class="form-control">
        </div>
        <button type="submit" class="btn btn-primary">Passwort speichern</button>
    </form>
    <?php endif; ?>
<?= renderFieldTooltipBootstrap($fieldTooltips ?? []) ?>
</body>
</html>
