<?php

include 'header.php';

echo '<div id="cover_screen">';

$_SESSION['destination0'] = $_POST['destination0'];
$_SESSION['ground_dest'] = $_POST['ground_dest'];
$_SESSION['passengers'] = $_POST['passengers'];
$_SESSION['mode'] = $_POST['mode'];
$_SESSION['Routing'] = $_POST['Routing'];


if ($_POST['FlyMode'] == 'ground')
{
	$_POST['destination0'] = $_POST['ground_dest'];
}
else
{
	$iata = explode(', ', $_POST['destination0']);

	$iata = mysql_query("SELECT iata FROM airports WHERE city = '{$iata[0]}' AND country = '{$iata[1]}' LIMIT 1");
	$iata = mysql_result($iata, 0, 0);

	$_POST['destination0'] = $iata;
}

$count = $_POST["destination"];
$_SESSION['count'] = $count;
$passengers = (int)$_POST["passengers"];
$_SESSION['mode'] = $_POST["mode"];
$_SESSION['flymode'] = $_POST["FlyMode"];
$_SESSION['pass'] = $passengers;

if ($_POST["Routing"] == "return")
{
	$rout = 2; //return
	$_SESSION['rout'] = $rout;
	$_SESSION['flight'] = 'round';
}
else
{
	$rout = 1;  //single
	$_SESSION['rout'] = $rout;
	$_SESSION['flight'] = 'One-way';
}

for ($i = 0; $i <= $count ; $i++)
{
	$destination[$i] = $_POST["destination".$i];
}

if ($passengers == '0')
{
	echo "Passengers entry is not a valid number. Please change the input.<br>";
	return;
}

$multiple = false;

for ($i = 0; $i <= $count; $i++)
{
	if (empty($destination[$i]))
	{
		echo '<div style="padding: 50px"><h2>Please go to the previous page and make sure the form is completed correctly.</h2><a href="index.php">Back</a></div>';
		return; //set a flag here to write the error.
	}
	if ($i == 1)
	{
		if ($_SESSION['flymode'] != 'ground')
		{
			$destination[$i] = $_SESSION['flymode'];
		}
	}

	$query = "SELECT * FROM ".$table." WHERE city=\"". $destination[$i] ."\"". " OR iata=\"". $destination[$i] ."\"";

	$result[$i] = mysqli_query($cxn, $query);
	if ($result[$i] == false)
	{
		echo "<h4>Error: ".mysqli_error($cxn)."</h4>";
		return;
	}

	$nrows[$i] = mysqli_num_rows($result[$i]);
	/*if ($nrows[$i] == 0)
	{
		echo "<h4>Query completed.
		No results for origin City or Destination City, check the inputs please.</h4>";
		return;
	}*/

	if ($nrows[$i] != 1) $multiple = true;
}

// Report starts from this line. /////////////////////////////////////////////////////

for ($j = 0; $j <= $count; $j++)
{
  	$row[$j] = mysqli_fetch_assoc($result[$j]);
}

