<?php
   define ('phpqr_path' , CORE_LIB_PATH.'/phpqrcode' );
      define ('temp_path', CORE_PATH.'/lib/phpqrcode/temp');
       $PNG_TEMP_DIR = phpqr_path.'/temp'.DIRECTORY_SEPARATOR;

      //html PNG location prefix
      $PNG_WEB_DIR = SITE_URL.'/core/lib/phpqrcode/temp/';



      include phpqr_path."/qrlib.php";
   $limit = $_GET['limit'];
   if(isset($_GET['limit']) && $_GET['limit'] != '') {
   	$limit = $_GET['limit'];
   } else {
   	$limit = 100;
   }


   $avail_flights = ICSScheduleMap::flights_from_location($icao, $limit);
   // Onclick Show schedules.
   ?>
   <div class="content-header">
   <div class="header-section">
      <h1>
         <i class="gi gi-airplane"></i><Strong>Flight Booking</Strong><br><small>Flight Operations | <?php echo SITE_NAME?> &copy; <?php echo date("Y"); ?></small>
      </h1>
   </div>
</div>

<div class="row">

   <div class="col-md-12">
   <div class="block">
      <div class="block-title">
         <h3>Available flights</h3>
      </div>
    <div class="mapcenter" align="center">
	<div id="schedule_search_map" style="width: 80%; height: 500px"></div>
</div>


<style>
	.leaflet-pulsing-icon {
    border-radius: 100%;
    box-shadow: 1px 1px 8px 0 rgba(0,0,0,0.75);
}

.leaflet-pulsing-icon:after {
    content: "";
    border-radius: 100%;
    height: 300%;
    width: 300%;
    position: absolute;
    margin: -100% 0 0 -100%;

}

@keyframes pulsate {
    0% {
        transform: scale(0.1, 0.1);
        opacity: 0;
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
        filter: alpha(opacity=0);
    }
    50% {
        opacity: 1;
        -ms-filter: none;
        filter: none;
    }
    100% {
        transform: scale(1.2, 1.2);
        opacity: 0;
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
        filter: alpha(opacity=0);
    }
}
</style>
<script src="<?php echo SITE_URL?>/lib/js/base_map.js"></script>
<script src="https://rawgit.com/mapshakers/leaflet-icon-pulse/master/src/L.Icon.Pulse.js"></script>

<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.0.6/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.0.6/dist/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet.markercluster@1.0.6/dist/leaflet.markercluster.js"></script>

<script type="text/javascript">

	// Creating a new map element.
	const map = createMap({
		render_elem: 'schedule_search_map',
		provider: '<?php echo Config::Get("MAP_TYPE"); ?>',
	});

		function get_api_request(yourUrl){
			var Httpreq = new XMLHttpRequest();
			Httpreq.open("GET",yourUrl,false);
			Httpreq.send(null);
			return Httpreq.responseText;
		}

	//Initializing Cluster Group
	var markersLayer = new L.LayerGroup();
	var markers = L.markerClusterGroup();
	map.addLayer(markersLayer);

  var apiURL = "<?php echo SITE_URL; ?>/action.php/schedules/flights_from_location_api/<?php echo $icao; ?>";
  var current_location = "<?php echo SITE_URL; ?>/action.php/schedules/current_location_api";

		var current_location = JSON.parse(get_api_request(current_location));
		var flights = JSON.parse(get_api_request(apiURL));
		console.log(current_location);


		map.setView(new L.LatLng(current_location.lat, current_location.lng), 4);

		var pulsingIcon_currentlocation = L.icon.pulse({
			iconSize: [12,12],
            fillColor: 'red',
            color: 'red',
            animate: true,
            heartbeat: 1
		});

		var pulsingIcon_displayairport = L.icon.pulse({
			iconSize: [12,12],
            fillColor: 'purple',
            color: 'purple',
            animate: true,
            heartbeat: 1
		});

		var current_location_pulsing_marker = L.marker([current_location.lat, current_location.lng],{icon: pulsingIcon_currentlocation}).bindTooltip("You are at " + current_location.name).addTo(map);
		var current_location_polyline = new L.LatLng(current_location.lat, current_location.lng);


		for(i=0; i<flights.length; i++) {

			var marker = L.marker([flights[i].arrlat, flights[i].arrlng]).bindTooltip(flights[i].arricao + " - " +  flights[i].code + flights[i].flightnum).addTo(map);
				marker.bindPopup('<p class="text-center"><center><img src="<?php echo SITE_URL; ?>/lib/images/airline/' + flights[i].code + '.png" style="width: 100px; height: auto;" /> <br> <h4 class="text-center"> ' + flights[i].code + flights[i].flightnum + '<br> <small> ' + flights[i].arricao + '</small></h4> <br>' + flights[i].aircraft + '<br> <span class="label label-primary">' + flights[i].flighttime + 'Hrs</span> <br><br> <a onclick="hotsnackbar("hsdone", "Your bid has been added!");" class="btn btn-success addBid btn-sm" style="color: #fff" href="<?php echo url('/schedules/bidSchedule'); ?>/' + flights[i].id + '">Bid Flight</a></center></p>');
 				markers.addLayer(marker);
 				markers.addTo(markersLayer);


	var airport_polyline_dep = new L.LatLng(flights[i].deplat, flights[i].deplng);
	var airport_polyline = new L.LatLng(flights[i].arrlat, flights[i].arrlng);
	var pointList = [airport_polyline_dep, airport_polyline];

	var drawPolyline = new L.Polyline(pointList, {
	    color: 'black',
    	weight: 2,
    	opacity: 1,
    	smoothFactor: 1
	});

	drawPolyline.addTo(map);

		if(i == (flights.length - 1)) {
			var depmarker = L.marker([flights[i].deplat, flights[i].deplng],{icon: pulsingIcon_displayairport}).bindTooltip("Departure Airport " + flights[i].depname).addTo(map);
			console.log("last");
		}

		}


	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: 50px; height: auto;" /><span class="text-primary">Schedule Map</span> ';
    return div;
	};
	legend.addTo(map);

