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


if (!isset($obj['requests'])) {

  $error = array("error"=> "No items selected");
  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") ));

    }

$selected = $obj['requests'] ?? [];

foreach ($selected as $id) {
  // Example: sanitize and use safely
  $id = intval($id); // convert to integer to prevent injection


  // find request by id
  $requestInfo = find_transfer_request_by_id($id);

  if(!isset($requestInfo)){
    continue;
  }  


  if($requestInfo->tbl_requestStatus != "PENDING"){
    continue;
  }  


  $transferInfo = find_branch_product_by_id($requestInfo->tbl_branch_productId);

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

    continue;
  }

  // product
  $prodSet = find_product_by_id($transferInfo->tbl_productId);

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




  // branch
  $branchInfo = find_branch_by_id($requestInfo->tbl_brandId);  


  // branch
  $branchFromInfo = find_branch_by_id($transferInfo->tbl_brandId);  

  $status = "APPROVED";

  // update request

  $sql = $connectMe->prepare("UPDATE `tbl_request` SET `tbl_requestStatus` =? WHERE tbl_requestId  =?");  
  $sql->bindParam(1, $status);
  
  $sql->bindParam(2, $requestInfo->tbl_requestId);
  if($sql->execute()){


    // create transfer


        $type = "FROM-BRANCH-REQUEST";
        $sourceId = mysql_prep($transferInfo->tbl_brandId);

        $stat = 1;
        $tk = uniqid();

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

        $stmt = $connectMe->prepare(" INSERT INTO  tbl_branch_product (tbl_branch_productDate, tbl_branch_productQty, tbl_branch_productToken, tbl_brandId, tbl_productId, tbl_branch_productStatus, tbl_inventoryId, tbl_branch_productPrice, tbl_branch_productAvail, tbl_sourceId, type, tbl_source_productId )  VALUES (?,?,?, ?,?,?, ?,?,?, ?,? ,?) ");  

        $stmt->bindParam(1, $date);
        $stmt->bindParam(2, $requestInfo->qty);

        $stmt->bindParam(3, $tk);
        $stmt->bindParam(4, $requestInfo->tbl_brandId);

        $stmt->bindParam(5, $transferInfo->tbl_productId);
        $stmt->bindParam(6, $stat);
        
        $stmt->bindParam(7, $transferInfo->tbl_inventoryId);
        $stmt->bindParam(8, $transferInfo->tbl_branch_productPrice);

        $stmt->bindParam(9, $requestInfo->qty);
        $stmt->bindParam(10, $sourceId);

        $stmt->bindParam(11, $type);
        $stmt->bindParam(12, $transferInfo->tbl_branch_productId);



        if($stmt->execute()){

          $transferAvailQty = $transferInfo->tbl_branch_productAvail - $requestInfo->qty;
          

          if( update_transfer_by_id($transferAvailQty, $transferInfo->tbl_branch_productId) ) {

            //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 ="We have TRANSFERRED - (".$requestInfo->qty .") of ".$prodSet->tbl_productBrand." from ".$branchFromInfo->tbl_brandName." branch to  ".$branchInfo->tbl_brandName." branch via TRANSFER REQUEST";

                NotifyMe(0, $title, $userData->tbl_userId);

              }

            }

          }

        }else {  // transfer failed


            //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 of  (".$requestInfo->qty .") of ".$prodSet->tbl_productBrand." from ".$branchFromInfo->tbl_brandName." branch to  ".$branchInfo->tbl_brandName." branch FAILED via TRANSFER REQUEST";

                NotifyMe(0, $title, $userData->tbl_userId);

              }

            }


        }


  }else{



            //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 approval failed,  (".$requestInfo->qty .") of ".$prodSet->tbl_productBrand." from ".$branchFromInfo->tbl_brandName." branch to  ".$branchInfo->tbl_brandName."  via TRANSFER REQUEST";

                NotifyMe(0, $title, $userData->tbl_userId);

              }

            }

  }


  
}


exit(
  json_encode(
    array(
      "message" => "Approval completed"
    ) 
  )
);


  }else{

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

    exit(json_encode($error));
  }
