<?php
session_start();

$db = new mysqli('localhost', 'papino', 'tt1201', 'chatgpt');
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

$login_error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['username']) && isset($_POST['password'])) {
    $username = $db->real_escape_string($_POST['username']);
    $password = $db->real_escape_string($_POST['password']);
    
    $query = "SELECT * FROM users WHERE username = '$username'";
    $result = $db->query($query);
    
    if ($result && $result->num_rows > 0) {
        $user = $result->fetch_assoc();
        if ($password === $user['password']) {
            $_SESSION['user_id'] = $user['id'];
            
            // Set a cookie for authentication
            setcookie('user_auth', base64_encode(serialize($user['id'])), time() + (86400 * 30), "/"); // 86400 = 1 day

            header('Location: index.php');
            exit;
        } else {
            $login_error = 'Invalid credentials';
        }
    } else {
        $login_error = 'Invalid credentials';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <form action="login.php" method="post">
        Username: <input type="text" name="username"><br>
        Password: <input type="password" name="password"><br>
        <input type="submit" value="Login">
    </form>
    <?php if ($login_error): ?>
        <p><?php echo $login_error; ?></p>
    <?php endif; ?>
</body>
</html>