<?php session_start();  ?>
<br/> 
 <a href="http://www.trekescapes.com/">
<img src="images/trek.jpg" width="280" height="111" border="0" /></a>
<br/>
<?php 

/*
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Routing</title>
</head>
<body>';
*/
     //$_SESSION['val'] = $_POST;
	 // print_r($_POST);
     // echo "<br/>Routing Test Page";
    
      /*info from the from*/
	  if(isset($_POST['calculate']))
	  {
              $calculate = false;  
	      $passengers = $_SESSION['pass'] ;
	  	  $rout = $_SESSION['rout'] ;
		  $count =  $_SESSION['count'];
		 // $origin = $_POST["radioorigin"];
		   for($i = 0; $i <= $count ; $i++ )
		  {
		  	   $destination[$i] = $_POST["radiodestin" . $i];
		  }
		 
	  }
	  else
	  {
	       $calculate = true;  
	      $count = $_POST["destination"] ;
  	    $_SESSION['count'] = $count;
		  $passengers = (int)$_POST["passengers"] ;
		
		  $_SESSION['pass'] = $passengers;
		  if( $_POST["Routing"] == "return" )
	  	  {
	        $rout = 2; //return
		    $_SESSION['rout'] = $rout;
			$_SESSION['flight'] = 'round-trip';
	 	  }
		  else 
	 	  {
	        $rout = 1;  //single
	        $_SESSION['rout'] = $rout;
			$_SESSION['flight'] = 'One-way';
		  }
	      
		  for($i = 0; $i <= $count ; $i++ )
		  {
		  	   $destination[$i] = $_POST["destination". $i];
		  }
	  }
	  
	
	  // print_r($_SESSION['pass']);
	  //$temp = is_int( $_POST["passengers"] );
	 
	  if ($passengers == '0')
	  {
	      echo "Passengers entry is not a valid number. Please change the input.<br>";
		  return;
	  }
	  
	  /* Connection to MySQL Database*/
	  $host="mysql103.mysite4now.com";
      $user="external";
      $password="ocns";
	  $database="ocns_calculator";
	  $table="airports";
	  //Connection
	  $cxn = mysqli_connect($host,$user,$password,$database);
	  $multiple = false; 
