<?php
require_once __DIR__ . "/config.inc.php";

$token = trim($_GET['token'] ?? $_POST['token'] ?? '');
$errors = [];
$success = false;

if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
    $errors[] = "This password reset link is invalid or has expired.";
}

if (!$errors && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        user_check_csrf();
    } catch (Throwable $e) {
        $errors[] = "Invalid CSRF token. Refresh and try again.";
    }

    $new = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    if (!valid_new_password($new)) {
        $errors[] = "New password must be at least 8 characters.";
    }
    if ($new !== $confirm) {
        $errors[] = "New password and confirmation do not match.";
    }

    if (!$errors) {
        try {
            $db = db();
            $tokenHash = hash('sha256', $token);

            $stmt = $db->prepare("
                SELECT pr.id, pr.user_id
                FROM password_resets pr
                JOIN users u ON u.id = pr.user_id
                WHERE pr.token_hash = ?
                  AND pr.used_at IS NULL
                  AND pr.expires_at > NOW()
                LIMIT 1
            ");
            $stmt->bind_param("s", $tokenHash);
            $stmt->execute();
            $reset = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            if (!$reset) {
                $errors[] = "This password reset link is invalid or has expired.";
            } else {
                $db->begin_transaction();

                $hash = password_hash($new, PASSWORD_DEFAULT);

                $stmt = $db->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
                $uid = (int)$reset['user_id'];
                $stmt->bind_param("si", $hash, $uid);
                $stmt->execute();
                $stmt->close();

                // Mark this token used and invalidate any other reset tokens.
                $resetId = (int)$reset['id'];
                $stmt = $db->prepare("UPDATE password_resets SET used_at = NOW() WHERE id = ?");
                $stmt->bind_param("i", $resetId);
                $stmt->execute();
                $stmt->close();

                $stmt = $db->prepare("DELETE FROM password_resets WHERE user_id = ? AND id <> ?");
                $stmt->bind_param("ii", $uid, $resetId);
                $stmt->execute();
                $stmt->close();

                $db->commit();
                $success = true;
            }
        } catch (Throwable $e) {
            if (isset($db) && $db instanceof mysqli) {
                try { $db->rollback(); } catch (Throwable $ignored) {}
            }
            error_log('Reset Password Error: ' . $e->getMessage());
            $errors[] = "Could not reset the password. Please request a new reset link.";
        }
    }
}

require_once __DIR__ . "/partials/header.php";
?>
<div class="row justify-content-center">
    <div class="col-md-6 col-lg-5">
        <div class="card shadow-sm">
            <div class="card-body">
                <h4 class="mb-3">Reset Password</h4>

                <?php if ($success): ?>
                    <div class="alert alert-success">
                        Your password has been reset successfully.
                    </div>
                    <div class="d-grid">
                        <a class="btn btn-primary" href="login.php">Go to Login</a>
                    </div>
                <?php else: ?>
                    <?php if ($errors): ?>
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                <?php foreach ($errors as $er): ?>
                                    <li><?= e($er) ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>

                    <?php if (!$errors || preg_match('/^[a-f0-9]{64}$/', $token)): ?>
                    <form method="post" class="row g-3">
                        <input type="hidden" name="csrf_token" value="<?= e(user_csrf()) ?>">
                        <input type="hidden" name="token" value="<?= e($token) ?>">

                        <div class="col-12">
                            <label class="form-label">New Password</label>
                            <input class="form-control" type="password" name="new_password" minlength="8" required autocomplete="new-password">
                        </div>

                        <div class="col-12">
                            <label class="form-label">Confirm New Password</label>
                            <input class="form-control" type="password" name="confirm_password" minlength="8" required autocomplete="new-password">
                        </div>

                        <div class="col-12 d-grid">
                            <button class="btn btn-primary" type="submit">Reset Password</button>
                        </div>
                    </form>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . "/partials/footer.php"; ?>
