<?php
    require_once "../includes/config.php";

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        $username = trim($_POST["username"]);
        $password = $_POST["password"];

        $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();

            if (password_verify($password, $user["password"])) {
                $_SESSION["data"] = $user;
                header("Location: home");
                exit;
            } else {
                $error = "Wrong Username or Password.";
            }
        } else {
            $error = "Username not found.";
        }
    }
?>

<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Hit or Run — Sign In</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <div class="card">
        <div class="logo">🂡</div>
        <h2>Hit or Run</h2>

        <?php if (!empty($error)) echo "<p style='color:red;'>$error</p>"; ?>

        <form action="" method="post">
            <label>Username</label>
            <input type="text" id="username" name="username" placeholder="Masukkan username" />

            <label>Password</label>
            <input type="password" id="password" name="password" placeholder="Masukkan password" />
            
            <button type="submit">Sign In</button>
        </form>

        <div class="note">Belum punya akun? <a href="signup.php">Sign Up!</a></div>
    </div>
</body>
</html>