for ($j = 0; $j < $count; $j++)
{
	if ($_SESSION['flymode'] == 'ground')
	{
	    $orglat = ($row[$j]['latdegree'] + ($row[$j]['latmin'] * 1/60) + ($row[$j]['latsec'] * 1/60 * 1/60));
	    if ($row[$j]['latdirection'] == "N") $orglat = $orglat * -1;

		$orglong = $row[$j]['longdeg'] + ($row[$j]['longmin'] * 1/60) + ($row[$j]['longsec'] * 1/60 * 1/60);
		if ($row[$j]['longdir'] == "E") $orglong = $orglong * -1;

		$deslat = ($row[$j + 1]['latdegree'] + ($row[$j + 1]['latmin'] * 1/60) + ($row[$j + 1]['latsec'] * 1/60 * 1/60));
		if ($row[$j + 1]['latdirection'] == "N") $deslat = $deslat * -1;

		$deslong = $row[$j + 1]['longdeg'] + ($row[$j + 1]['longmin'] * 1/60) + ($row[$j + 1]['longsec'] * 1/60 * 1/60);
		if ($row[$j + 1]['longdir'] == "E") $deslong = $deslong * -1;


		$ground_dist = mysql_query("SELECT Distance FROM ground WHERE City = '$_POST[ground_dest]'");
		$ground_dist = mysql_result($ground_dist, 0, 0);


		$ferry_dist = ground_emission($ground_dist, 'ferry_distance');


		$dist = 0;


		$origin = $_POST['ground_dest'];
		$flight = 'N/A';
	}
	else
	{
	    $orglat = ($row[$j]['latdegree'] + ($row[$j]['latmin'] * 1/60) + ($row[$j]['latsec'] * 1/60 * 1/60));
	    if ($row[$j]['latdirection'] == "N") $orglat = $orglat * -1;

		$orglong = $row[$j]['longdeg'] + ($row[$j]['longmin'] * 1/60) + ($row[$j]['longsec'] * 1/60 * 1/60);
		if ($row[$j]['longdir'] == "E") $orglong = $orglong * -1;

		$deslat = ($row[$j + 1]['latdegree'] + ($row[$j + 1]['latmin'] * 1/60) + ($row[$j + 1]['latsec'] * 1/60 * 1/60));
		if ($row[$j + 1]['latdirection'] == "N") $deslat = $deslat * -1;

		$deslong = $row[$j + 1]['longdeg'] + ($row[$j + 1]['longmin'] * 1/60) + ($row[$j + 1]['longsec'] * 1/60 * 1/60);
		if ($row[$j + 1]['longdir'] == "E") $deslong = $deslong * -1;


		if ($_POST['FlyMode'] == 'yvr') $ground_dist = 122;
		elseif ($_POST['FlyMode'] == 'sea') $ground_dist = 354;


		$dist = distance($orglat, $orglong, $deslat, $deslong, "k");


		//$origin = ucwords(strtolower($row[$j]['name'])).' / '.$row[$j]['iata'].'<br /><div class="origin">'.$row[$j]['city'].', '.$row[$j]['country'].'</div>';
		$origin = ucwords(strtolower($row[$j]['city'])).'<br /><div class="origin">'.ucwords(strtolower($row[$j]['country'])).'</div>';
		//$flight = $row[$j]['iata'].' to '.$row[$j + 1]['iata'];
		$flight = ucwords(strtolower($row[$j]['city'])).' to '.ucwords(strtolower($row[$j + 1]['city']));
	}

	echo '<div id="purchase">Purchase Carbon Offsets</div>';
	echo '<div id="results_outer">';
	echo '<table id="results" cellspacing="0" cellpadding="0">';
	echo '<tr><td><h3>Place of origin</h3></td><td><h3>To</h3></td></tr>';
	echo '<tr><td>'.$origin.'</td><td>Whistler, BC</td></tr>';
	echo '<tr><td colspan="2"><h3>Number of travellers</h3></td></tr>';
	echo '<tr><td colspan="2">'.$passengers.' <span style="font-weight: normal">passenger(s)</span> '.$_SESSION['flight'].' trip</td></tr>';
	echo '<tr><td><h3>Flight</h3></td><td><h3>Ground transport to Whistler</h3></td></tr>';
	echo '<tr><td>'.$flight.'</td><td>'.ucwords($_SESSION['mode']).'</td></tr>';

	if ($_SESSION['mode'] != 'bus') $ground_passengers = 1; // certain transport modes and charging per vehicle or per passenger
	else $ground_passengers = $passengers;

	$total = emission($dist) * $passengers + ground_emission($ground_dist) * $ground_passengers;
	$cton += round($total / 1000, 3);
	$totaldist += round($rout * ($dist + $ground_dist + $ferry_dist));

	echo '<tr><td><h3><span>Emission / Distance / Cost summary</span>Total distance</h3></td><td><h3><span>&nbsp;</span>Total trip emissions</h3></td></tr><tr><td>'.$totaldist.' km<div class="origin">';

	if ($dist) echo 'Air: '.round($rout * $dist).'km<br/>';
	if ($ground_dist) echo 'Ground: '.round($rout * $ground_dist).'km<br/>';
	if ($ferry_dist) echo 'Ferry: '.round($rout * $ferry_dist).'km';

	echo '</div><br/>&nbsp;</td><td>'.round($rout * $total).' kg of CO2e<div class="origin">';

	if ($dist) echo 'Air: '.round(emission($rout * $dist * $passengers)).'kg<br/>';
	if ($ground_dist) echo 'Ground: '.round(ground_emission($rout * $ground_dist * $ground_passengers, 'ground')).'kg<br/>';
	if ($ferry_dist) echo 'Ferry: '.round(ground_emission($rout * $ground_dist * $ground_passengers, 'ferry')).'kg';

	echo '</div><br/>&nbsp;</td></tr>';
}

