<?php
class DecodeThis {
	private $db, $vin, $baseurl;
	function __construct(){}
	function getPettyDetails($vin){
		$arr = array();
		if(sizeof($arr)==0){
			$this->baseurl = 'http://www.decodethis.com/webservices/api.ashx?vin='.$vin.'&apikey=737faa81-d5ec-4abf-aa55-b704199137be&format=JSONP';
			$this->vin = $vin;
			$dtres = file_get_contents($this->baseurl);
			$dtres = substr($dtres,1,strrpos($dtres,")")-1);
			
			$indxobrack = strpos($dtres,"[");
			$dtArr = json_decode($dtres,true);
			
			$isArr=false;
			if(json_last_error()==0){
				if(trim($dtArr["decode"]["status"])=="SUCCESS"){
					if(!$indxobrack===false) { if($indxobrack<70) $isArr=true; }
					if($isArr){
						$arr = $this->fetchPettyMultiDetails($dtArr["decode"]["vehicle"][0]["id"]);
					}else{
						$arr = $this->fetchPettyDetails($dtArr["decode"]["vehicle"]["id"]);
					}
				}else{ echo '{"opsstat":1,"opsstatinfo":"Failed to process VIN : '.$vin.'"}'; }
			}else{ echo '{"opsstat":1,"opsstatinfo":"JSON decoding failed !"}'; }
		}
		return $arr;
	}
	function getDet($vin){
		$row = array();
		$res=mysql_query("select decodethis.*, vehiclecatman.code from decodethis LEFT JOIN vehiclecatman ON (decodethis.make=vehiclecatman.make and decodethis.model=vehiclecatman.model) where decodethis.vin='{$vin}' limit 1");
		if($res && mysql_num_rows($res)>0){
			$row = mysql_fetch_array($res);
		}
		return $row;
	}
	function getPetDet($vin){
		$arr = array();
		$res=mysql_query("select ovlength,ovwidth,ovheight, seats,capacity from decodethispetty where vin='{$vin}' limit 1");
		if($res && mysql_num_rows($res)>0){
			$row = mysql_fetch_array($res);
			$ovL=(double) $row["ovlength"];
			$ovW=(double) $row["ovwidth"];
			$ovH=(double) $row["ovheight"];
			
			$arr["measurement"] = $this->format(($ovL*$ovW*$ovH)/3)." cubic in";
			$arr["seats"] = $row["seats"];
			$arr["capacity"] = $row["capacity"];
		}
		return $arr;
	}
	function getDetails($vin){
		$arr = $this->getDet($vin); $sss = false;
		if(sizeof($arr)==0){
			//then get the data first
			$this->baseurl = 'http://www.decodethis.com/webservices/api.ashx?vin='.$vin.'&apikey=737faa81-d5ec-4abf-aa55-b704199137be&format=JSONP';
			$this->vin = $vin;
			$dtres = file_get_contents($this->baseurl);
			$dtres = substr($dtres,1,strrpos($dtres,")")-1);
			
			$indxobrack = strpos($dtres,"[");
			$dtArr = json_decode($dtres,true);
			
			$isArr=false;
			if(json_last_error()==0){
				if(trim($dtArr["decode"]["status"])=="SUCCESS"){
					if(!$indxobrack===false) { if($indxobrack<70) $isArr=true; }
					if($isArr){
						$sss = $this->fetchMultiDetails($dtArr["decode"]["vehicle"][0]["id"]);
					}else{
						$sss = $this->fetchDetails($dtArr["decode"]["vehicle"]["id"]);
					}
				}else{ echo '{"opsstat":1,"opsstatinfo":"Failed to process VIN : '.$vin.'"}'; }
			}else{ echo '{"opsstat":1,"opsstatinfo":"JSON decoding failed !"}'; }
			
			//now try again
			if($sss){ $arr = $this->getDet($vin); }
		}
		return $arr;
	}
	
