<?php 

error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 1);

class webcurl{
	var $_url = "";
	function __construct($url){
		$this->_url = $url;
	}
	function url($url){
		$this->_url = $url;
		return $this;
	}
	function post($data,$params = []){
		$list = [];
		foreach ($data as $key => $value) {
			$list[] = "$key=$value";
		}
		return $this->curl("POST",$params,join("&",$list));
	}
	function get($params = []){
		return $this->curl("GET",$params);
	}
	var $_header = [];
	function header($header = []){
		$this->_header = $header;
		return $this;
	}
	var $headerrep = "";
	function curl($method = "GET",$get_params = [],$post_data = []){
		error_log("\n\n\n-------------------\n");
		$url = $this->_url;
		if (!empty($get_params)) {
			if (!preg_match("/\?/i",$url)) {
				$url .= "?"; 
			}
			$url .= "&".http_build_query($get_params);
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		if (strtoupper($method) == "POST") {
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		}
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20); 
		curl_setopt($ch, CURLOPT_TIMEOUT, 20);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_header);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		$response = curl_exec($ch);
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if($httpcode!=200) {
			fad::sendmail($httpcode);
			return null;
		}
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$this->headerrep = substr($response, 0, $header_size);
		$listh = explode("\n",$this->headerrep);
		foreach ($listh as $row) {
			if (preg_match("/-Cookie\s*:\s*(?<name>[^=]+)=(?<value>[^;]*?)(;|$)/i",$row,$match)) {
			}
		}

		$body = substr($response, $header_size);
		curl_close($ch);
		return $body;
	}
}

class fad{
	static function sendmail($code) { 
		date_default_timezone_set("Africa/Tunis");
		$date=date("Y-m-d H:i:s");
        mail("jokhml@gmail.com, contact@mosaique-auto.com","API FAD Fail with code ($code)","API FAD Fail with code ($code) at $date");
    }
	static function ping($host, $port, $timeout) { 
        $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
        if (!$fP) { return false; } 
        return true;
    }
	static function login(){
		$loginRequest = new webcurl("https://fad.tn/Account/Login?ReturnUrl=%2F");
		$header   = [];
		$header[] = "Host: fad.tn";
		$header[] = "Upgrade-Insecure-Requests: 1";
		$header[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36";
		$loginRequest->header($header);
		$body = $loginRequest->get();
		preg_match("/__RequestVerificationToken\" type=\"hidden\" value=\"(?<token>[^\"]+)\"/i", $body,$match);
		$token = $match["token"];
		preg_match("/__RequestVerificationToken=(?<token>[^\;]+)\;/i", $loginRequest->headerrep,$match);
		$tokencookie = $match["token"];
		$header[] = "Cookie: __RequestVerificationToken=$tokencookie";
		$loginRequest->header($header);
		$rep = $loginRequest->post([
			"__RequestVerificationToken" => $token,
			"UserName"=>"4046",
			"Password"=>"aa@@TY67",
		]);
		error_log($rep);
		if(preg_match('/validation-summary-errors/', $rep)) self::sendmail("wrong credentials");
		$aspxauth = explode(";",array_pop(explode("ASPXAUTH=",$loginRequest->headerrep)))[0];
		$NET_SessionId = explode(";",array_pop(explode("ASP.NET_SessionId=",$loginRequest->headerrep)))[0];
		file_put_contents("fad-cookies.txt", "Cookie: __RequestVerificationToken=$tokencookie; ASP.NET_SessionId=$NET_SessionId; .ASPXAUTH=$aspxauth");
		return 1;
	}

	static function initwcurl($api = "RechecherARTN"){
		$header   = [];
		$header[] = "Host: fad.tn";
		$header[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36";
		$header[] = "Referer: https://fad.tn/Home/NouvelleCommande";
		$header[] = "Accept: application/json, text/javascript, */*; q=0.01";
		$header[] = "X-Requested-With: XMLHttpRequest";
		$header[] = "Content-Type: application/x-www-form-urlencoded; charset=UTF-8";
		$header[] = "Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7,ar;q=0.6";
		$header[] = "Origin: https://fad.tn";
		$header[] = file_get_contents("fad-cookies.txt");
		$search = new webcurl("https://fad.tn/Requests/$api");
		$search->header($header);
		return $search;
	}


	static function search($api,$data){
		if (!file_exists("fad-cookies.txt")) {
			fad::login();
		}
		$rep = self::initwcurl($api)->post($data);
		$rep = json_decode($rep,true);
		if (is_null($rep)) {
			fad::login();
			$rep = self::initwcurl($api)->post($data);
			return json_decode($rep,true);
		}
		return $rep;
	}

	static function searchVIN($vin){
		return self::search("GetTypesVIN",["ID" => $vin]);
	}
	static function searchRef($ref){
		return self::search("RechecherARTN",["RefART" => $ref ]);
    }
	static function searchIMM($imm){
		return self::search("GetTypesImmatriculation",["ID" => $imm]);
	}
}

if (file_exists(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/apistoredata.json')) {
    $zz = json_decode(file_get_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/apistoredata.json'),true);
	if($zz){
		if($zz["fad_serveur"]){
			if(!fad::ping("41.226.255.80",8085, 5)) {fad::sendmail("Localserver Down");exit();}
        	echo file_get_contents("http://41.226.255.80:8085/?".$_SERVER["QUERY_STRING"]);
			exit();
		}
	}
}

if(empty($_GET["ref"])){
    if(empty($_GET["vin"])){
        if(empty($_GET["imm"])){
            echo json_encode(["data" => [ "type" => "", "res"=>[]]]);
        }else{
            echo json_encode(["data" => ["type" => "imm", "res"=>fad::searchIMM($_GET["imm"])]]);
        }
    }else{
        echo json_encode(["data" => ["type" => "vin", "res"=>fad::searchVIN($_GET["vin"])]]);
    }
}else{
    echo json_encode(["data" => ["type" => "ref","res"=>fad::searchRef($_GET["ref"])]]);
}