<!-- Inbox Header -->
<div class="content-header">
   <div class="header-section">
      <h1><i class="gi fa-spin gi-radar"></i> <Strong>ACARS</Strong> Flight Tracker<br><small>Flight Operations | <?php echo SITE_NAME?> &copy; 2017</small></h1>
   </div>
</div>
<!-- END Inbox Header -->
<div class="row">
   <div class="col-md-12">
      <a href="javascript::(0)" class="widget widget-hover-effect5">
         <div class="widget-simple">
            <h3 class="widget-content text-center animation-pullDown">
               <strong><?php echo $acarsdata->flightnum?></strong><br>
               <small>Last update on : <?php echo date('H:i:s', strtotime($acarsdata->lastupdate)); ?></small>
            </h3>
         </div>
      </a>
   </div>
</div>
<?php 
   $flightnum = SchedulesData::getProperFlightNum($acarsdata->flightnum);
   $schedule = SchedulesData::getScheduleByFlight($flightnum['code'], $flightnum['flightnum']);
   $schedule = SchedulesData::getSchedule($schedule->id);
   
   ?>


<div class="col-md-4">
   <div class="widget">
      <div class="widget-extra-full">
         <div id="widget-carousel6" class="carousel slide remove-margin">
            <div class="carousel-inner">
               <div class="active item">
                  <?php 
                     /*Aircraft Images*/
                     $reg = $acarsdata->aircraft;
                     $aircraft = OperationsData::getAircraftByReg($reg);
                     $imagelink = $aircraft->imagelink;
                     if($imagelink == '')
                     {
                     	$imagelink = 'https://icrew.piavirtual.org/iCrew/airlinepics/404.png';
                     	$text = '<span class="text-center text-muted">Aircraft image not found in database</span>';
                     }
                     
                     ?>
                  <img src="<?php echo $imagelink; ?>" width="auto;" height="70;" alt="image">
                  <?php if($text) { echo '<span class="text-center">'.$text.'</span>'; } ?>
               </div>
            </div>
         </div>
      </div>
      <div class="widget-simple themed-background-muted">
         <h6 class="widget-content widget-content-light">
            <span class="pull-left">
            <Strong><span data-toggle="tooltip" title="<?php echo $acarsdata->depapt; ?>">
            <?php echo $acarsdata->depicao; ?>
            </span>
            </span>
            <span class="pull-right">
            <span data-toggle="tooltip" title="<?php echo $acarsdata->arrapt; ?>">
            <?php echo $acarsdata->arricao; ?>
            </span>
            </span>
            </Strong>
         </h6>
         <br>
         <h6 class="widget-content widget-content-light">
            <small><span class="pull-left">
            <?php echo date('H:i', strtotime($acarsdata->deptime)); ?> z
            </span>
            <span class="pull-right">
            <?php echo date('H:i', strtotime($acarsdata->arrtime)); ?> z
            </span>
            </small>
         </h6>
      </div>
      <?php $pilotdetail = PilotData::getPilotData($thepositions->pilotid); ?>
      <div class="widget widget-hover-effect2">
         <div class="widget-extra themed-background text-center">
            <h4 class="widget-content-light"><strong>Status</strong></h4>
         </div>
         <div class="widget-extra-full text-center">
            <span class="h2 animation-expandOpen"></span>
            <h3>
               <?php 
                  $phase = $acarsdata->phasedetail;
                  if($phase == "Preflight")
                  {
                  	echo '	<span class="label label-default">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Taxiing to Runway")
                  {
                  	echo '	<span class="label label-warning animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Pushing Back")
                  {
                  	echo '	<span class="label label-warning animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Taking Off")
                  {
                  	echo '	<span class="label label-primary animation-pulse">
                  			'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Climbing")
                  {
                  	echo '	<span class="label label-primary animation-pulse">
                  			'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Cruising")
                  {
                  	echo '	<span class="label label-success">
                  				'. $acarsdata->phasedetail .' </span>';
                  }
                  else if ($phase == "Descending")
                  {
                  	echo '	<span class="label label-success animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Approaching")
                  {
                  	echo '	<span class="label label-primary animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Final Approach")
                  {
                  	echo '	<span class="label label-primary animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Landing")
                  {
                  	echo '	<span class="label label-primary animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else if ($phase == "Taxiing to Gate")
                  {
                  	echo '	<span class="label label-warning animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  else 
                  {
                  	echo '	<span class="label label-danger animation-pulse">
                  				'. $acarsdata->phasedetail .'
                  			</span>';
                  }
                  
                  ?>	
            </h3>
         </div>
      </div>
      <?php 
         //calculating the Estimated Enroute Time 
         $dep = date("H:i",strtotime($acarsdata->deptime)); 
         $arr = date("H:i",strtotime($acarsdata->arrtime));
         $dept = new DateTime($dep);
         $arrt = new DateTime($arr);
         $eet = $dept->diff($arrt);
         
         //Estimated Enroute Time in Hours and Minutes Format
         $EET =  $eet->format("%H:%i");
         
         
         //Serperating the EET into Hours and Minutes
         $hours = date("H",strtotime($EET));
         $minutes = date("i",strtotime($EET));
         
         //Converting Hours into minutes and adding the Remaining Minutes
         $estimated = ($hours * 60) + $minutes;
         	if ($estimated == 0)
         		{
         			$prog = 0.5;
         			$pgbarcolor = "danger";
         		}
         	elseif ($estimated < 0)
         		{
         			$prog = 0.5;
         			$pgbarcolor = "danger";
         		}
         	else 
         		{
         			$finaleet = $estimated;
         			//Seperating the Elapsed time provided by the ACARS Data
         			$acarshours = date("H",strtotime($acarsdata->timeremaining));
         			$acarsminutes = date("i",strtotime($acarsdata->timeremaining));
         			//Converting the Elapsed time into Minutes 
         			$elapsed = ($acarshours * 60) + $acarsminutes;
         				$elapsedhours = $eet->format("%H");
         				# echo $elapsedhours.'<br>';
         				if ($acarsdata->phasedetail == "Arrived")
         					{
         						$prog = 100;
         						$pgbarcolor = "danger";
         					}
         				
         				else if ($elapsed == 0)
         					{
         						$finalete = ($elapsedhours * 60) + $acarsminutes;
         						
         						$progress = ($finalete / $finaleet) * 100;
         						$prog = 100 - $progress;
         						$pgbarcolor = "warning";
         					}
         				else 
         				{
         						$finalete = $elapsed;
         						
         						$progress = ($finalete / $finaleet) * 100;
         						$prog = 100 - $progress;
         						$pgbarcolor = "success";
         					}
         		}
         			#	echo $finalete;
         			#	echo "<br>";
         			#	echo $acarsdata->timeremaining;
         			#	echo "<br>";
         			#	echo $estimated;
         			#	echo "<br>";
         			#	echo $acarsminutes;
         			#	echo "<br>";
         			#	echo $elapsed;
         			#	echo "<br>";
         			#	echo $prog;
         ?>
      <?php 
         ?>
      <div class="widget-main">
         <div class="list-group remove-margin">
            <a href="javascript:void(0)" class="list-group-item">
               <span class="pull-right"><strong><?php echo $acarsdata->pilotname; ?></strong></span>
               <h5 class="list-group-item-heading remove-margin"><i class="fa fa-user fa-fw"></i> Pilot in Command </h5>
            </a>
            <a href="javascript:void(0)" class="list-group-item">
               <span class="pull-right"><strong><?php echo $acarsdata->aircraft; ?></strong></span>
               <h5 class="list-group-item-heading remove-margin"><i class="fa fa-file fa-fw"></i> Aircraft Registration </h5>
            </a>
            <a href="javascript:void(0)" class="list-group-item">
               <span class="pull-right"><strong><?php echo $acarsdata->timeremaining; ?> Hr</strong></span>
               <h5 class="list-group-item-heading remove-margin"><i class="fa fa-clock-o fa-fw"></i> Arriving in  </h5>
            </a>
         </div>
      </div>
   </div>
   <div class="widget widget-hover-effect2">
      <div class="widget-extra themed-background text-center">
         <h4 class="widget-content-light"><strong>Client</strong></h4>
      </div>
      <div class="widget-extra-full text-center">
         <span class="h2 animation-expandOpen"></span>
         <h4><?php echo $acarsdata->client; ?></h4>
      </div>
   </div>
</div>
<div class="col-md-8">

<?php 
         $dep = OperationsData::getAirportInfo($acarsdata->depicao);
         $arr = OperationsData::getAirportInfo($acarsdata->arricao);
         
         	$groundspeed = $acarsdata->gs;
         	$gspercent = ($groundspeed / 650) * 100;
         	$ias = floor($gspercent);
         	
         	$alti = $acarsdata->alt; 
         $altchr = ($alti / 39500) * 100;
         $altchart = floor($altchr);
         
         
         	$hdg = $acarsdata->heading; 
         $hdgchr = ($hdg / 360) * 100;
         $hdgchart = floor($hdgchr);
         ?>
         
    <style>
    	.myCSSClass {
			background: #ffffff;
			border: 2px solid black
		}
		
		.leaflet-tooltip-left.myCSSClass::before {
			border-left-color: black;
		}
			
		.leaflet-tooltip-right.myCSSClass::before {
			border-right-color: black;
		}
    </style>
   <div class="block">
   	<div class="block-title">
      <h3>Live<strong>Map</strong></h3>
   </div>
     <div class="mapcenter" align="center">
      <div id="routemap" style="width:100%; box-sizing:border-box; height: <?php echo Config::Get('MAP_HEIGHT')?>">
      </div>
      <script type="text/html" id="navpoint_bubble">
         <span style="font-size: 10px; text-align:left; width: 100%" align="left">
         <strong>Name: </strong><%=nav.title%> (<%=nav.name%>)<br />
         <strong>Type: </strong>
         <?php	/* Show the type of point */ ?>
         <% if(nav.type == 2) { %> NDB <% } %>
         <% if(nav.type == 3) { %> VOR <% } %>
         <% if(nav.type == 4) { %> DME <% } %>
         <% if(nav.type == 5) { %> FIX <% } %>
         <% if(nav.type == 6) { %> TRACK <% } %>
         <br />
         <?php	/* Only show frequency if it's not a 0*/ ?>
         <% if(nav.freq != 0) { %>
         <strong>Frequency: </strong><%=nav.freq%>
         <% } %>
         </span>
      </script>
      <?php
         /*	Below here is all the javascript for the map. Be careful of what you
         	modify!! */
         ?>
      <script src="<?php echo SITE_URL?>/lib/js/base_map.js"></script>
      <script src="https://iosphere.github.io/Leaflet.hotline/dist/leaflet.hotline.js"></script>
      <script src="https://raw.githubusercontent.com/iosphere/Leaflet.hotline/master/demo/js/coords.js"></script>
      <script type="text/javascript">
         // Write the PIREP data out into JSON
         // The big reason being we don't need to have PHP writing JS - yuck
         const flight = JSON.parse('<?php echo json_encode($schedule); ?>');
         const acars = JSON.parse('<?php echo json_encode($acarsdata); ?>');
         console.log(flight);
         
         const map = createMap({
         	render_elem: 'routemap',
         	provider: '<?php echo Config::Get("MAP_TYPE"); ?>',
         	center: L.latLng("<?php echo Config::Get('MAP_CENTER_LAT'); ?>", "<?php echo Config::Get('MAP_CENTER_LNG'); ?>")
         });
         
         
         	var legend = L.control({position: 'bottomright'});
         
         	legend.onAdd = function (map) {
         
             var div = L.DomUtil.create('div', 'info legend');
                 div.innerHTML = '<img src="<?php echo SITE_URL; ?>/iCrew/favicon.png" style="width: 30px; height: auto;" />';
         
             return div;
         	};
         
         	legend.addTo(map);
         
         	<?php
            echo "var DrivePath = [";
            	foreach($posreports as $path) {
            			
            			echo "new L.LatLng(".$path->latitude.", ".$path->longitude."),"; 
            		} 
            	echo "];";
            ?>
         	
         	<?php
            echo "var hotlinePath = [";
            	foreach($posreports as $hotline) {
            			echo "[".$hotline->latitude.",".$hotline->longitude.",".$hotline->altitude."], ";
            		} 
            	echo "];";
            ?>
         	
         	
         	var hotlineOptions = {
         			min: 0,
         			max: 41000,
         			palette: {
         				0.1: '#f2ff00',
         				0.3: '#73ff00',
         				0.5: '#00ff80',
         				0.7: '#00d5ff', 
         				0.8: '#0004ff',
         				1.0: '#7b00ff',
         				
         			},
         			weight: 3,
         			outlineColor: '#000000',
         			outlineWidth: 1,
           };
           
         
         	// If you don't want to show the Colored line. 
         	
         	// var acarspath = new L.Polyline(DrivePath, {
          //   	color: getColor(acars.alt),
          //   	weight: 3,
          //   	opacity: 0.9,
          //   	smoothFactor: 1
         	// });
         	
         	// acarspath.addTo(map);
         
         
         	var hotlineLayer = L.hotline(hotlinePath, hotlineOptions).addTo(map);
             
             
             //////////////// END HOTLINE ///////////////////////    
         
         	const depCoords = L.latLng(flight.deplat, flight.deplng);
         		selDepMarker = L.marker(depCoords, {
         	}).bindPopup("DEPARTURE: " + flight.depname + " " + flight.depicao).addTo(map);
         
         
         	const arrCoords = L.latLng(flight.arrlat, flight.arrlng);
         		selArrMarker = L.marker(arrCoords, {
         	}).bindPopup("ARRIVAL: " + flight.arrname + " " + flight.arricao).addTo(map);
         
         	let points = [];
         	points.push(depCoords);
         	
         	// Get heading Icon 
         	var heading = acars.heading;
         	var aircraft_position = "[" + acars.lat + "," + acars.lng + "]";
             
             let headingIcons = {};
         	const getHeadingIcon = (heading) => {
                 if (!(heading in headingIcons)) {
                     headingIcons[heading] = L.icon({
                         iconUrl: url + "/lib/images/inair/" + heading + ".png",
                         iconSize: [50, 50]
                     });
                 }
         
                 return headingIcons[heading];
             };
         	
         	console.log(acars);
         	console.log(aircraft_position);
         	
         
         	L.marker([acars.lat, acars.lng], {icon: getHeadingIcon(heading)}).bindPopup('<span class="label label-primary"><?php echo $acarsdata->flightnum; ?></span> <br><br> Ground Speed : <?php echo $acarsdata->gs; ?>KTS <br> Heading : <?php echo $acarsdata->heading; ?>&deg; <br> Altitude : <?php echo $acarsdata->alt; ?>ft AMSL' + 
         	 '<br><img src="<?php echo fileurl('/lib/images/airline/'.$flightnum["code"].'.png'); ?>" width="127px" height="auto;" />' + '<br> <hr><?php if(!$acarsdata->online)
            {
            	echo 'OFFLINE';
            }
            else {
            	switch ($acarsdata->online) {
            
            		case 'IVAO':
            			echo '<center><img src="https://upload.wikimedia.org/wikipedia/commons/5/53/IVAO_Logo.png" style="width: 50px; height: auto;"></center>';
            		break;
            
            		case 'VATSIM':
            			echo '<center><img src="https://fselitemedia.nyc3.digitaloceanspaces.com/fselite/2018/08/vatsim.jpg" style="width: 90px; height: auto;"></center>';
            		break;
            
            		default:
            			echo strtoupper($acarsdata->online);
            		break;
            	}
            	} ?>').bindTooltip(acars.flightnum+' Click to see more', {className: 'myCSSClass'}).addTo(map);
         
         	
         
         
         // THIS IS IF YOU WANNA SHOW THE ROUTE!
         // 	// rendering for if there's smartcars data
         // 	if(flight.rawdata instanceof Object 
         // 	&& flight.rawdata.points !== undefined
         // 	&& Array.isArray(flight.rawdata.points)
         // 	) {
         // 		$.each(flight.rawdata.points, function(i, nav) {
         // 		if(nav.lat === undefined || nav.lng === undefined) {
         // 			return;
         // 		}
         
         // 		points.push(L.latLng(nav.lat, nav.lng));
         // 	});
         // 	} else {
         // 	$.each(flight.route_details, function(i, nav) {
         // 		const loc = L.latLng(nav.lat, nav.lng);
         // 		const icon = (nav.type === 3) ? MapFeatures.icons.vor : MapFeatures.icons.fix;
         // 		points.push(loc);
         
         // 		const marker = L.marker(loc, {
         // 				icon: icon,
         // 				title: nav.title,
         // 			})
         // 			.bindPopup(tmpl("navpoint_bubble", { nav: nav }))
         // 			.addTo(map);
         // 	});
         // }
         
         points.push(arrCoords);
         
         const selPointsLayer = L.geodesic([points], {
         	color: 'black',
             weight: 5,
         	opacity: .7,
         	dashArray: '10,9',
         	lineJoin: 'round'
         }).addTo(map);
         
         map.on('click', function(e) {
             // alert(" You have clicked at " + e.latlng);
         } );
         
         
         
         	
         map.fitBounds(selPointsLayer.getBounds());
      </script>
   </div>
      <p class="text-center text-muted">Flight Progress</p>
      <?php 
         /*ALGORITHM FOR FLIGHT PROGRESS*/
            $depicao = $acarsdata->depicao;
            $arricao = $acarsdata->arricao;
            $dist = OperationsData::getAirportDistance($depicao, $arricao);
            $distremain = $acarsdata->distremain;
            $progress = 100 - (($distremain / $dist) * 100);
            $progressbar_val = floor($progress);
            if($progressbar_val < 10)
            {
              $progressbar_clr = 'info';
            }
            elseif($progressbar_val < 50)
            {
              $progressbar_clr = 'success';
            }
            elseif($progressbar_val < 80)
            {
              $progressbar_clr = 'warning';
            }
            elseif($progressbar_val < 100)
            {
              $progressbar_clr = 'danger';
            }
            
            ?>
      <div class="progress progress-striped active">
         <div class="progress-bar progress-bar-<?php echo $progressbar_clr?>" role="progressbar" aria-valuenow="<?php echo $progressbar_val?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $progressbar_val?>%"><?php echo $progressbar_val?>%</div>
      </div>
   </div>
</div>
<div class="col-md-12">
   <div class="block">
      <div class="block-title">
         <div class="block-options pull-right">
            <span class="label label-danger animation-pulse">LIVE</span>
         </div>
         <h3><strong>Flight </strong> Parameters</h3>
      </div>
      <div class="row">
         <div class="col-sm-4">
            <div class="pie-chart block-section easyPieChart" data-percent="<?php echo $ias; ?>" data-size="130" style="width: 90px; height: 90px; line-height: 90px;">
               <span><?php echo $acarsdata->gs; ?> kts</span>
               <canvas width="20" height="20"></canvas>
            </div>
            <p class="text-center">Groundspeed</p>
         </div>
         <div class="col-sm-4">
            <?php 
               ?>
            <div class="pie-chart block-section easyPieChart" data-percent="<?php echo $altchart; ?>" data-size="130" style="width: 90px; height: 90px; line-height: 90px;">
               <span><?php echo $acarsdata->alt; ?> ft</span>
               <canvas width="20" height="20"></canvas>
            </div>
            <p class="text-center">Altitude</p>
         </div>
         <div class="col-sm-4">
            <?php 
               ?>
            <div class="pie-chart block-section easyPieChart" data-percent="<?php echo $hdgchart; ?>" data-size="130" style="width: 90px; height: 90px; line-height: 90px;">
               <span><?php echo $acarsdata->heading; ?>&deg;</span>
               <canvas width="20" height="20"></canvas>
            </div>
            <p class="text-center">Heading</p>
         </div>
      </div>
      <canvas id="flightGraph"></canvas>
   </div>
</div>
<script>
   var flightGraph = document.getElementById("flightGraph");
   var lineChart = new Chart(flightGraph, {
     type: 'line',
       data: {
           datasets: [{
               label: "Airspeed",
       data: [<?php foreach ($posreports_g as $graph) { echo $graph->groundspeed.","; } ?>],
       lineTension: 0.3,
       fill: false,
       borderColor: 'yellow',
       backgroundColor: 'transparent',
       pointBorderColor: 'yellow',
       pointBackgroundColor: 'yellow',
       pointRadius: 1,
               // This binds the dataset to the left y axis
               yAxisID: 'left-y-axis'
           }, {
               label: "Altitude",
       data: [<?php foreach ($posreports_g as $graph) { echo $graph->altitude.","; } ?>],
       lineTension: 0.3,
       fill: false,
       borderColor: 'green',
       backgroundColor: 'transparent',
       pointBorderColor: 'green',
       pointBackgroundColor: 'green',
       pointRadius: 1,
   
               // This binds the dataset to the right y axis
               yAxisID: 'right-y-axis'
           }],
           labels: [<?php foreach ($posreports_g as $graph) { echo '"'.date("H:i:s", strtotime($graph->positiontime)).'", '; } ?>]
       },
       options: {
       	responsive: true,
                   hoverMode: 'index',
                   stacked: false,
                   title:{
                       display: true,
                       text:'LiveData chart - hover on the graph to see data.'
                   },
           scales: {
               yAxes: [{
                   id: 'left-y-axis',
                   type: 'linear',
                   position: 'left'
               }, {
                   id: 'right-y-axis',
                   type: 'linear',
                   position: 'right'
               }]
           }
       }
   });
</script>
<div class="row">
   <div class="col-md-12">
      <div class="block">
         <div class="block-title">
            <div class="block-options pull-right">
               <span class="label label-success">Total Packages Received : <?php echo count($posreports); ?></span>
            </div>
            <h3><i class="gi gi-notes_2"></i> ACARS Report transcript for <?php echo $acarsdata->flightnum; ?></h3>
         </div>
         <div style="overflow: auto; height: 400px; margin-bottom: 20px; padding: 5px; padding-top: 0px; padding-bottom: 20px;">
            <table class="table table-responsive">
               <thead>
                  <th>Package</th>
                  <th>Time</th>
                  <th>Phase</th>
                  <th>Altitude</th>
                  <th>Ground Speed</th>
                  <th>Latitude</th>
                  <th>Longitude</th>
               </thead>
               <tbody>
               </tbody>
               <?php 
                  $sno = count($posreports);
                  foreach($posreports as $thepositions)
                  { 
                  ?>
               <tr>
                  <td><?php echo $sno; ?></td>
                  <td><?php echo date('H:i:s', strtotime($thepositions->positiontime)); ?> z</td>
                  <td><?php echo $thepositions->phase; ?></td>
                  <td><?php echo $thepositions->altitude; ?>ft AMSL</td>
                  <td><?php echo $thepositions->groundspeed; ?>kts</td>
                  <td><?php echo $thepositions->latitude; ?></td>
                  <td><?php echo $thepositions->longitude; ?></td>
               </tr>
               <?php
                  $sno--;
                  }
                  ?>
            </table>
         </div>
      </div>
   </div>
</div>