<?php
session_start();
if($_SERVER['REQUEST_METHOD']=="POST"){
    include("db.php");
    $username=$_POST['username'];
    $password=$_POST['password'];
    $email=$_POST['email'];
    $password=password_hash($password,PASSWORD_ARGON2ID);

    $sql="SELECT * FROM `User` WHERE `Username`=?";
    $stmt=mysqli_stmt_init($conn);
    mysqli_stmt_prepare($stmt,$sql);
    mysqli_stmt_bind_param($stmt,"s",$username);
    if(!mysqli_stmt_execute($stmt)){
        die("ERROR ".mysqli_stmt_error($stmt));
    }
    else{
        $result=mysqli_stmt_get_result($stmt);
        $row=mysqli_fetch_assoc($result);
        if(!$row){
            mysqli_stmt_close($stmt);

            $sql="INSERT INTO `User`(`Username`, `Password`) VALUES (?,?)";

            $stmt=mysqli_stmt_init($conn);
            mysqli_stmt_prepare($stmt,$sql);
            mysqli_stmt_bind_param($stmt,"ss",$username,$password);
            
            if(!mysqli_stmt_execute($stmt)){
                die("ERROR ".mysqli_stmt_error($stmt));
            }
            else {

                $id=mysqli_insert_id($conn);
                mysqli_stmt_close($stmt);

                $sql="UPDATE `Customers` SET `User_id`=? WHERE `Email` = ? ";
                $stmt=mysqli_stmt_init($conn);
                mysqli_stmt_prepare($stmt,$sql);
                mysqli_stmt_bind_param($stmt,"is",$id,$email);
                if(!mysqli_stmt_execute($stmt)){
                    die("ERROR" .mysqli_stmt_error($stmt));
                }

                if(mysqli_stmt_affected_rows($stmt)==0){
                    mysqli_stmt_close($stmt);
                    $sql="UPDATE `Producers` SET `User_id`=? WHERE `CompanyEmail` = ? ";
                    $stmt=mysqli_stmt_init($conn);
                    mysqli_stmt_prepare($stmt,$sql);
                    mysqli_stmt_bind_param($stmt,"is",$id,$email);
                    if(!mysqli_stmt_execute($stmt)){
                        die("ERROR" .mysqli_stmt_error($stmt));

                    }

                    else{
                        echo"<script>alert('account created successfully');</script>";
                        echo"<script>window.location.href='ProducerHome.php';</script>";
                        exit();
                    }

                }
                else{
                    echo"<script>alert('account created successfully');</script>";
                    echo"<script>window.location.href='CustomerHome.php';</script>";
                    exit();
                }
                    
                
                
            }
        }
        else{
            echo"<script>alert(Username already registerd)</script>";
            echo"<script>window.location.href='AccountCreate.php'</script>";
            exit();
            
        }
    }
   
}
?>