<?php
class VA_PettyReader{
	private $specurl = "http://api.vinaudit.com/pullspecs.php?key=4G0N1TNOTE9KMJ0&format=json&vin=";
	private $histurl = "http://api.vinaudit.com/pullreport.php?user=automasters&pass=hpns1990&key=99BJS5MNYKWV7QS&format=json&vin=";
	private $lookfor = array("VIN","Year","Make","Model","Trim Level","Style","Made In","Engine","Steering Type","Anti-Brake System","Tank Size","Overall Height","Overall Length","Overall Width","Standard Seating","Optional Seating","Highway Mileage","City Mileage");
	
	private $replace = array("vin","year","make","model","trim","style","madein","engine","steering","brake","tank","height","length","width","sseats","oseats","highway","city");
	private $lookfor0 = array("O","I");
	private $replace0 = array("0","1");
	private $vin, $vin4, $sql;
	
	function __construct($sql){ $this->sql = $sql; }
	
	function read($vin){
		$this->vin = mysql_real_escape_string(strip_tags($vin));
		$this->vin = str_replace($this->lookfor0, $this->replace0, $this->vin);
		$this->vin4 = substr($this->vin,10,7);
		
		$info = array();
		$info = $this->sql->getWhere("vin='{$this->vin}'","vinprefix");
		if(sizeof($info<0)){//not found in DB so go API and save
			$rs = $this->getSpecs($this->vin); $raO = json_decode($rs,true); $ra = $raO['attributes'];
			if(isset($ra)){
				$eng = trim($ra['engine']); $pos=strpos($eng,"L");
				$enginecapacity=trim(substr($eng,0,$pos));
				$enginetype=trim(substr($eng,($pos+1)));
				
				//construct hole peg array and save
				$info['vin']				 = $ra['vin'];
				//$info['year']				 = $ra['year'];
				//$info['make']				 = $ra['make'];
				//$info['model']				 = $ra['model'];
				//$info['trim']				 = $ra['trim'];
				$info['va_capacity']		 = $enginecapacity;
				$info['va_enginetype']		 = $enginetype;
				//$info['madein']				 = $ra['madein'];
				//$info['steeringtype']		 = $ra['steering'];
				//$info['brakesystem']		 = $ra['brake'];
				//$info['tanksize']			 = $ra['tank'];
				//$info['overallheight']		 = $ra['height'];
				//$info['overalllength']		 = $ra['length'];
				//$info['overallwidth']		 = $ra['width'];
				$info['va_sseating']		 = $ra['sseats'];
				$info['va_oseating']		 = $ra['oseats'];
				$info['va_highwaympg']		 = $ra['highway'];
				$info['va_citympg']			 = $ra['city'];
				
				$this->sql->update("vinprefixes", $info, "vin='{$info['vin']}'");
			}
		}
		return $info;
	}
	
	function getSpecs(){
		$rs = trim(file_get_contents($this->specurl.$this->vin));
		$rs = str_replace($this->lookfor,$this->replace,$rs);
		return $rs;
	}	
}
?>