<?php header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: *");  

  header('Content-Type: application/json');

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

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

    }

    $type = mysql_prep($_GET["tp"]);
    
    //All categories

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

      $branchSet = all_branches_for_type($type, 1);

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

      $branchSet = all_branches_for_business_and_type($type, $decodeToken->BUSID, 1); 
    
    }else if($decodeToken->UT== 'manager' || $decodeToken->UT== 'technician'){

      $branchSet = all_branches_for_business_and_type($type, $decodeToken->BUSID, 1); 
    }

    foreach ($branchSet as $branch[]) {

      $item = $branch;

      $json = json_encode($item);

    }

    exit($json) ;

  }else{

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

  }