<?php

session_start();
include "config/db.php";

$pesan_sukses="";
$pesan_gagal="";


if(isset($_POST['register'])){
    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = $_POST['password'];
    $rpassword = $_POST['rpassword'];
    
    if(empty($email) || empty($username) || empty($password)){
        $_SESSION['flash'] = "Semua data harus terisi";
    }else if($password !== $rpassword){
        $_SESSION['flash']=  "password tidak sama";
    }
    else{
        $hashpw = password_hash($password, PASSWORD_DEFAULT); 

        $sql = "INSERT INTO users (email,username,password,score)VALUES(?,?,?,0)";

        $stmt = $db -> prepare($sql);

        $stmt->bind_param("sss",$email,$username,$hashpw);


        if($stmt->execute()){

            header("location:index.php");
            exit();
            
        }else{
            if($stmt->erno==1602){
                $_SESSION['flash'] = "email atau username sudah pernah terdaftar";
            }else{
                $_SESSION['flash'] = "Regitrasi gagal: ".$stmt->error;
            }
        }
        $stmt -> close();
    }
}$db->close()
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>codebeater</title>
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container-register">
    <?php
    include "notif.php";

    if (isset($_SESSION['flash'])) {
        echo "<script>showNotif(" . json_encode($_SESSION['flash']) . ");</script>";
        unset($_SESSION['flash']);
    }
    ?>

        <h1 data-aos="zoom-out" data-aos-duration="1000">codebeater</h1>
        <form action="register.php" method="POST">
            <h2 data-aos="fade-up" data-aos-duration="1000">Register to get account</h2>
            <input type="email" name="email" id="email" placeholder="input your email" data-aos="fade-up" data-aos-duration="2000"><br>
            <input type="text" name="username" id="username" placeholder="input your username" data-aos="fade-up" data-aos-duration="2000"><br>
            <input type="password" name="password" id="password" placeholder="input your password" data-aos="fade-up" data-aos-duration="2000"><br>
            <input type="password" name="rpassword" id="rpassword" placeholder="repeat your password" data-aos="fade-up" data-aos-duration="2000"><br>
            <button type="submit" name="register" data-aos="fade-up" data-aos-duration="3000">REGISTER</button>
            <p data-aos="fade-up" data-aos-duration="3000"><a href="index.php" name = "login">have an account? <span> Login now!</span></a></p>
        </form>
    </div>
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <script>
        AOS.init();
    </script>
</body>

</html>