<?php

class TecAll2{
	static $off = false;
	static function getApiKey($generate = false, $auto = false){
		
		if(!$generate){
			if (file_exists(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/tecall.json')) {
				$rep = json_decode(file_get_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/tecall.json'),true);
				if($rep){
					if(TecAll2::$off??false) {
						file_put_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/tecall.json', "");
						return "";
					}
					if (!empty($rep["apiKey"])&&(!$auto||($auto&&$rep["status"]!="200"))) {
						return $rep["apiKey"];
					}
				}
			}
		}
		if(TecAll2::$off??false) {
			file_put_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/tecall.json', "");
			return "";
		}
		//return "";
		if (file_exists(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/refresh_token.json')) {
			$repx = json_decode(file_get_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/refresh_token.json'),true);
			if($repx){
				if($new=file_get_contents("https://webservice.tecalliance.services/openid-connect/refresh?catalog=tecdoc&token=".$repx['refresh_token'])){
					file_put_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/refresh_token.json', $new);
					$repx=json_decode($new,true);
				}
			}
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'https://webservice.tecalliance.services/auth/v1/services/AuthWS.jsonEndpoint');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, '{"getAPIKeyForOpenIDConnect":{"catalog":"tecdoc","idToken":"'.$repx['id_token'].'","accessToken":"'.$repx['access_token'].'","ttlSeconds":31536000}}');
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20); 
		curl_setopt($ch, CURLOPT_TIMEOUT, 20);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		
		$headers = array();
		$headers[] = 'Accept: application/json, text/plain, */*';
		$headers[] = 'Referer: https://web.tecalliance.net/tecdocsw/fr/login';
		$headers[] = 'Origin: https://web.tecalliance.net';
		$headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36';
		$headers[] = 'Sec-Fetch-Mode: cors';
		$headers[] = 'Content-Type: application/json; charset=UTF-8';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$result = curl_exec($ch);
		if (curl_errno($ch)) {
		    echo 'Error:' . curl_error($ch);
		}
		file_put_contents(implode("/",array_slice(explode("/",realpath(".")), 0, -1)).'/tecall.json', $result);
		$rep = json_decode($result, true);
		if(!isset($rep["apiKey"])) return "";
		return $rep["apiKey"];
	}
	static function query($body,$first = true){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'https://webservice.tecalliance.services/pegasus-3-0/services/TecdocToCatDLB.jsonEndpoint');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
		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);
		$headers = array();
		$headers[] = 'Origin: https://webservice.tecalliance.services';
		$headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36';
		$headers[] = 'Sec-Fetch-Mode: cors';
		$headers[] = 'Content-Type: application/json';
		$headers[] = 'Accept: application/json, text/plain, */*';
		$headers[] = 'X-Api-Key: '.self::getApiKey();
		
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		$result = curl_exec($ch);
		if (curl_errno($ch)) {
		    echo 'Error:' . curl_error($ch);
		}
		curl_close($ch);
		$rep = json_decode($result,true);
        if($rep["status"] == 401 && $first){
            self::getApiKey(false,true);
            return self::query($body, false);
        }
		return $rep;
	}
	static function search($ref,$type="",$marque="",$page = 1, $codebarre = 10,$country= "TN"){
        if($type!="")$type='"genericArticleIds": '.$type.',';
        if($marque!="")$marque='"dataSupplierIds": '.$marque.',';
		return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "perPage": 1000 , "provider": 0, "searchQuery": "'.$ref.'", "searchType": '.$codebarre.', "searchMatchType": "exact", '.$marque.' '.$type.' "lang": "fr", "includeMisc": true, "includeGenericArticles": true, "includeArticleText": true, "includeGTINs": true, "includeTradeNumbers": true, "includeOEMNumbers": true, "includeReplacesArticles": true, "includeReplacedByArticles": true, "includeArticleCriteria": true, "includeLinkages": true, "includeImages": true, "includeDataSupplierFacets": true, "includeGenericArticleFacets": true } }');
	}
	static function search2($group,$carid,$type,$country= "TN"){
		if($type=="O"&&$carid>1000000)$carid=$carid-1000000;
		return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "assemblyGroupNodeIds": '.$group.', "linkageTargetId": '.$carid.', "linkageTargetType": "'.$type.'", "perPage": 1000 , "provider": 0, "lang": "fr", "includeMisc": true, "includeGenericArticles": true, "includeArticleText": true, "includeGTINs": true, "includeTradeNumbers": true, "includeOEMNumbers": true, "includeReplacesArticles": true, "includeReplacedByArticles": true, "includeArticleCriteria": true, "includeLinkages": true, "includeImages": true, "includeDataSupplierFacets": true, "includeGenericArticleFacets": true } }');
	}
	static function search3($list,$carid,$type,$country= "TN"){
		$gens=implode(',',$list);
		if($gens){
			if($type=="O"&&$carid>1000000)$carid=$carid-1000000;
			return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "genericArticleIds": ['.$gens.'], "linkageTargetId": '.$carid.', "linkageTargetType": "'.$type.'", "perPage": 1000 , "provider": 0, "lang": "fr", "includeMisc": true, "includeGenericArticles": true, "includeArticleText": true, "includeGTINs": true, "includeTradeNumbers": true, "includeOEMNumbers": true, "includeReplacesArticles": true, "includeReplacedByArticles": true, "includeArticleCriteria": true, "includeLinkages": true, "includeImages": true, "includeDataSupplierFacets": true, "includeGenericArticleFacets": true } }');
		}
	}
	static function searchq($ref,$marque,$type,$country= "TN"){
		return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "perPage": 1000 , "provider": 0, "searchQuery": "'.$ref.'", "searchType": '.$type.', "dataSupplierIds": '.$marque.', "lang": "fr", "searchMatchType": "exact", "includeGenericArticles": true } }');
	}
	static function searchy($ref,$country= "TN"){
		return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "perPage": 1000 , "provider": 0, "searchQuery": "'.$ref.'", "searchType": 6, "lang": "fr", "includeGenericArticles": true } }');
	}
	static function searchId($id,$country= "TN"){
		return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "perPage": 1000 , "provider": 0, "legacyArticleIds": '.$id.', "lang": "fr", "includeMisc": true, "includeGenericArticles": true, "includeArticleText": true, "includeGTINs": true, "includeTradeNumbers": true, "includeOEMNumbers": true, "includeReplacesArticles": true, "includeReplacedByArticles": true, "includeArticleCriteria": true, "includeLinkages": true, "includeImages": true, "includeDataSupplierFacets": true, "includeGenericArticleFacets": true } }');
	}
	static function searchL($id,$carId,$type,$country= "TN"){
		if($type=="O"&&$carId>1000000)$carId=$carId-1000000;
		return self::query('{ "getArticles": { "articleCountry": "'.$country.'", "provider": 0, "legacyArticleIds": '.$id.', "linkageTargetId": '.$carId.', "linkageTargetType": "'.$type.'", "linkageTargetCountry": "'.$country.'", "lang": "fr", "includeLinkages": true } }');
	}
	static function searchVeh($manu,$mod,$country= "TN"){
		return self::query('{"getVehicleIdsByCriteria": {"carType": "AZERTYIOPQSDFGHJKLMWXCVBN","countriesCarSelection": "'.$country.'","lang": "fr","manuId": '.$manu.',"modId": '.$mod.',"provider": 0}}');
	}
	static function searchTree($id,$type,$country= "TN"){
		return self::query('{ "getChildNodesAllLinkingTarget2": { "articleCountry": "'.$country.'", "childNodes": true, "lang": "fr", "linked": true, "linkingTargetId": '.$id.', "linkingTargetType": "'.$type.'", "provider": 0 } }');
	}
	static function searchMod($manu,$aa="AZERTYIOPQSDFGHJKLMWXCVBN",$country= "TN"){
		do {
			$ww=self::query('{"getModelSeries2": { "country": "'.$country.'", "lang": "fr", "linkingTargetType": "'.$aa.'", "manuId": '.$manu.', "provider": 0 }}');
			if($ww["status"]==400){
				$aa=str_replace(substr($ww["statusText"],-2,1),"",$aa);
			}
		}while($ww["status"]==400);
		return $ww;
	}
	static function searchManu($country= "TN"){
		return self::query('{ "getManufacturers2": { "country": "'.$country.'", "lang": "fr", "linkingTargetType": "AZERTYIOPQSDFGHJKLMWXCVBN", "provider": 0 } }');
	}
	static function codebarre($codebarre){
		return self::search($codebarre,"","",1,6);
	}
	static function getArticleDetails($uid){
		$list = explode("|", $uid);
		if(count($list)!==3) return null;
		$dataSupplierId = $list[0];
		$articleNumber = $list[1];
		$mfrId = $list[2];
		$artciles = self::search($articleNumber,"",$dataSupplierId);
		foreach ($artciles["articles"] as $key => $value) {
			if ($value["dataSupplierId"]."" ==  "$dataSupplierId") {
				return $value;
			}
		}
		return null;
	}
	static function getMarqueCars($articleId,$country= "TN"){
		$rep = self::query('{ "getArticleLinkedAllLinkingTargetManufacturer2": { "articleCountry": "'.$country.'", "articleId": '.$articleId.', "country": "'.$country.'", "linkingTargetType": "PO", "provider": 0 } }');
		return $rep["data"]["array"];
	}
	static function getCars($articleId,$manuId,$country= "TN"){
		$rep = self::query('{ "getArticleLinkedAllLinkingTarget4": { "articleCountry": "'.$country.'", "articleId": '.$articleId.', "country": "'.$country.'", "lang": "fr", "linkingTargetManuId": '.$manuId.', "linkingTargetType": "PO", "provider": 0 } }');
		$list = [];
		foreach ($rep["data"]["array"] as $arr) {
			foreach ($arr["articleLinkages"]["array"] as $ar) {
				$list[$ar["articleLinkId"]] = [
					"articleLinkId" => $ar["articleLinkId"],
					"linkingTargetId" => $ar["linkingTargetId"],
				];
			}
		}
		$list = array_values($list);
		$listy = array_chunk($list,25);
		$lis = [];
		foreach($listy as $list){
			$rep = self::query('{ "getArticleLinkedAllLinkingTargetsByIds3": { "articleCountry": "'.$country.'", "articleId": '.$articleId.', "immediateAttributs": true, "lang": "fr", "linkedArticlePairs": { "array": '.json_encode($list).' }, "linkingTargetType": "PO", "provider": 0 } }');
			foreach ($rep["data"]["array"] as $a1) {
				foreach ($a1["linkedVehicles"]["array"] as $c) {
					$lis[$c["carId"]] = $c;
				}
			}
		}
		$lis = array_values($lis);
		return $lis;
	}
	static function vin($vin,$country="TN"){
		$rep = self::query('{ "getVehiclesByVIN": {"lang": "fr","country": "'.$country.'","maxVehiclesToReturn":-1, "vin": "'.$vin.'", "provider": 0 } }');
		return $rep;
	}
	static function countries($lang="fr"){
		return self::query('{ "getCountries": {"lang": "'.$lang.'", "provider": 0 } }');
	}
	static function getCarx($carId,$country="TN"){
		$rep = self::query('{ "getVehicleByIds4": { "articleCountry": "'.$country.'", "carIds": { "array": [ '.$carId.' ] }, "countriesCarSelection": "'.$country.'", "country": "'.$country.'", "lang": "fr", "motorCodes": true, "provider": 0 } }');
		for($k=0;$k<count($rep["data"]["array"]);$k++){
			$yf=$rep["data"]["array"][$k]["motorCodes"]["array"];
			$oo=array();
			for($i=0;$i<count($yf);$i++){
				array_push($oo,$yf[$i]["motorCode"]);
			}
			$rep["data"]["array"][$k]["motorCodes"]["array"]=implode(" | ",$oo);
		}
		return $rep;
	}
}