<?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["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") ));

    }


    //resert transfer

    if (isset($obj["quantity"]) && isset($obj["transferId"])  ) {

      @$availTransferId =  mysql_prep($obj['transferId']);
      @$availQty= mysql_prep($obj['quantity']);

      @$reason = '';

      $transferInfo = find_transfer_by_id($availTransferId);
      $prodSet = find_product_by_id($transferInfo->tbl_productId);  

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


      //all quantity for product
      $AllProdQty = countAllProductsQty( $prodSet->tbl_productId, 1 )->qty; 

      //all quantity for product and store
      $AllStoreProdQty = countAllStoreProductsQty( $prodSet->tbl_productId, 1 )->qty; 

    
      //check is valid

      $date = date("Y-m-d"); 
      $stmt = $connectMe->prepare(" UPDATE tbl_branch_product  SET tbl_branch_productAvail =? WHERE tbl_branch_productId =?  ");  

      $stmt->bindParam(1, $availQty);
      $stmt->bindParam(2, $availTransferId);

      if($stmt->execute()){

        $lastId = $connectMe->lastInsertId();


            //all quantity for product
            $AllAfterProdQty = countAllProductsQty( $prodSet->tbl_productId, 1 )->qty; 

            //all quantity for product and store
            $AllAfterStoreProdQty = countAllStoreProductsQty( $prodSet->tbl_productId, 1 )->qty; 

            $time = date("h:i:sa");
            $empId = mysql_prep($decodeToken->EMPID);

            $bQty = $transferInfo->tbl_branch_productAvail;
            $totalBQty = $AllProdQty + $AllStoreProdQty;

            $totalAfterQty = $AllAfterProdQty + $AllAfterStoreProdQty;

            $stockMessage = '';


            // save action
            if(add_new_stock_action($availTransferId, $totalBQty, $bQty, $availQty, $empId, $reason, $date, $time, $totalAfterQty)) {

              $stockMessage = 'Kandi ishusho yahindutswe';

            }else{
               $stockMessage = 'Ariko ishusho ntabwo yahindutswe';
            }



            //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 ="Izoherejwe za:  ".$prodSet->tbl_productBrand." zirahinduwe zibaye: ".$availQty.' '.$stockMessage;
                NotifyMe(0, $title, $userData->tbl_userId);

              }

            }
            

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

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

            }else{

              exit(json_encode(
                array(
                  "message" => "Stock updated",
                  "id" => $lastId 
                ) 
              ));

            }




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

  }