<?php require_once("../../classes/DBConnection.php"); $DB = new DBConnection();

echo "<br />Loading Attributes...";
$res = $DB->execute("select id, vinprefix, year from nhtsa order by id ASC");

if(!is_null($res)){
	$res = $res[0];
	while($W = $DB->nextRow($res)){
		$id = $W['id'];
		$vin = $W['vinprefix'];
		$year = $W['year'];

		//NOW GO
		saveToRow($id, $vin, $year);
	}
	echo "<br />ENDED<hr />";
}else{ "<span style='color:#F00'>Error in Commencement</span><br />"; }


function saveToRow($id, $vin,$year){
	global $DB;
	$url = "https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/{$vin}?format=json&modelyear={$year}";
	$rs =trim(file_get_contents($url));

	$lookfor = array();
	$replace = array();

	$sav = json_decode(str_replace($lookfor,$replace,$rs),true);
	$rs = str_replace($lookfor,$replace,$rs);

	if(true){
		$sav = $sav['Results'][0];
		
		//FUEL TYPE
		$fueltype = strtolower(trim($sav['FuelTypeSecondary']));
		$t = strtolower($sav['FuelTypePrimary']);
		if(strpos($t,'diesel')>-1){
			$fueltype = "Diesel";
		}
		else if(strpos($t,'gasoline')>-1 || strpos($t,'leaded')>-1 || strpos($t,'petrol')>-1){
			$fueltype = "Petrol";
		}

		//CAPACITY
		$capacity = (double) $sav['DisplacementL'];
		
		//SEATS
		$seats = (int) $sav['Seats'];

		//save
		$clause = "engine = '{$engine}'";
		//if($capacity>0) $clause .= ", capacity = '{$capacity}'";
		//if($fueltype!='') $clause .= ", fueltype = '{$fueltype}'";
		if($seats>0) $clause .= ", seats = '{$seats}'";

		//$clause .= ", displacementcc = '{$sav['DisplacementCC']}'";

		if($DB->simpleQuery("update nhtsa set {$clause} where vinprefix = '{$vin}'")){
			echo "<br />Done at #{$id} {$vin}";
		}else{
			echo "<br /><span style='color:#F00'>Error at #{$id} {$vin}</span>";
		}

	}
	return $sav;
}
?>