	function fetchDetails($id){
		$ss=false;
		$dtrs = file_get_contents( $this->baseurl.'&detail='.$id);
		
		$dtrs = substr($dtrs,1,strrpos($dtrs,")")-1);
		$dtrsArr = json_decode($dtrs,true);
		
		if(json_last_error()==0){
			$ss = $this->saveDetails($dtrsArr["decode"]["vehicle"], $dtrsArr["decode"]["vehicle"]["id"]);
		}
		return $ss;
	}
	function fetchPettyDetails($id){
		$ss=false;
		$dtrs = file_get_contents($this->baseurl.'&detail='.$id);
		
		$dtrs = substr($dtrs,1,strrpos($dtrs,")")-1);
		$dtrsArr = json_decode($dtrs,true);
		
		if(json_last_error()==0){
			$ss = $this->savePettyDetails($dtrsArr["decode"]["vehicle"], $dtrsArr["decode"]["vehicle"]["id"]);
		}
		return $ss;
	}
	
	function fetchMultiDetails($id){
		$ss=false;
		$dtrs = file_get_contents($this->baseurl.'&detail='.$id);
		
		$dtrs = substr($dtrs,1,strrpos($dtrs,")")-1);
		$dtrsArr = json_decode($dtrs,true);
		
		if(json_last_error()==0){
			$vehs = $dtrsArr["decode"]["vehicle"];
			for($i=0; $i<sizeof($vehs); $i++){
				$ss = $this->saveDetails($vehs[$i], $vehs[$i]["id"]);
			}
		}else{
			echo '{"opsstat":1,"opsstatinfo":"Could not proceed to save. Bad JSON format !"}';
			return;
		}
		return $ss;
	}
	function fetchPettyMultiDetails($id){
		$ss=false;
		$dtrs = file_get_contents($this->baseurl.'&detail='.$id);
		
		$dtrs = substr($dtrs,1,strrpos($dtrs,")")-1);
		$dtrsArr = json_decode($dtrs,true);
		
		if(json_last_error()==0){
			$vehs = $dtrsArr["decode"]["vehicle"];
			for($i=0; $i<sizeof($vehs); $i++){
				$ss = $this->savePettyDetails($vehs[$i], $vehs[$i]["id"]);
			}
		}else{
			echo '{"opsstat":1,"opsstatinfo":"Could not proceed to save. Bad JSON format !"}';
			return;
		}
		return $ss;
	}
	
	function saveDetails($veh, $did){
		$NODATA = "No data"; $ss = false;
		$equip = $veh["Equip"];
		
		$make = $veh["make"];
		$model = $veh["model"];
		$body = $veh["body"];
		$trim = $veh["trim"];
		$year = $veh["year"];
		
		for($i=0; $i<sizeof($equip); $i++){
			$equipA = $equip[$i];
			switch($equipA["name"]){
				case "Manufactured in":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $coorigin = ""; }
				else{
					$coorigin = $val;
				}
				break;
				
				case "Body Style":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $bodystyle = ""; }
				else{
					$bodystyle = $val;
				}
				break;
				
				case "Engine Type":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $capacity = ""; $enginetype = ""; }
				else{
					$pOL = strpos($equipA["value"],"L");
					$enginetype = trim(substr($equipA["value"],$pOL+1));
					$capacity = trim(substr($equipA["value"],0,$pOL));
				}
				break;
				