/*if ($_SESSION['flymode'] != 'ground' || $_SESSION['mode'] == 'bus')*/ $number = $rout * $cton * 20;
//else $number = $rout * 1 * $cton * 20;

echo '<tr><td><h2>Total offset cost to make<br>your trip climate friendly</h2></td><td>';
echo '<span id="total">$'.number_format($number, 2, '.', '').'</span>CDN';
if ($_SESSION['passengers'] > 1) echo '<br/>$'.number_format($number / $_SESSION['passengers'], 2, '.', '').' CDN per person';
echo '</td></tr><tr><td><a href="index.php" title="Recalculate"><img src="recalculate.png"></a></td><td>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
 	<input type="hidden" name="cmd" value="_xclick"/>
	<input type="hidden" name="business" value="offsetters@gmail.com"/>
	<input type="hidden" name="item_name" value="Whistler EcoPath - Carbon Offset"/>
	<input type="hidden" name="currency_code" value="CAD"/>
	<input type="hidden" name="amount" value="'.$number.'"/>
	<input type="image" src="offset_now.png">
</form>
</td></tr></table></div>';


function distance($lat1, $lon1, $lat2, $lon2, $unit)
{
	$theta = $lon1 - $lon2;


	$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
	$dist = acos($dist);
	$dist = rad2deg($dist);
	$miles = $dist * 60 * 1.1515;
	$unit = strtoupper($unit);

	if ($unit == "K")
	{
		return ($miles * 1.609344);
	}
	elseif ($unit == "N")
	{
		return ($miles * 0.8684);
	}
	else
	{
		return $miles;
	}
}

//return emission in kgr
function emission($dist)
{
	$metric = 2;
	//freight allocation
	$freight = 0.10;
	if ($dist <= 500) $haul = 0.15;
	if ($dist <= 1600 && $dist > 500) $haul = 0.12;
	if ($dist > 1600) $haul = 0.11;

	$temission = $dist * $haul;
	//echo $temission."<br>";
	$falloc = $temission * $freight;
	//echo $falloc."<br>";
	$emission = ($temission - $falloc) * $metric;
	return $emission;
}

//return ground emission in kgr
function ground_emission($dist, $type = false)
{
		if ($_SESSION['mode'] == 'car') $haul = 0.2124;
	elseif ($_SESSION['mode'] == 'van') $haul = 0.27376;
	elseif ($_SESSION['mode'] == 'sport') $haul = 0.30208;
	elseif ($_SESSION['mode'] == 'truck') $haul = 0.32804;
	elseif ($_SESSION['mode'] == 'hcar') $haul = 0.130221;
	elseif ($_SESSION['mode'] == 'hsuv') $haul = 0.204295;
	elseif ($_SESSION['mode'] == 'cab') $haul = 0.2457;
	elseif ($_SESSION['mode'] == 'limo') $haul = 0.47194875;
	elseif ($_SESSION['mode'] == 'bus') $haul = 0.0565;

	//now check the distance and if it was any of the 6 cities with ferry emission, add it to them.

		if (strpos($multi = $dist / 255.44, '.') === false) // Campbell River
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 208.44, '.') === false) // Courtenay
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 156.44, '.') === false) // Duncan
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 105.44, '.') === false) // Nanaimo
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 363, '.') === false) // Tofino
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 184.44, '.') === false) // Port Alberni
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 488.44, '.') === false) // Port Hardy
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.8715 * $multi;
		else $ferry_emission = 27.573 * $multi;

		$ferry_distance = 55.56 * $multi;
	}
	elseif (strpos($multi = $dist / 187.55, '.') === false) // Victoria
	{
		if ($_SESSION['mode'] == 'bus') $ferry_emission = 1.9266 * $multi;
		else $ferry_emission = 28.385 * $multi;

		$ferry_distance = 44.448 * $multi;
	}

	if (!$type) return $dist * $haul + $ferry_emission;
	elseif ($type == 'ground') return $dist * $haul;
	elseif ($type == 'ferry') return $ferry_emission;
	elseif ($type == 'ferry_distance') return $ferry_distance;
}

echo '</div>';

include 'footer.php';

?>

