<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    require_once "../includes/config.php";

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

        // Insert using prepared statement (safe)
        $stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
        $stmt->bind_param("ss", $username, $password);

        try {
            $stmt->execute();
            header("Location: signin.php");
            exit;
        } catch (mysqli_sql_exception $e) {
            if ($e->getCode() == 1062) {
                $error = "Username already exists.";
            } 
        }

    }
?>

<!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 Up</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 Up</button>
        </form>

        <div class="note">Sudah punya akun? <a href="signin.php">Sign In!</a></div>
    </div>
</body>
</html>