<?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;

  //send request

  // (A) NO data
  if (!isset($obj["qty"])  || !isset($obj["branchId"])  || !isset($obj["transferId"]) ) {

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

  }


  if( AuthorizeMe(@substr(getallheaders()["Authorization"], 7)) ){

    $jwt = substr(getallheaders()["Authorization"], 7);

    //Decoding data
    $decodeToken = (json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $jwt)[1]))))->data);

    if(!isset($decodeToken)){

      exit(json_encode(array("error" => "unauthorised") ));

    }


    if(isset($obj['qty']) && isset($obj['branchId'])  && isset($obj['transferId']) ){

      @$qty =  mysql_prep($obj['qty']);
      @$branchId =  mysql_prep($obj['branchId']);

      @$transferId =  mysql_prep($obj['transferId']);
      @$employId =  mysql_prep($decodeToken->EMPID);

      @$token =  uniqid();
      $branchInfo = find_branch_by_id($branchId);

      $transferInfo = find_branch_product_by_id($transferId);

      if(!isset($transferInfo)){
        exit("Error occured ".$transferId);
      }

      $transInfo = find_transaction_by_id($transferInfo->tbl_inventoryId);

      $prodSet = find_product_by_id($transInfo->tbl_productId);  

      //find product cateory by id
      $proCategInfo = find_prod_categ_by_id($prodSet->tbl_product_categId);


        //check if balance is available
        if( $qty > $transferInfo->tbl_branch_productAvail){

          exit("Quantity is greater than available");
        }


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

        $hour = date("h:i:sa");


        $stmt = $connectMe->prepare("INSERT INTO `tbl_request`(`tbl_branch_productId`, `qty`, `tbl_brandId`, `tbl_employeeId`, `tbl_requestDate`, `tbl_requestTime`, `tbl_requestTk`, `tbl_requestTid`, `tbl_requestStatus`) VALUES (?,?,?, ?,?,?, ?,?,?) ");  

        $stmt->bindParam(1, $transferInfo->tbl_branch_productId);
        $stmt->bindParam(2, $qty);

        $stmt->bindParam(3, $branchId);
        $stmt->bindParam(4, $employId);

        $stmt->bindParam(5, $date);
        $stmt->bindParam(6, $hour);
        
        $stmt->bindParam(7, $token);
        $stmt->bindParam(8, $token);

        $stmt->bindParam(9, $status);

        if($stmt->execute()){

          
          //send notifications
          $allUsers = find_all_users_for_business($proCategInfo->tbl_businessId, 1);

          foreach ($allUsers as $userData) {    

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


            //if he/she is admin or director 
            if( (strtolower(mysql_prep($UserType->tbl_user_categName)) =="admin") || (strtolower(mysql_prep($UserType->tbl_user_categName)) =="director")  ){  

            
              $title ="Transfer request of (".$qty .") of ".$prodSet->tbl_productBrand." from ".$branchInfo->tbl_brandName." branch ";
              NotifyMe(0, $title, $userData->tbl_userId);

            }

          }
          

          if($decodeToken->LANGUAGE == 2){    //KINYARWANDA

            $message = array("message"=> $name." yongewe muri system");
            exit( json_encode($message) ); 

          }else{  //English

            $message = array("message"=> "Request received");
            exit( json_encode($message) ); 

          }
      
        }else{

          if($decodeToken->LANGUAGE == 2){    //KINYARWANDA

            $error = array("error"=> 'Igikorwa ntabwo kibashije kurangira, ongera ugerageze');
            exit( json_encode($error) ); 

          }else{


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

          }
        }
      

    }





  }else{

    $error = array("error" => "UNAUTHORIZED");

    exit(json_encode($error));
  }