<?php
include 'header.php'; // include koneksi & session
$pesan_error = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $nama = mysqli_real_escape_string($koneksi, $_POST['nama']);
    $username = mysqli_real_escape_string($koneksi, $_POST['username']);
    $password = $_POST['password'];

    // Validasi dasar
    if (empty($nama) || empty($username) || empty($password)) {
        $pesan_error = "Semua field wajib diisi!";
    } else {
        // Cek jika username sudah ada
        $cek_user = mysqli_query($koneksi, "SELECT username FROM users WHERE username = '$username'");
        if (mysqli_num_rows($cek_user) > 0) {
            $pesan_error = "Username sudah terdaftar, silakan gunakan username lain.";
        } else {
            // Hash password sebelum disimpan
            $password_hashed = password_hash($password, PASSWORD_DEFAULT);
            
            // Simpan ke database
            $query = "INSERT INTO users (nama, username, password) VALUES ('$nama', '$username', '$password_hashed')";
            if (mysqli_query($koneksi, $query)) {
                // Langsung redirect ke halaman login setelah sukses
                header("Location: login.php?status=register_sukses");
                exit;
            } else {
                $pesan_error = "Gagal mendaftar: " . mysqli_error($koneksi);
            }
        }
    }
}
?>

<div class="login-container">
    <img src="https://i.imgur.com/gA5gVvL.png" alt="Logo"> <h2>Register</h2>

    <div class="card">
        <form action="register.php" method="POST">
            <?php if(!empty($pesan_error)) { echo "<p style='color:red;'>$pesan_error</p>"; } ?>
            
            <div class="form-group">
                <label>Nama</label>
                <input type="text" name="nama" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%;">Daftar</button>
        </form>
    </div>
    <p style="margin-top: 15px;">
        Sudah punya akun? <a href="login.php">Login disini</a>
    </p>
</div>

<?php include 'footer.php'; // Ini hanya untuk menutup tag </html> ?>