<?php 
if(empty($_GET["ref"])){
    echo json_encode(["data" => ["res"=>[]]]);
    exit();
    //echo file_get_contents("http://145.223.118.124:32021/fad.php?".$_SERVER["QUERY_STRING"]);
}
function login($g=false){
  if($g){
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://fadpro.tn:8095/fad/auth/login?custNo=4046&password=aa@@TY67',
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_FOLLOWLOCATION => true,
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    file_put_contents('token.json',$response);
  }else{
    if(file_exists('token.json')){
      $response=file_get_contents('token.json')??"";
    }
    else return login(true);
  }
  return json_decode($response,true)['token']??'';
}
function query($ref,$g=false){
  $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://fadpro.tn:8095/fad/api/b2b/search?refFour='.$ref,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => array('Authorization: Bearer '.login($g))
    ));
    $response = curl_exec($curl);
    $e=curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    if($e==403&&$g!=true){
      return query($ref,true);
    }
    return $response;
}
$res=json_decode(query($_GET["ref"]))??[];
echo json_encode(["data" => ["type" => "ref","res"=>$res]]);