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

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

    }



    //////////////////////// sales


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


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

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

        //find user by id 
        $userInfo = find_user_by_id($decodeToken->ID);


        //find_branch_by_id
        $branchInfo = find_branch_by_id($userInfo->tbl_brandId);


        $sales = search_sold_product_by_business($search, $branchInfo->tbl_businessId, $status); 

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

        //find user by id 
        $userInfo = find_user_by_id($decodeToken->ID);


        //find_branch_by_id
        $branchInfo = find_branch_by_id($userInfo->tbl_brandId);


        $sales = search_sold_product_by_branch($search, $branchInfo->tbl_brandId, $status); 

      }

      $i = 0;

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


      foreach ($sales as $pro[]) {

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

        $i++;

      }


      exit($json) ;


    }


  }else{


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


  }




