<?php
require_once 'security_headers.php';
require 'db.php';
require_once 'csrf.php';
require_once 'rate_limiter.php';
session_start();

// Initialize rate limiter
$rateLimiter = new RateLimiter($pdo);
$clientIP = $rateLimiter->getClientIP();

// Check for registration success message
$success_message = '';
if (isset($_SESSION['registration_success'])) {
    $success_message = "Registration successful! Please login with your credentials.";
    unset($_SESSION['registration_success']);
}

if ($_POST) {
    // Check rate limit
    if (!$rateLimiter->checkLimit($clientIP)) {
        $error = "Too many login attempts. Please try again later.";
    } else {
        // Validate CSRF token
        validateCSRF();
        
        // Get input (no sanitization needed for database storage with prepared statements)
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'];
        
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        
        if ($user && password_verify($password, $user['password'])) {
            // Regenerate session ID for security
            session_regenerate_id(true);
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['display_name'] = $user['display_name'] ?: $user['username'];
            header("Location: game.php");
            exit();
        } else {
            $error = "Invalid credentials";
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>login - Asteroids</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div class="auth-container">
        <h2>Login</h2>
        <?php if ($success_message) echo "<p class='success'>" . htmlspecialchars($success_message) . "</p>"; ?>
        <?php if (isset($error)) echo "<p class='error'>" . htmlspecialchars($error) . "</p>"; ?>
        <form method="post">
            <?php echo getCSRFField(); ?>
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Login</button>
        </form>
        <p>Don't have an account <a href="register.php"> Click Here!</a></p>
    </div>
</body>
</html>