<?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('error' => '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('error' => 'something went wrong');

        exit(json_encode($error));

      }


      //view transfers

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

        $bought_pro = find_all_bought_transaction_for_products($prodSet->tbl_productId, 1); 

      }else if($decodeToken->UT== 'admin'){

        $bought_pro = find_all_bought_transaction_for_products($prodSet->tbl_productId, 1); 

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

        $bought_pro = find_all_bought_transaction_for_products_and_branch($prodSet->tbl_productId, 1, $decodeToken->BID); 
        //$bought_pro = find_all_bought_transaction_for_products($prodSet->tbl_productId, 1);
      }

      $filteredList = [];

      foreach ($bought_pro as $bought) {  
        $boughtArray = (array) $bought; 

        $filteredList[] = $boughtArray; 
      }


      exit(json_encode($filteredList));



    }  


  }else{

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


  }

