<?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_token($pId); 

      if(!$prodSet){

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

        exit(json_encode($error));

      }


      //view transfers

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

        $lastSalesSet = find_all_sold_pro_for_product($prodSet->tbl_productId, 1); 

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

        $lastSalesSet = find_all_sold_pro_for_product($prodSet->tbl_productId, 1);  

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

        //$lastSalesSet = find_all_transferred_for_product_and_branch($prodSet->tbl_productId, 1, $decodeToken->BID ); 

        $lastSalesSet = find_all_sold_pro_for_product($prodSet->tbl_productId, 1); 
      }


      if(empty($lastSalesSet)){

        exit(json_encode([]));

      }

      $count = 0;


    foreach ($lastSalesSet as $lastSale[]) {

      $count = $count + 1;

    }


    $message = array('count' => $count);
    exit(json_encode($message));



    }  


  }else{

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


  }

