<?php
include('inc/db.php');

$token = $_GET['token'] ?? null;
$error = '';
$success = false;
$username = '';

if (!$token) {
    die("Ungültiger Zugriff.");
}

// Token prüfen: existiert, nicht abgelaufen, nicht verwendet
$stmt = mysqli_prepare($conn, "
    SELECT prt.id, prt.user_id, prt.expires_at, u.username 
    FROM password_reset_tokens prt 
    JOIN users u ON prt.user_id = u.id 
    WHERE prt.token = ? AND prt.used = 0
");
mysqli_stmt_bind_param($stmt, "s", $token);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$token_data = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);

if (!$token_data) {
    $error = "Ungültiger oder bereits verwendeter Link.";
} else if (strtotime($token_data['expires_at']) < time()) {
    $error = "Der Link ist abgelaufen. Bitte fordere einen neuen Link an.";
} else {
    $username = htmlspecialchars($token_data['username']);

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';

        if (strlen($new_password) < 6) {
            $error = "Das Passwort muss mindestens 6 Zeichen lang sein.";
        } else if ($new_password !== $confirm_password) {
            $error = "Die Passwörter stimmen nicht überein.";
        } else {
            // Neues Passwort hashen und speichern
            $hashed = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = mysqli_prepare($conn, "UPDATE users SET password = ? WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "si", $hashed, $token_data['user_id']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            // Token als verwendet markieren
            $stmt = mysqli_prepare($conn, "UPDATE password_reset_tokens SET used = 1 WHERE id = ?");
            mysqli_stmt_bind_param($stmt, "i", $token_data['id']);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);

            $success = true;
        }
    }
}

require_once 'inc/public_header.php';
?>

<div class="container d-flex justify-content-center align-items-start py-4 pt-5">
    <div class="card bg-light shadow w-100" style="max-width: 400px;">
        <div class="card-body">
            <h4 class="card-title text-center mb-4 fs-3">Neues Passwort</h4>

            <?php if ($error): ?>
                <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
            <?php elseif ($success): ?>
                <div class="alert alert-success">
                    Dein Passwort wurde erfolgreich geändert!<br>
                    <a href="login.php" class="alert-link">Zum Login</a>
                </div>
            <?php else: ?>
                <p>Neues Passwort für: <strong><?= $username ?></strong></p>
                <form method="post">
                    <div class="mb-3">
                        <label for="new_password" class="form-label">Neues Passwort</label>
                        <input type="password" class="form-control" id="new_password" name="new_password" required minlength="6">
                    </div>
                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Bestätigen</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Passwort speichern</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include('inc/footer.php'); ?>