<?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 EMAIL/PASSWORD SENT
  if (!isset($obj["username"]) || !isset($obj["pass"])  ) {

    $error = array("error"=> "no");
    exit( json_encode($error) ); 

  }


  // (A) NO EMAIL/PASSWORD SENT
  if ( isset($obj["username"]) && isset($obj["pass"])  ) {

    @$Uname = mysql_prep($obj['username']);
    @$pass =  mysql_prep($obj['pass']); 

 
    $salt1 = "09#@!&*^_+87654:3&^%!21";
    $salt2 = "0123456789";
    
    $hash = $salt1.$pass.$salt2 ;      
    $stmt = $connectMe->prepare("SELECT * FROM tbl_user  WHERE tbl_userName= ?  ");
      
    $stmt->bindParam(1, $Uname);
    $stmt->execute();  

    if ($stmt->rowCount() > 0) {  
          
      if($results = $stmt->fetch(PDO::FETCH_OBJ)){

        if($results->tbl_userStatus == 0){

          $error = array("error"=> "blocked");
          exit( json_encode($error) ); 

        }else if( password_verify($hash, $results->tbl_userPass) ){

          //find user type by id
          $UserType =  find_user_categ_by_id(mysql_prep($results->tbl_roleId));

                    //if he/she is admin 
          if( (strtolower(mysql_prep($UserType->tbl_roleName)) =="admin")   ){

            $now = strtotime("now");
            $token = array(
              "token" =>

              JWT::encode([

              "iat" => $now, // ISSUED AT - TIME WHEN TOKEN IS GENERATED
              "nbf" => $now, // NOT BEFORE - WHEN THIS TOKEN IS CONSIDERED VALID
              "exp" => $now + 3600, // EXPIRY - 1 HR (3600 SECS) FROM NOW IN THIS EXAMPLE


              "jti" => base64_encode(uniqid()), // JSON TOKEN ID

              "iss" => JWT_ISSUER, // ISSUER
              "aud" => JWT_AUD, // AUDIENCE

              "data" => [
                "ID"    => $results->tbl_userId,
                "NAME"  => $results->tbl_userName,

                "FULLNAME"  => $results->tbl_userFname." ".$results->tbl_userLname,

                "UT"  => mysql_prep($UserType->tbl_roleName),
                "TEL"  => $results->tbl_userTel
                
              ]
            ], JWT_SECRET, JWT_ALGO)

            );

            exit( json_encode($token) );


          
          }else if( (strtolower(mysql_prep($UserType->tbl_roleName)) =="client")   ){  //client

            $now = strtotime("now");
            $token = array(
              "token" =>

              JWT::encode([

              "iat" => $now, // ISSUED AT - TIME WHEN TOKEN IS GENERATED
              "nbf" => $now, // NOT BEFORE - WHEN THIS TOKEN IS CONSIDERED VALID
              "exp" => $now + 3600, // EXPIRY - 1 HR (3600 SECS) FROM NOW IN THIS EXAMPLE


              "jti" => base64_encode(uniqid()), // JSON TOKEN ID

              "iss" => JWT_ISSUER, // ISSUER
              "aud" => JWT_AUD, // AUDIENCE
              // WHATEVER USER DATA YOU WANT TO ADD
              "data" => [
                "ID"    => $results->tbl_userId,
                "NAME"  => $results->tbl_userName,

                "FULLNAME"  => $results->tbl_userFname." ".$results->tbl_userLname,

                "UT"  => mysql_prep($UserType->tbl_roleName),
                "TEL"  => $results->tbl_userTel

                
              ]
            ], JWT_SECRET, JWT_ALGO)

            );

            exit( json_encode($token) );


          }else {
            $error = array("error"=> "wrong");
            exit( json_encode($error) ); 

          }


        }else{

          $error = array("error"=> "wrong");
          exit( json_encode($error) ); 
        }

      }

    }


  }else{
    
    $error = array("error"=> "No data found");
    exit( json_encode($error) ); 
  }



