<?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($_GET["bd"])  || !isset($_GET["br"])) {

  if (!isset($_GET["bd"]) || !isset($_GET["br"]) ) {

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

    }



    ////////////////////////products


    if (  (mysql_prep(@$_GET['bd']) != "") && (mysql_prep(@$_GET['br']) != "")   ) {


      @$prodSpec = mysql_prep($_GET['bd']); 
      @$status  = 1; 

      @$branchId  = mysql_prep($_GET['br']); 
     // $branchInfo = find_branch_by_id($prodBranch) ;


      $newPro = find_all_products_for_spec($prodSpec, $status); 

      $i = 0;


      if(empty($newPro)){
        exit(json_encode([]));
      }

      foreach ($newPro as $pro[] ) {
         

        if($branchId == 0 ){ //all branch 

          //all quantity for product
          $AllProdQty = countAllProductsQty( $pro[$i]->tbl_productId, 1 )->qty;

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


          $overall= $AllProdQty + $AllStoreProdQty; 
          $pro[$i]->tbl_productQty = $overall;


        }else {

          //all quantity for product
          $AllProdQty = countAllProductsQtyForCurrentBranch( $pro[$i]->tbl_productId, 1, $branchId )->qty;

          //all quantity for product and store
          $AllStoreProdQty = countAllStoreProductsQtyForCurrentBranch( $pro[$i]->tbl_productId, 1, $branchId )->qty;


          $overall= $AllProdQty + $AllStoreProdQty; 
          $pro[$i]->tbl_productQty = $overall;


        }











        $item = $pro;
        $json = json_encode($item);

        $i++;

      }


      exit($json) ;

    }




  }else{
   

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


  }