if($calculate)
	  {
 for($i = 0; $i <= $count ;$i++ )
	  {
	       
		   if(empty($destination[$i])) 
		   {
		         echo "<h3> Please enter inputs. </h3>";
		  		 return; //set a flag here to write the error. 
		   }
		   $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;
				
		   
	 }
		} //if they press calculate so there is only one destination to calculate
		else	
        {
		    for($i = 0; $i <= $count ; $i++ )
	  	    {
				$query="SELECT * FROM ".$table." WHERE iata=\"". $destination[$i] ."\"";
	       		$result [$i] = mysqli_query($cxn,$query);
		   		if($result[$i] == false )
		   		{
						echo "<h4>Error: ".mysqli_error($cxn)."</h4>";
						return;
		   		}
			}
 	    }


	 if($multiple)
	 {
	        
	       	echo '<form action="index.php?'. SID .'" method="post" target="_self">';
	        for($j = 0; $j <= $count; $j++) 
			{         
               		
	 		        echo '<br><h2>Airport '.$j.' : </h2>';
					$form = null;
					$text = 'radio';
					for($i = 1; $i <= $nrows[$j]; $i++) 
					{
					    $row = mysqli_fetch_assoc($result[$j]);
          				$input = createInput($text."destin".$j,$row['iata'],$text,$i==1);
						$form .= $input;
						
						 $form .= '<b>'. ucwords(strtolower( $row['name'])) . ' (' . $row['iata'] .')' .  '</b> airport at <b>' 
							  . ucwords(strtolower( $row['city'])) . '-'  .
							    ucwords(strtolower( $row['country'])) . '</b>' ."</label><br /> \n";
						
						
					}		
					echo $form;
			}
					echo '<br><input name="calculate" type="submit" value="calculate emissions" />';
					echo '</form>';	
					return;	
       }//end of multiple
	   // Report starts from this line. 
	   echo '<br/><h2> Flight(s) </h2>';
	   echo  '<b>'. $passengers . '</b> passenger(s) <b>' .  $_SESSION['flight'] . ' </b>flight(s) : <br/><br/>';
	        
			  for($j = 0; $j <= $count; $j++) 
			  {
			      	$row[$j] = mysqli_fetch_assoc($result[$j]);
			  
			  }
		   
		   
		    for($j = 0; $j < $count; $j++) 
			{         
				
					    $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 ;
      						   
						}
						
						
						
						echo   'From <b>' 
						      . ucwords(strtolower( $row[$j]['name'])) . ' (' . $row[$j]['iata'] .')' .  '</b> airport at <b>' 
							  . ucwords(strtolower( $row[$j]['city'])) . '-'  .
							    ucwords(strtolower( $row[$j]['country']))  
							     .'</b> to  <b>' . ucwords(strtolower($row[$j+1]['name'])) .  ' (' . $row[$j+1]['iata'] .')'  . 
								   '</b> airport at <b>' .  ucwords(strtolower($row[$j+1]['city'])) . '-' . 
							 ucwords(strtolower($row[$j+1]['country'])) .'</b>' ;
						echo '<br/>';
						$dist = distance($orglat,$orglong,$deslat,$deslong, "k") ;
						//echo floor($dist)* $rout . " kilometers<br>";
						$total =  emission( $dist );
						//echo  round($total) . " kilograms<br>";
						$cton += round($total/1000,3);
						//echo $cton . " tonne<br>";
						$totaldist += floor($dist);
						$emission += round($total);
						echo 'Distance: <b>' .  floor($dist) . ' </b>kilometers per leg,&nbsp;&nbsp;&nbsp;Emissions per passenger: <b>' . round($total) . ' </b>kilograms of CO2e per leg.<br/><br/>'; 
						         
				    
		}
		
		
		echo '<hr>';
			echo '<h3> Emission, Distance, and Cost Summary:</h3>';
		echo 'Total trip distance:<b> '  . $totaldist * $rout  . '</b> km/passenger. <br/> ';
		echo 'Total trip emissions:<b> '  .number_format($rout * $cton, 1, '.', '') . '</b> tonne/passenger. <br/> ';
		$number = $rout * $passengers * $cton * 16 ;
		echo 'Total offset cost to make your flight(s) for <b> '  .$passengers  . '</b> passenger(s) climate friendly  
		      is only: <b>$' .number_format($number, 2, '.', '').' </b>(CDN)<br/><hr>';
		echo '<h3> Save to Database :</h3>';
		//save the inputs in sessions so we can access them in the confirmation page, add a name form hear before sending us to
		//the next page.
        $_SESSION['emission'] = number_format($rout * $cton, 1, '.', '');
        $_SESSION['distance'] = $totaldist * $rout ; 
		$_SESSION['cost'] = number_format($number, 2, '.', '');
       	echo '<form action="confirm.php?'. SID .'" method="post">';
		echo '<label> Transaction ID: <br />';
		echo '<input name="transaction" type="text" />';
		echo '</label><br/>';
		echo '<label> Agent Code: <br />';
		echo '<input name="agent" type="text" />';
		echo '</label><br/>';
		echo '<label> Enter Traveler Name(optional): <br />';
		echo '<input name="name" type="text" />';
		echo '</label><br/>';
        echo '<input name="confirmsave" type="submit" value="Confirm" />';
		echo '</form>';
			
 ?>


<br/>
<a href="index.php" title="New" accesskey="n" target="_self">New calculation</a>
<br/>
<br/>

  <a href="http://www.offsetters.ca">
<img src="http://www.trekescapes.com/offsetting/images/ofsetters-logo.gif" width="250" height="98" border="0" /></a>

<?php
 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); 
  } else if ($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;
}

function createInput($name, $value, $type, $checked)
{
	return "<input type=\"{$type}\" name=\"{$name}\" value=\"{$value}\" " . ( $checked ? " checked = \"checked\" " : "" ) . "/>" ;
}
//echo '</body></html>';
?>
 






























