<?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["pd"]) ) {

    $error = array('prodDetails' => 'something went wrong');
    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") ));

    }
    //view all product information

    if (@$_GET['pd'] != "" ) {

      @$pId = mysql_prep($_GET['pd']);

      $prodSet = find_product_by_prod_id($pId); 

      if(!$prodSet){

        $error = array('prodDetails' => 'something went wrong');

        exit(json_encode($error));

      }


      if($decodeToken->UT== 'wsadmin' || $decodeToken->UT== 'admin'  ){

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

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

        $overall= $AllProdQty + $AllStoreProdQty; 
        $prodSet->tbl_productQty = $overall;


      }else if( $decodeToken->UT== 'manager' || $decodeToken->UT== 'technician' ){


        //all quantity for product and branch
        $AllBranchProdQty = (float) countAllProductsQtyForBranch($decodeToken->BID, $prodSet->tbl_productId, 1 )->qty; 
          
        $prodSet->tbl_productQty = $AllBranchProdQty;


      }


      //product details
      $prodDetails = array("prodDetails" => $prodSet);

      exit(json_encode($prodDetails));



    }  


  }else{

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


  }

