<?php 
	class ICSTour extends CodonModule {
		
		public function __construct() {
			CodonEvent::addListener('ICSTour', array('pirep_filed'));
		}
		
		public function EventListener($eventinfo) {
			$eventname = $eventinfo[0]; // Event name
			$eventmodule = $eventinfo[1]; // Class calling it
			if($eventinfo[0] == 'pirep_filed') { 
				// Getting the most recent PIREP!
			$pirep = DB::get_row("SELECT * FROM ".TABLE_PREFIX."pireps ORDER BY pirepid DESC LIMIT 1");
			// $pirep = DB::get_row("SELECT * FROM ".TABLE_PREFIX."pireps WHERE `pirepid` = '41652'");
			// echo $pirep->code.$pirep->flightnum;
			// echo "<br>";
			//LogData::addLog(3,"Looking for schedule with flight number: ".$pirep->code.$pirep->flightnum);
			$schedules = SchedulesData::getScheduleByFlight($pirep->code, $pirep->flightnum);
				if($schedules != '') {
					
					// Save Tour progress.
					
					$flightentry = ICSTourData::getFlightEntry($pirep->code.$pirep->flightnum);
					// print_r($flightentry);
					if($flightentry == '') {
						//DiscordData::deliver('Unable to process Tour PIREP (#'.$pirep->pirepid.'). Flight Entry not found.', DISCORD_ADMIN_TEXT_CHANNEL);
						return;
					}
					
					if($flightentry->pilotid == '' || $flightentry->tourid == '' || $pirep->depicao == '' || $pirep->arricao == '') {
						DiscordData::deliver('Unable to process Tour PIREP (#'.$pirep->pirepid.'). Parameters required to update tour leg are missing. ', DISCORD_ADMIN_TEXT_CHANNEL);
						return;
					}

					$sql_reply = ICSTourData::updateTourPosition($flightentry->pilotid, $flightentry->tourid, $pirep->depicao, $pirep->arricao);
					
					ICSTourData::deleteFlightEntry($flightentry->pilotid, $flightentry->tourid, $flightentry->legid);
					// IF LAST LEG, Send mails, add award.
					
					LogData::addLog(3,"Deleting Tour Schedule: ".$schedule->id." for PIlot ID: ".$flightentry->pilotid);
					SchedulesData::deleteSchedule($schedules->id);
					PIREPData::addComment($pirep->pirepid, $pirep->pilotid, "This Tour Flight was Processed, Schedule ".$pirep->code.$pirep->flightnum." was deleted. (this comment was added by the ToursModule)");
					DiscordData::deliver('Tour PIREP (#'.$pirep->pirepid.') for Pilot '.$pirep->pilotid.' was successfully evaluated', DISCORD_ADMIN_TEXT_CHANNEL);
				} else {
					// DiscordData::deliver('Unable to process Tour PIREP (#'.$pirep->pirepid.'). Schedule was not found!', DISCORD_ADMIN_TEXT_CHANNEL);
				}
			}
		}

	
		
		public function index() {
			
			$participatingTours = ICSTourData::pilotParticipatingTours(Auth::$userinfo->pilotid);
			$this->set('participatingTours', $participatingTours);
			$this->set('randomTour', ICSTourData::getRandomTour());
			$this->set('tours', ICSTourData::getActiveTours(0));
			$this->show('ICSTour/index');
		}
		
		public function details($tourid = '') {
			if($tourid == '') {
				$this->set('message', 'Tour ID is missing');
				$this->show('core_error.php');
				return;
			}
			
			
			
			$this->set('tour', ICSTourData::getTour($tourid));
			$this->set('tourParticipants', ICSTourData::getTourParticipants($tourid));
			$this->show('ICSTour/details');
			
		}
		
		public function tour_map_api($tourid) {
			$tour = ICSTourData::getTour($tourid);
			$legs = ICSTourData::getTourLegs($tourid);
			
			$response = array();
			$response['tour'] = $tour;
			$legs_array = array();
			foreach ($legs as $leg) {
				
				$data = array();
				$depdata = OperationsData::getAirportInfo($leg->depicao);
				$arrdata = OperationsData::getAirportInfo($leg->arricao);
				$data['departure'] = $depdata;
				$data['arrival'] = $arrdata;
				$data['legdata'] = $leg;
				$legs_array[] = $data;
			}
			
			
			$response['legs'] = $legs_array;
			header('Content-Type: application/json');
			echo json_encode($response);
		}
		
		
		public function email() {
			
			$this->set('tour', ICSTourData::getTour('14'));
			$this->set('pilot', Auth::$userinfo);
			
			
			$this->show('ICSTour/emails/notification-toursignup.php');
			
		}
		
		public function participate($tourid = '') {
			if($tourid == '') {
				$this->set('message', 'Tour ID is missing');
				$this->show('core_error.php');
				return;
			}
			$tour = ICSTourData::getTour($tourid);
			$this->set('tour', $tour);
			
			$isParticipating = ICSTourData::isParticipating(Auth::$userinfo->pilotid, $tour->id);
			if($isParticipating == true) {
				$this->set('message', 'You have already signed up for this tour, happy flying');
				$this->show('core_message.php');
				$this->fly($tour->id);
				return;
			} else {
				
				//Signup mechanism
				$participate = ICSTourData::participate(Auth::$userinfo->pilotid, $tour);
				//Send Notification to Pilot 
				$pilot = Auth::$userinfo;
				$this->set('pilot', $pilot);
				
				$email = Template::GetTemplate('ICSTour/emails/notification-toursignup.php', true);
				Util::SendEmail($pilot->email, '[iCrew] '.SITE_NAME.' | You have signed up for '.$tour->title.'', $email);
				
				//Send Notification to Admin on Discord
				if(DISCORD_ENABLE_WEBHOOKS == 1) {
					$discord_notification = '['.$pilot->code.$pilot->pilotid.'] '.$pilot->firstname.' '.$pilot->lastname.' has signed up for the '.$tour->title.'';
					DiscordData::deliver($discord_notification, DISCORD_ADMIN_TEXT_CHANNEL);	
				}
				
				
				$this->set('message', 'Congratulations, you are now successfully signed up for <strong>'.$tour->title.'</strong>! Happy flying');
				$this->show('core_success.php');
				$this->fly($tour->id);
				return;
			}
			
		}
		
		public function fly($tourid = '') {
			
			if($tourid == '') {
				$this->set('message', 'Tour ID is missing');
				$this->show('core_error.php');
				return;
			}
			
			
			$tour = ICSTourData::getTour($tourid);
			
			if(ICSTourData::isEligible(Auth::$userinfo->pilotid, $tour->id)) {
				
			
			
			$this->set('tour', $tour);
			
			$isParticipating = ICSTourData::isParticipating(Auth::$userinfo->pilotid, $tour->id);
			if($isParticipating != true) {
				$this->participate($tourid);
				return;
			}
			
			
			$this->set('current_location', ICSTourData::current_location());
			$this->set('progress', ICSTourData::getTourProgress(Auth::$userinfo->pilotid, $tourid));
			$this->set('tourParticipants', ICSTourData::getTourParticipants($tourid));
			$this->show('ICSTour/fly');
			
			} else {
				
				$this->set('message', 'Whooopsie! You are not eligible to fly this tour. Earn your ranks, we cannot wait to get you started for this tour.');
				$this->show('core_error.php');
				$this->index();
			}
			
		}
		
		public function getaircraftRegistrations_api($icao) {
			$response = array();
			
			if($icao == '') {
				$response = 'Invalid ICAO Code';
			} else {
				$response = ICSTourData::getAircraftbyICAO($icao);	
			}
			header('Content-Type: application/json');
			echo json_encode($response);
		}
		
		
		public function generateAircraftRegistrations($icao) {
			$aircrafts = ICSTourData::getAircraftbyICAO($icao);
			$this->set('aircrafts', $aircrafts);
			$this->render('ICSTour/aircraftselect_api.php');
		}
		
		public function jumpseat_new($from, $to, $tourid) {
		$pilotid = Auth::$userinfo->pilotid;
			//Now, We cannot fake phpvms about the Pilot's location, hence we file a Fake PIREP
			$airlinecode = Auth::$userinfo->code;
			$submit_date = date('d.m.y');
			$accept_date = date('Y-m-d H:i:s');
			$flighttime = $distance / 500;
			$sql = "INSERT INTO `phpvms_pireps` (`pilotid`, `code`, `flightnum`, `depicao`,
			`arricao`, `route`, `route_details`, `aircraft`, `flighttime`, `flighttime_stamp`,
			`distance`, `landingrate`, `submitdate`, `modifieddate`, `accepted`, `log`, `load`,
			`fuelused`, `fuelunitcost`, `fuelprice`, `price`, `flighttype`, `gross`, `pilotpay`,
			`paytype`, `expenses`, `revenue`, `source`, `exported`, `rawdata`)
			VALUES ('$pilotid', '$airlinecode', 'JUMP', '$from', '$to',
			'JUMP SEAT ROUTE',
			'a:0:{}', '0', '$flighttime', '$submit_date', '$distance', '---',
			'$accept_date', '$accept_date', '1', '',
			'0', '0', '0', '0', '0', ' ', '0', '0',
			'1', '0', '0', 'JUMPSEAT TRACKER', '1', '')";
			$result = DB::query($sql);
			
			if($result == true) {
				$thread_id = time();
				$who_to = $pilotid;
				$who_from = ADMIN_BOT_ACCOUNT;
				$subject = 'JUMPSEAT CONFIRMED';
				$new_message = 'Your Jumpseat travel from <strong>'.$from.'</strong> to <strong>'.$to.'</strong> has been confirmed. Your current location should be refreshed in your account soon! 
				<br><br><span class="text-muted">
				<i><small>This e-mail was generated automatically, donot reply to this e-mail.</i><br>Flight Operations | '.SITE_NAME.' </small></span>';
				//Now we are notifying the Pilot about the Jumpseat.
				//MailData::send_new_mail($who_to, $who_from, $subject, $new_message, $notam, $thread_id);

				$name = Auth::$userinfo->firstname.' just flew jumpseat from '.$from.' to '.$to;
				$posted_by = 'Jumpseat Monitor';
				$privacy = '1';
				ICSActs::new_ics_activity($name, $posted_by, $privacy);	
				$this->set('message', 'You are now relocated to '.$to.'. You can continue with your tour! Redirecting you back to the tour page. Happy flying.');
				$this->render('core_success.php');
			} else {
				$this->set('message', 'Unable to fly jumpseat, please try again later and report this to webmaster');
				$this->render('core_error.php');
			}
			
			$link = SITE_URL.'/index.php/ICSTour/fly/'.$tourid;
			?>
			
			<script>
			setTimeout(function() {
				location.replace('<?php echo $link; ?>');
			}, 3000);
			</script>
			<?php
		}
		
		public function currentTours() {
			
		}
		
		public function pastTours() {
			
		}
		
		public function widget() {
			// Randomly Show Tours...
		}
		
		public function generateFlight($tourid, $legid) {
		
		$tour = ICSTourData::getTour($tourid);
		
		// $check = ICSTourData::checkFlightEntry($tourid, Auth::$userinfo->pilotid);
		// if($check != '') {
		// 	// If there are flights existing, delete them from DB, and Bidlist. 
			
		// 	$flightnum_to_delete = str_replace($tour->airline, '', $check->flightnum);
		// 	// Deleting Bids.
		// 	$sch_to_delete = SchedulesData::findSchedules(array('s.code' => $tour->airline, 's.flightnum' => $flightnum_to_delete));
		// 	foreach ($sch_to_delete as $sch_to_delete);
			
		// 	$bidid = SchedulesData::GetBidWithRoute(Auth::$userinfo->pilotid, $tour->airline, $flightnum_to_delete);
  //          SchedulesData::RemoveBid($bidid->bidid);
            
  //          // Deleting the flight from Tours DB.
  //          $id = $check->id;
		// 	$sql = "DELETE FROM `icrewsystems_tour_flights` WHERE `id` = '$id'";
		// 	DB::query($sql);
			
		// 	//Deleting flight from actual DB.
		// 	SchedulesData::deleteSchedule($sch_to_delete->id);
		// }
		
		$aircraft = OperationsData::getAircraftInfo($_POST['aircraft']);
		$acspeed = $aircraft->maxspeed;
		if($acspeed == 0) {
			$acspeed = '250';
        }
        
        $time = ($_POST['distance'] / $acspeed);
		$_POST['flighttime'] = round($time);
		$data = $_POST;
		
		$sch = ICSTourData::addSchedule($data);
		if($sch) {
			$data = (object) $data;
			ICSTourData::makeFlightEntry(Auth::$userinfo->pilotid, $tourid, $legid, $data->code.$data->flightnum, $data->depicao, $data->arricao);	
		} else {
			$this->set('message', 'Something went wrong. Unable to add schedule to the Database. Aborting. Please contact the admins');
			$this->show('core_error.php');
			return;
		}
		
		
		// THIS METHOD IS SPECIAL FOR UPSVAC. REMOVE IT IN OTHER VA's! Check for the next line as well.
		$aircraftid = $data->aircraft;
		if($aircraftid == '') {
			 $this->set('message', 'Oh Snap! Aircraft ID missing.');
    		 $this->show('core_error.php');
    		 return;
		}
		
        // See if this is a valid route
        $route = SchedulesData::findSchedules(array('s.code' => $data->code, 's.flightnum' => $data->flightnum));
			
		foreach ($route as $route) 
		
        if($route == '') {
			 $this->set('message', 'Oh Snap! Schedule was not added. Unable to bid flight.');
    		 $this->show('core_error.php');
    		 return;
		}

		CodonEvent::Dispatch('bid_preadd', 'Schedules', $route->id);

        
        // THIS METHOD IS SPECIAL FOR UPSVAC. REMOVE IT IN OTHER VA's! and use addBid ONLY!!!!!!!!!!!11
        
        $ret = SchedulesData::addBid(Auth::$pilot->pilotid, $route->id);
        CodonEvent::Dispatch('bid_added', 'Schedules', $route->id);
        
        if ($ret == true) {
            $this->set('message', 'Congratulations! Your tour flight '.$route->code.$route->flightnum.' was created and has added to your bid list. To view accurate briefing, please genreate a simbrief briefing package.');
            $this->show('core_success.php');
        } else {
            $this->set('message', 'Hey, you have already bidded this route! Happy Flying!');
            $this->show('core_message.php');
        }
		
		
		
		$new_message = 'Your leg for '.$tour->title.', <strong>'.$data->code.$data->flightnum.'</strong> was generated and was added to your bid list. 
		Please fly this flight and file a PIREP at your earliest convenience.
		<br><br>
		<span class="text-muted">
		<i><small>This e-mail was generated automatically, donot reply to this e-mail.</i>
		<br>Flight Operations | '.SITE_NAME.' </small></span>';
		
		$thread_id = time();
		$who_to = $pilotid;
		$who_from = ADMIN_BOT_ACCOUNT;
		$subject = 'Tour flight ready';
		//Now we are notifying the Pilot about the Jumpseat.
		MailData::send_new_mail($who_to, $who_from, $subject, $new_message, $notam, $thread_id);
		
        $schedule = SchedulesData::getScheduleDetailed($route->id);
        $this->set('schedule', $schedule);
        $this->render('schedule_briefing.php');
		}
		
	
		
		public function tourmap($tourID) {
			$this->set('tourid', $tourID);
			$this->set('legs', ICSTourData::getTourLegs($tourID));
			$this->render('ICSTour/tour_legs_map.php');
		}
	}
	
	