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

$t1_name	= trim($_POST['t1_name']);
$id_from	= (int) trim($_POST['id_from']);
$id_to		= (int) trim($_POST['id_to']);

$id 		= "";
$vin 		= "";
$agetype 	= "";
$doa 		= "";
$fxmonth 	= "";
$fxyear 	= "";
$vinpfx 	= "";

$yearDiff 	= 0;
$monthAI 	= 0;
$ageinmonths= 0;
$aoa 		= "";

$make 		= "";
$model 		= "";
$fueltype 	= "";
$capacity 	= "";
$year 		= "";
$hscode 	= "";
$msrp 		= "";
$depperc 	= "";
$fob 		= "";
$cf_n 		= "";
$payable 	= "";

echo "<br />'DUTY CALCULATION' STARTED<br />";
//prepare and bind
$updstmt = $DB->con->prepare("update `{$t1_name}` set
	atf_make = ?,
	atf_model = ?,
	atf_fueltype = ?,
	atf_capacity = ?,
	atf_year = ?,
	atf_hscode = ?,
	atf_msrp = ?,
	atf_depperc = ?,
	atf_fob = ?,
	atf_cif = ?,
	atf_dutypayable = ?,
	audstat = 'pass' where vin = ?
");
$updstmt->bind_param("ssssssssssss", $make, $model, $fueltype, $capacity, $year, $hscode, $msrp, $depperc, $fob, $cf_n, $payable, $vin);

//proceed
$res = $DB->execute("select * from `{$t1_name}` where id >= {$id_from} and id <= {$id_to} order by id");
if(!is_null($res)){
	$res = $res[0];
	while($row = $DB->nextRow($res)){
		$id 		= $row['id'];
		$vin 		= $row['vin'];
		$agetype 	= $row['agetype'];
		$doa 		= 'December-1-2018';
		$fxmonth 	= $row['fxmonth'];
		$fxyear 	= $row['fxyear'];

		//find in prefixes
		$ret = decode($row);
		if($ret>-1){
			$updstmt->execute();//update row
			echo "<br />D@{$id}";
		}else{
			echo "<br />E({$id}){$ret}";
		}
	}
	$updstmt->close();
	$DB->con->close();
	echo "<br />ENDED<br />";
}

function decode($W){
	global $DB, $id, $vin, $agetype, $doa, $fxmonth, $fxyear, $ageinmonths, $vinpfx, $make, $model, $fueltype, $capacity, $year, $hscode, $msrp, $depperc, $fob, $cf_n, $payable;

	$ret = -100;

	//calculate duty
	$S = array(); $rs = array(); getAgeOnArrival( $doa, $year );

	//HEADING
	/*$S['myear'] 	= $this->input->post('myear', true);
	$S['make'] 		= trim( $this->input->post('make', true) );
	$S['model'] 	= trim( $this->input->post('model', true) );
	$S['bodystyle'] = trim( $this->input->post('bodystyle', true) );
	$S['trim'] 		= trim( $this->input->post('trim', true) );

	$S['title'] = $S['myear'].' '.$S['make'].' '.$S['model'].' '.$S['bodystyle'].' '.$S['trim'];
	$rs['title'] = $S['title'];

	//PRE-BODY
	$S['photo'] = $this->input->post('photo', true);
	$rs['photo'] = $S['photo'];

	$S['coorigin'] = "USA";
	$rs['coorigin'] = $S['coorigin'];

	$S['refid'] = strtoupper("US".mt_rand(100,999).substr(uniqid(),9));
	$rs['refid'] = $S['refid'];

	$S['transactdate'] = date('M d, Y H:i:s');
	$rs['transactdate'] = $S['transactdate'];*/

	//VEHICLE SPECIFICATION
	$S['vin'] 	= $W['vin'];
	$rs['vin'] = $S['vin'];

	$S['seats'] 	= $W['seats'];
	$rs['seats'] = $S['seats'];

	$S['doors'] 	= $W['doors'];
	$rs['doors'] = $S['doors'];

	$S['fueltype'] 	= strtolower( $W['fueltype'] );
	$rs['fueltype'] = ucfirst($S['fueltype']);

	$S['capacity'] 	= $W['capacity'];
	$rs['capacity'] = $S['capacity'].' ccm",';

	/*$S['engine'] 	= $this->input->post('engine', true);
	$rs['engine'] = $S['engine'];*/

	/*$S['coomanuf'] 	= $this->input->post('coomanuf', true);
	$rs['coomanuf'] = $S['coomanuf'];

	$S['measurement'] 	= $this->input->post('measurement', true);
	$rs['measurement'] = $S['measurement'];*/

	$S['weight'] 	= $W['weight'];
	$rs['weight'] = $S['weight'];

	/*$S['production'] 	= $this->input->post('production', true);
	$rs['production'] = $S['production'];*/

	/*$S['doa'] 	= $this->input->post('doa', true);
	$rs['doa'] = $S['doa'];*/

	$S['aoa'] 	= $aoa;
	$rs['aoa'] = $S['aoa'];

	$S['hscode'] = "N/A";

	$heading = $W['heading'];
	//get hs applicabbles
	$cond = '';
	$res = $this->db->query("select * from hs_applicables where heading='{$heading}'");
	if($res->num_rows()>0){
		$row = $res->result_array()[0];

		if($row['fueltype'] == '*')
		$cond .= " and fueltype = '{$this->fueltype}'";

		if($row['capacity'] == '*')
		$cond .= " and (capacityfrom <= {$this->capacity} and capacityto >= {$this->capacity})";

		if($row['seats'] == '*')
		$cond .= " and (seatfrom <= {$this->seats} and seatto >= {$this->seats})";

		if($row['weight'] == '*')
		$cond .= " and (tonnesfrom <= {$this->weight} and tonnesto >= {$this->weight})";
	}

	$agetype = $this->input->post('agetype', true);
	switch(strtolower($S['fueltype'])){
		case "electric": case "hybrid": case "gas":
		$qry = "select * from hs_coding_gam where fueltype='{$S['fueltype']}'";
		break;

		default:
		$qry = "select * from hs_coding_gam where age='{$agetype}' and heading='{$heading}'{$cond}";
	}
	$res = $this->db->query($qry);
	if($res->num_rows()>0){
		$row = $res->result_array()[0];
		$S['dtyperc'] = $row['importduty'];
		$rs['dtyperc'] = $this->formatPerc( $S['dtyperc'] );

		$S['vatperc'] = $row['vat'];
		$rs['vatperc'] = $this->formatPerc( $S['vatperc'] );

		$S['excperc'] = $row['excise'];
		$rs['excperc'] = $this->formatPerc( $S['excperc'] );

		$S['auperc'] = $row['au'];
		$rs['auperc'] = $this->formatPerc( $S['auperc'] );

		$S['prcperc'] = $row['processing'];
		$rs['prcperc'] = $this->formatPerc( $S['prcperc'] );

		$S['ecwperc'] = $row['ecowas'];
		$rs['ecwperc'] = $this->formatPerc( $S['ecwperc'] );

		$S['envperc'] = $row['environmental'];
		$rs['envperc'] = $this->formatPerc( $S['envperc'] );

		$S['hscode'] = $row['hscode'];
		$rs['hscode'] = $S['hscode'];
	}else{
		return "-1";
	}

	//COST AND FREIGHT
	$S['msrp'] = $W["msrp"];
	$rs['msrp'] = $this->format( $S['msrp'] );

	//depreciation
	if(trim(strtolower($this->input->post('agetype', true))) == "new"){
		$S['depperc'] = 0;
	}else{
		$res=$this->db->query("select * from depreciation_gam where periodfrom<={$this->ageinmonths} and periodto>={$this->ageinmonths}");
		if($res->num_rows()>0){
			$row = $res->result_array()[0];
			$S['depperc'] = $row['depreciationp'];
		}else{
			return "-2";
		}
	}
	$rs['depperc'] = $this->formatPerc( $S['depperc'] );

	$S['residue'] = ( 1 - ( ( (double) $S['depperc'] ) / 100 ) ) * $S['msrp'];
	$rs['residue'] = $this->format( $S['residue'] );

	$S['freight'] = (double) $this->input->post('freight', true);
	$rs['freight'] = $this->format( $S['freight'] );

	$S['cf_f'] = $S['residue'] + $S['freight'];
	$rs['cf_f'] = $this->format( $S['cf_f'] );

	$S['currency'] = "USD";
	$rs['currency'] = $S['currency'];

	//get fx rates
	$curyear = date('Y');
	$curmonth = date('M');

	$Q = $this->db->query("select rate from fx_rates_gam where year <= '{$curyear}' and month = '{$curmonth}' order by year DESC limit 1");
	if($Q->num_rows()>0){ $R = $Q->result_array()[0]; $S['fxrate'] = $R['rate']; }

	$rs['fxrate'] = $this->formatRate( $S['fxrate'] );

	$S['cf_l'] = $S['cf_f'] * $S['fxrate'];
	$rs['cf_l'] = $this->format( $S['cf_l'] );

	//DUTY, TAXES AND LEVIES
	$S['dtybase'] = $S['cf_l'];
	$rs['dtybase'] = $this->format( $S['dtybase'] );

	$S['prcbase'] = $S['cf_l'];
	$rs['prcbase'] = $this->format( $S['prcbase'] );

	$S['ecwbase'] = $S['cf_l'];
	$rs['ecwbase'] = $this->format( $S['ecwbase'] );

	//amounts
	$S['dtyamt'] = ( $S['dtyperc'] / 100 ) * $S['dtybase'];
	$rs['dtyamt'] = $this->format( $S['dtyamt'] );

	$S['prcamt'] = ( $S['prcperc'] / 100 ) * $S['prcbase'];
	$rs['prcamt'] = $this->format( $S['prcamt'] );

	$S['ecwamt'] = ( $S['ecwperc'] / 100 ) * $S['ecwbase'];
	$rs['ecwamt'] = $this->format( $S['ecwamt'] );

	//continues
	$S['excbase'] = $S['cf_l'] + $S['dtybase'] + $S['prcbase'] + $S['ecwbase'];
	$rs['excbase'] = $this->format( $S['excbase'] );

	//amount
	$S['excamt'] = ( $S['excperc'] / 100 ) * $S['excbase'];
	$rs['excamt'] = $this->format( $S['excamt'] );

	//continues
	$S['vatbase'] = $S['cf_l'] + $S['dtybase'] + $S['excbase'];
	$rs['vatbase'] = $this->format( $S['vatbase'] );

	//amount
	$S['vatamt'] = ( $S['vatperc'] / 100 ) * $S['vatbase'];
	$rs['vatamt'] = $this->format( $S['vatamt'] );

	//continues
	$S['aubase'] = $S['cf_l'];
	$rs['aubase'] = $this->format( $S['aubase'] );

	//amount
	$S['auamt'] = ( $S['auperc'] / 100 ) * $S['aubase'];
	$rs['auamt'] = $this->format( $S['auamt'] );

	//continues
	$S['envbase'] = "";
	$rs['envbase'] = "";

	//amount
	$S['envamt'] = $S['envperc'];
	$rs['envamt'] = $this->format( $S['envamt'] );		

	//TOTAL
	$S['payable'] =  $S['dtyamt'] + $S['vatamt'] + $S['excamt'] + $S['auamt'] + $S['prcamt'] + $S['ecwamt'] + $S['envamt'];

	$rs['payable'] = $this->format( $S['payable'] );

	$S['machineip']	= $_SERVER['REMOTE_ADDR'];

	$ret = 0;
	
	return $ret;
}

function format($d){
	return number_format((double) $d,0,".",",");
}
function formatPerc($d){
	return number_format(((double) $d),0,".",",")."%";
}
function formatRate($d){
	return number_format((double) $d,4,".",",");
}

function getAgeOnArrival($doa, $year){
	global $yearDiff, $monthAI, $ageinmonths, $aoa;
	
	$tmp			= explode( '-', $doa );
	$arrivalyear	= (int) trim( $tmp[2] );
	$modelyear		= (int) $year;
	$curyear		= (int) date("Y");
	
	$yearDiff = $arrivalyear - $modelyear;
	if( $yearDiff >= 10 ) $yearDiff = $yearDiff - 1;
	
	$monthAI = monthAI( trim( $tmp[0] ) ); $ageinmonths = 0;
	
	if( $modelyear <= $curyear ){
		if( $arrivalyear >= $modelyear ){ calculateAgeNormally(); }
		else{
			$aoa="Incorrect selection - The estimated year of arrival cannot be earlier than the year of manufacture";
		}
	}else{//make year zero and add the month value for calculation
		if( $arrivalyear >= $modelyear ){ calculate_age_normally(); }
		else if( $arrivalyear == $curyear ){//3 months /*$this->aoa="3 mth"; $this->ageinmonths=3;*/
			$aoa = "{$monthAI} mth";
			$ageinmonths = $monthAI;
		}else if( $arrivalyear < $curyear ){
			$aoa = "Incorrect selection - The estimated year of arrival cannot be earlier than the year of manufacture";
		}else{
			$aoa = "Unknown Case - An error occurred while trying to calculate the age";
		}
	}
}
function calculateAgeNormally(){
	global $yearDiff, $monthAI, $ageinmonths, $aoa;

	if( $monthAI == 12 ){
		$yearDiff = $yearDiff + 1; $monthAI = 0;
	}
	if( $monthAI > 0 ){
		$aoa = "{$yearDiff} yr {$monthAI} mth";
	} else{
		$aoa = "{$yearDiff} yr";
	}
	$ageinmonths = ( $yearDiff * 12 ) + $monthAI;
}
function monthAI( $str ){
	$n = -1;
	if($str == "January") 		$n = 1;
	else if($str == "February") $n = 2;
	else if($str == "March") 	$n = 3;
	else if($str == "April") 	$n = 4;
	else if($str == "May") 		$n = 5;
	else if($str == "June") 	$n = 6;
	else if($str == "July") 	$n = 7;
	else if($str == "August") 	$n = 8;
	else if($str == "September") $n = 9;
	else if($str == "October") 	$n = 10;
	else if($str == "November") $n = 11;
	else if($str == "December") $n = 12;
	else $n = -1;
	return $n;
}
?>