</script>

   <hr>
      <div class="row">
      	<?php
         foreach($avail_flights as $route)
                {

                ?>
      <?php $cload = round($route->distance);
         if($cload < 1000) {
         	$cload_clr = 'success';
         	$notes ='<small><span class="label label-success">SHORT HAUL</span></small>';
         }
         else if($cload < 2500) {
         	$cload_clr = 'success';
         	$notes ='<small><span class="label label-success">MEDIUM HAUL</span></small>';
         }
         else if($cload < 3500) {
         	$cload_clr = 'warning';
         	$notes ='<small><span class="label label-warning">LONG HAUL</span></small>';
         }
         else {
         	$cload_clr = 'danger';
         	$notes = '<small><span class="label label-danger">ULTRA LONG HAUL</span></small>';
         }
         ?>
      <div class="col-md-4">
         <div class="block full">
            <center>
               <h3>
                  <span class="label label-primary"><strong><?php echo $route->code.''.$route->flightnum; ?></strong></span><br>
                  <small>
                  <span class="text-muted">
                  <a href="javascript:void(0)" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Departing @ <?php echo $route->deptime; ?> UTC"><?php echo $route->depicao; ?></a> <i class="fa fa-plane"></i>
                  <a href="javascript:void(0)" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Arriving @ <?php echo $route->arrtime; ?> UTC">
                  <?php echo $route->arricao; ?></a>
                  </span>
                  </small>
                  <?php
                     // Not all airline uses CodeShare, so normally the code gets ignored. 28.03.2019
                       $cs = CodeShareData::get_codeshares($route->id);
                       if($cs == '') {
                         $airline = OperationsData::getAirlineByCode($route->code);
                         $operator = $airline->name;
                         $logo = SITE_URL."/lib/images/airline/".$route->code.".png";
                       } else {
                         $op = CodeShareData::check_airline($cs->operator);
                         $operator = $op->name;
                         $logo = $op->image;
                       }

                     $schedule_id = SITE_URL."/index.php/schedules/bidSchedule/".$route->id;
                     // user data
                     $filename = $PNG_TEMP_DIR.'test'.md5($schedule_id.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
                     QRcode::png($schedule_id, $filename, "Q", "2", 2);

                     //display generated file

                     ?>
                  <br>
                  <img src="<?php echo $logo; ?>" style="height: 50px; width: auto;" />
                  <h5>Operated by <?php echo $operator; ?></h5>
                  <h6><?php echo $route->aircraft.' ('.$route->registration.')'; ?></h6>
                  <span class="badge"><?php echo $route->flighttime; ?> Hrs</span> <?php echo $notes; ?>
                  <br><br>
                  <?php echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" />'; ?>
                  <h6><i class="text-muted">Scan the code to bid this flight <br>
                     <small>(ID: <?php echo md5($route->flightnum); ?>)</small></i>
                  </h6>
               </h3>
            </center>
            <ul class="pager">
               <!--<li class="previous"><a href="javascript:void(0)" data-toggle="tooltip" data-placement="top" title="" data-original-title="Departing @ <?php echo $route->deptime; ?> UTC"><?php echo $route->depicao; ?></a></li>-->
               <!--<li class="next"><a href="javascript:void(0)" data-toggle="tooltip" data-placement="top" title="" data-original-title="Arriving @ <?php echo $route->arrtime; ?> UTC"><?php echo $route->arricao; ?></a></li>-->
               <ul class="pagination text-center">
                  <li>
                     <?php
                        # Don't allow overlapping bids and a bid exists
                        if(Config::Get('DISABLE_SCHED_ON_BID') == true && $route->bidid != 0) {
                        	echo '<a id="'.$route->id.'" class="addbid" href="'.actionurl('/schedules/addbid').'">Add to Bid</a>';
                        	} else {
                        		if(Auth::LoggedIn()) { ?>
                     <a onclick="setTimeout('window.location.href=\'<?php echo SITE_URL; ?>/index.php/schedules/brief/<?php echo $route->id; ?>\';', 2000); hotsnackbar('hsdone', 'Your bid has been added!'); play(); loadScheduleBrief();"  id="<?php echo $route->id; ?>" class="addbid" href="<?php echo url('/schedules/addbid'); ?>" data-toggle="tooltip" data-placement="top" title="" data-original-title="Add bid!"><i class="fa fa-plus"></i></a>
                     <?php
                        }
                        }
                        ?>
                  </li>
                  <li><a href="<?php echo url('/schedules/details/'.$route->id);?>" target="_blank" data-toggle="tooltip" data-placement="top" title="" data-original-title="View flight info" ><i class="fa fa-info"></i></a></li>
               </ul>
            </ul>
         </div>
      </div>
      <?php
         /* END OF ONE TABLE ROW */
         }
         ?>
      </div>
   </div>
   </div>
</div>
