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

echo "<br />NHTSA Population Started...";
$res = $DB->execute("select 
	id,
	vinprefix,
	year
from nhtsa_pref 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];
		//extract details
		
		//ENGINE
		$engine = trim($sav['EngineModel']);

		//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 .= ", nhtsa_capacity = '{$capacity}'";
		if($fueltype!='') $clause .= ", nhtsa_fueltype = '{$fueltype}'";
		if($seats>0) $clause .= ", nhtsa_seats = '{$seats}'";

		/*$clause .= ", bodyclass = '{$sav['BodyClass']}'";
		$clause .= ", displacementcc = '{$sav['DisplacementCC']}'";
		$clause .= ", doors = '{$sav['Doors']}'";
		$clause .= ", drivetype = '{$sav['DriveType']}'";
		$clause .= ", trim = '{$sav['Trim']}'";
		$clause .= ", vehicletype = '{$sav['VehicleType']}'";*/

		$vfam = substr($vin, 0,8);

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

	}else{
		$DB->simpleQuery("update us_vinprefixes set status='fail' where vfam = '{$vfam}'");
	}
	return $sav;
}

?>