<?php header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: *");  

  header('Content-Type: application/json');

  $json = file_get_contents('php://input');
  $obj = json_decode($json, true);

  include '../db/connectMe.php';   
  include '../function/function.php';  

  // (C) GENERATE JWT TOKEN
  require "../vendor/autoload.php";
  use Firebase\JWT\JWT;



  // (A) NO data
  if (!isset($obj['username'])  || !isset($obj['password']) || !isset($obj['tel'])  || !isset($obj['name'])  || !isset($obj['email'])  ){

    //http_response_code(400);

    $error = array("error"=> "Fill all fields");
    exit( json_encode($error) ); 

  }






  //create account


  if (isset($obj['username'])  && isset($obj['password']) && isset($obj['tel']) && isset($obj['name'])  && isset($obj['email'])  ) {


    $username = mysql_prep($obj['username']);
    $pass = mysql_prep($obj['password']);
    
    $firstName = mysql_prep($obj['name']);
    $lastName = '';

    $phone = mysql_prep($obj['tel']);
    $email = mysql_prep($obj['email']);

    $roleId = 1;
    $pass = mysql_prep($obj['password']);

    $token = mysql_prep(uniqid());
    
      $salt1 = "09#@!&*^_+87654:3&^%!21";
      $salt2 = "0123456789";
    
      $hash = $salt1.$pass.$salt2 ;
      $hash_password = password_hash($hash, PASSWORD_BCRYPT, ['cost' => 10]);    


      $sql = $connectMe->prepare("SELECT * FROM tbl_user WHERE tbl_userName = ?   " );
      $sql->bindParam(1, $username);
      $sql->execute();
  
      if($sql->rowCount() > 0){
        
        //http_response_code(409);
        $error = array("error"=> "Username is already exist");

        exit( json_encode($error) ); 

        

      }else {


        $date = date("Y-m-d");
        $status = 1;

        $sql = $connectMe->prepare("INSERT INTO tbl_user (tbl_userFname, tbl_userLname,tbl_userTel, tbl_userEmail, tbl_userName, tbl_userPass, tbl_userDate, tbl_userToken, tbl_userStatus, tbl_roleId) VALUES (?,?,?, ?,?,?, ?,?,?, ?)" );
        
        $sql->bindParam(1, $firstName);
        $sql->bindParam(2, $lastName);

        $sql->bindParam(3, $phone);
        $sql->bindParam(4, $email);

        $sql->bindParam(5, $username);
        $sql->bindParam(6, $hash_password);

        $sql->bindParam(7, $date);
        $sql->bindParam(8, $token);

        $sql->bindParam(9, $status);
        $sql->bindParam(10, $roleId);

        if($sql->execute()){

          $message = array("message"=> 'Account Created');
          exit( json_encode($message) ); 

          

        }else{
            
            //http_response_code(500);

            $error = array("error"=> 'Something went wrong, please try again');
            exit( json_encode($error) ); 

          
        }

      }

 
  }


