<?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["quantity"])  || !isset($obj["price"])  || !isset($obj["branchId"]) || !isset($obj["purchaseId"])  ) {

    $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") ));

    }


    //make transfer
    if (isset($obj["quantity"])  && isset($obj["price"])  && isset($obj["branchId"]) && isset($obj["purchaseId"])  ) {

      @$addInventId =  mysql_prep($obj['purchaseId']);
      @$addTransferQty= mysql_prep($obj['quantity']);

      @$addTransferEmp =  mysql_prep($decodeToken->EMPID);
      @$addTransferBranch =  mysql_prep($obj['branchId']);

      @$addTransferPrice =  mysql_prep($obj['price']);
      @$token =  str_replace("/","", password_hash(uniqid(), PASSWORD_BCRYPT, ['cost' => 10]));


      $branchInfo = find_branch_by_id($addTransferBranch);
      $date = date("Y-m-d");

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

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

      $status = 1;

      $inventAvailQty = $transInfo->tbl_inventoryAvailQty - $addTransferQty;

      if($inventAvailQty < 0){

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

          exit(json_encode(array("error" => "Wohereje ibiruta ibyo ufite") ));

        }else{

          exit(json_encode(array("error" => "You transferred more quantity that what you have") ));

        }

      }

      $type = "FROM-STORE";
      $sourceId = mysql_prep($transInfo->tbl_brandId);

      $transferId = 0;

      $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, $addTransferQty);

        $stmt->bindParam(3, $token);
        $stmt->bindParam(4, $branchInfo->tbl_brandId);

        $stmt->bindParam(5, $transInfo->tbl_productId);
        $stmt->bindParam(6, $status);
        
        $stmt->bindParam(7, $addInventId);
        $stmt->bindParam(8, $addTransferPrice);

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

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

        if($stmt->execute()){


          $lastId = $connectMe->lastInsertId();

          $inventAvailQty = $transInfo->tbl_inventoryAvailQty - $addTransferQty;

          
          if(update_inventory_by_id($inventAvailQty, $addInventId)){


            //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 =" Hoherejew Ibicuruzwa - (".$addTransferQty .") bya ".$prodSet->tbl_productBrand." ku ishami rya: ".$branchInfo->tbl_brandName;
                NotifyMe(0, $title, $userData->tbl_userId);

              }

            }
            

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

              exit(json_encode(array("message" => "Ibicuruzwa byoherejwe") ));

            }else{

              exit(json_encode(
                array(
                  "message" => "Transfer Completed",
                  "id" => $transInfo->tbl_productId 
                ) 
              ));

            }



          }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 =" Iyoherezwa ryibicuruzwa : - (".$addTransferQty .") bya ".$prodSet->tbl_productBrand." ku ishami rya: ".$branchInfo->tbl_brandName.' ntabwo ryakunze';
                NotifyMe(0, $title, $userData->tbl_userId);

              }

            }



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

              exit(json_encode(array("error" => "Ntabwo ibicuruzwa byabashije koherezwa") ));

            }else{

              exit(json_encode(array("error" => "Transfer Failed") ));

            }



          }




      
        }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{


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

  }