<?php

    $con = @mysqli_connect("localhost", "root", "abc456", "loginadminuser") 
       or die(mysqli_connect_error());
    mysqli_query($con,"set names utf8");

    //ถ้ามีการกด submit
    if(isset($_POST['submit'])){
        error_reporting(0);

        $username=$_POST['username'];
        $password=$_POST['password'];
        $firstname=$_POST['firstname'];
        $lastname=$_POST['lastname'];
 
        //การตรวจสอบไม่ให้ user เข้ามาซ้ำ
        $user_check="SELECT * FROM user WHERE username='$username' LIMIT 1";//อนุญาตให้ user 1 คน
        $result=mysqli_query($con,$user_check); //$con มาจาก require_once "connection.php"
        $user=mysqli_fetch_assoc($result);

        if($user['username'] === $username){
            echo "<script>alert('Username already exists');</script>"; //ใช้ JS Alert
        }else{
            $passwordenc=md5($password); //เป็นการเข้ารหัสเพื่อ save ใน field password

            //ไม่ต้องใส่ id เนื่องจาก id เป็น autoincrement
            $query="INSERT INTO user(username,password,firstname,lastname,userlevel)
                    VALUE('$username','$passwordenc','$firstname','$lastname','m')";
            $result=mysqli_query($con,$query); 
            if(!$result){echo "<script>alert('Username already exists');</script>";}
            else{echo "<script>alert('Insert Coplete');</script>";}
        }

    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ADD User Page</title>

</head>
<body>
    
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"><!-- ทำที่หน้าตัวเอง -->

        <lebel for="username">Username</lebel>
        <input type="text" name="username" placeholder="Enter your Userame" require>
        <br>
        <lebel for="password">Password</lebel>
        <input type="text" name="password" placeholder="Enter your Password" require>
        <br>
        <lebel for="firstname">Firstname</lebel>
        <input type="text" name="firstname" placeholder="Enter your Firstname">
        <br>
        <lebel for="lastname">Lastname</lebel>
        <input type="text" name="lastname" placeholder="Enter your Lastname">
        <br>
        <input type="submit" name="submit" value="Submit">

    </form>

</body>
</html>