				case "Transmission":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $transmission = ""; }
				else{
					$transmission = $val;
				}
				break;
				
				case "Driveline":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $driveline = ""; }
				else{
					$driveline = $val;
				}
				break;
				
				case "Tank":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $tank = ""; }
				else{
					$tank = $val." ".$equipA["unit"];
				}
				break;
				
				case "City MPG":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $citympg = ""; }
				else{
					$citympg = $val;
				}
				break;
				
				case "Highway MPG":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $highwaympg = ""; }
				else{
					$highwaympg = $val;
				}
				break;
				
				case "Tires":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $tires = ""; }
				else{
					$tires = $val;
				}
				break;
				
				case "Curb Weight":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $curbweight = "0"; }
				else{
					$curbweight = $val." ".$equip["unit"];
				}
				break;
				
				case "Overall Length":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $ovlength = "0"; }
				else{
					$ovlength = $val;
				}
				break;
				
				case "Overall Width":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $ovwidth = "0"; }
				else{
					$ovwidth = $val;
				}
				break;
				
				case "Overall Height":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $ovheight = "0"; }
				else{
					$ovheight = $val;
				}
				break;
				
				case "Wheelbase":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $wheelbase = "0"; }
				else{
					$wheelbase = $val;
				}
				break;
				
				case "Ground Clearance":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $gclearance = "0"; }
				else{
					$gclearance = $val;
				}
				break;
				
				case "Standard Seating":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $seats = ""; }
				else{
					$str = trim($equipA["value"]);
					if(ctype_digit($str)) $seats = $str;
				}
				break;
				
				case "Optional Seating":
				$val = trim($equipA["value"]);
				if($val!=$NODATA){
					if(ctype_digit($val)){
						if($seats==""){ $seats = $val; } else{ if($seats!=$val) $seats = $seats."|".$val; }
					}
				}
				break;
				
				case "MSRP":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $msrp = "0"; }
				else{
					$msrp = trim(str_replace(",","",substr($val,1)));
				}
				break;
				
				case "Dealer Invoice":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $dinvoice = "0"; }
				else{
					$dinvoice = trim(str_replace(",","",substr($val,1)));
				}
				break;
				
				case "Cargo Net":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $cargonet = "0"; }
				else{
					$cargonet = $val;
				}
				break;
			}
		}
		$res=mysql_query("insert into decodethis (did, vin, make, model, trim, body, bodystyle, myear, seats, fueltype, capacity, enginetype, transmission, measurement, driveline, tank, citympg, highwaympg, tires, curbweight, ovlength, ovwidth, ovheight, wheelbase, gclearance, msrp, dinvoice, cargonet, coorigin, photo) values ('{$did}', '{$this->vin}', '{$make}', '{$model}', '{$trim}', '{$body}', '{$bodystyle}', '{$year}', '{$seats}', '{$fueltype}', '{$capacity}', '{$enginetype}', '{$transmission}', '{$measurement}', '{$driveline}', '{$tank}', '{$citympg}', '{$highwaympg}', '{$tires}', '{$curbweight}', '{$ovlength}', '{$ovwidth}', '{$ovheight}', '{$wheelbase}', '{$gclearance}', '{$msrp}', '{$dinvoice}', '{$cargonet}', '{$coorigin}', '{$photo}')");
		
		if($res){ $ss=true; }
		return $ss;
	}
	
	function savePettyDetails($veh, $did){
		$NODATA = "No data"; $ss = false;
		$equip = $veh["Equip"];
		
		$make = $veh["make"];
		$model = $veh["model"];
		$trim = $veh["trim"];
		$year = $veh["year"];
		
		for($i=0; $i<sizeof($equip); $i++){
			$equipA = $equip[$i];
			switch($equipA["name"]){
				case "Engine Type":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $capacity = ""; $enginetype = ""; }
				else{
					$pOL = strpos($equipA["value"],"L");
					$enginetype = trim(substr($equipA["value"],$pOL+1));
					$capacity = trim(substr($equipA["value"],0,$pOL));
				}
				break;
				
				case "Overall Length":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $ovlength = "0"; }
				else{
					$ovlength = $val;
				}
				break;
				
				case "Overall Width":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $ovwidth = "0"; }
				else{
					$ovwidth = $val;
				}
				break;
				
				case "Overall Height":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $ovheight = "0"; }
				else{
					$ovheight = $val;
				}
				break;
				
				case "Standard Seating":
				$val = trim($equipA["value"]);
				if($val==$NODATA){ $seats = ""; }
				else{
					$str = trim($equipA["value"]);
					if(ctype_digit($str)) $seats = $str;
				}
				break;
				
				case "Optional Seating":
				$val = trim($equipA["value"]);
				if($val!=$NODATA){
					if(ctype_digit($val)){
						if($seats==""){ $seats = $val; } else{ if($seats!=$val) $seats = $seats."|".$val; }
					}
				}
				break;
			}
		}
		$res=mysql_query("insert into decodethispetty (did, vin, seats, capacity, ovlength, ovwidth, ovheight) values ('{$did}', '{$this->vin}', '{$seats}', '{$capacity}', '{$ovlength}', '{$ovwidth}', '{$ovheight}')");
		
		if($res){ $ss=true; }
		return $ss;
	}
	function format($d){
		return number_format((double) $d,2,".",",");
	}
}
?>