<?php
	class ICSFleet extends CodonModule {

	public function __construct() {
		CodonEvent::addListener('ICSFleet', 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 WHERE 'flightnum' != 'JUMP' ORDER BY pirepid DESC LIMIT 1");
			$id = $pirep->aircraft;
			$sql = "SELECT * FROM `phpvms_aircraft` WHERE `id` = '$id'";
			$ret = DB::get_row($sql);
			$airplane_location = $ret->location;
			$ac_current_location = $pirep->arricao;
			if($ac_current_location == '') {
				$ac_current_location = 'XXXX';
			}
			$id = $pirep->aircraft;
			$sql = "UPDATE `phpvms_aircraft` SET `location` = '$ac_current_location' WHERE `id` = '$id'";
			DB::query($sql);
			// DiscordData::deliver('(ICSFleet) Flight: '.$pirep->code.$pirep->flightnum.', PIREPID: '.$pirep->pirepid.', Aircraft ('.$ret->registration.') location as been successfully updated from `'.$airplane_location.'` to `'.$ac_current_location.'`');
		}
	}


		public function index() {
			$header_fleet = ICSFleetData::getAllFleetGrouped_rand(1);
			$fleet = ICSFleetData::getAllFleetGrouped(1);
			$this->set('fleet', $fleet);
			$this->set('header_fleet', $header_fleet);
			$this->show('ICSFleet/index');
		}

		public function view($icao) {
			$fleet = ICSFleetData::getACbyICAO($icao);
			$this->set('fleet', $fleet);
			$this->set('icao', $icao);
			$this->show('ICSFleet/view_icao');
		}

		public function update_locations() {
			ICSFleetData::update_fleet_locations();
			echo "Fleet locations updated.";
		}

		public function upload_screenshots($registration) {


			$this->set('registration', $registration);
			$this->render('ICSFleet/fleet_screenshot.php');
		}

		public function process_screenshot() {


			if ((($_FILES["uploadedfile"]["type"] == "image/x-png")
            || ($_FILES["uploadedfile"]["type"] == "image/jpeg")
            || ($_FILES["uploadedfile"]["type"] == "image/png")
            || ($_FILES["uploadedfile"]["type"] == "image/bmp")
            || ($_FILES["uploadedfile"]["type"] == "image/pjpeg")
            || ($_FILES["uploadedfile"]["type"] == "image/gif"))
            && ($_FILES["uploadedfile"]["size"] < 2000000))
        {

            if ($_FILES["file"]["error"] > 0) {
                echo "Error: " . $_FILES["file"]["error"] . "<br />";
            }
            $target_path = "pics/";

            $_FILES['uploadedfile']['name'] = time().'_'.$_FILES['uploadedfile']['name'];

            $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

            if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
              $this->set('message', 'The file '.  basename( $_FILES['uploadedfile']['name']).' has been uploaded - An Administrator will approve the screenshot prior to it being available in the gallery.');
              $this->render('core_success.php');


                $file_name = $_FILES['uploadedfile']['name'];
                $pilot_id = Auth::$userinfo->pilotid;
                $description = DB::escape($this->post->description);
                $registration = DB::escape($this->post->registration);
                $description = "[".$registration."] ".$description;


                if (!$description)
                    {$description = 'No Description Provided';}
                $query = "INSERT INTO ".TABLE_PREFIX."screenshots (file_name, file_description, pilot_id, date_uploaded, file_approved)
                VALUES ('$file_name', '$description', '$pilot_id', NOW(), 0)";

                DB::query($query);
            } else {
              $this->set('message', 'There was an error uploading the file, please try again!');
              $this->render('core_error.php');
            }

        }
        else {
          $this->set('message', 'That sucks! Your upload is not a jpg or gif file, or may be too big!');
          $this->render('core_error.php');
          $this->index();
          return;
        }

        $this->view_aircraft($registration);

		}

		public function _map_generate($icao) {
			$fleet = ICSFleetData::getACbyICAO($icao);
			$this->set('fleet', $fleet);
			$this->set('icao', $icao);
			$this->show('ICSFleet/view_icao_map.php');
		}

		public function view_aircraft($registration) {
			$sql = "SELECT * FROM `phpvms_screenshots` WHERE `file_description` LIKE '%[$registration]%'";
			$result = DB::get_results($sql);

			$this->set('screenshots', $result);
			$this->set('registration', $registration);
			$this->set('aircraft', ICSFleetData::getACbyREG($registration));
			$this->show('ICSFleet/view_aircrafts');
		}

		public function maintenance() {

		}

		public function view_flights($registration) {

		$params = array();
		$params['a.registration'] = $registration;
        $params['s.enabled'] = 1;
        $schedule_list = SchedulesData::findSchedules($params);
        $this->set('registration', $registration);
        $this->set('allroutes', $schedule_list);
        $this->render('ICSFleet/view_flights.php');
		}

		public function relief_flight($id) {

			$this->set('icao', 'REP');
			$this->set('id', $id);
			$this->set('last_flight', ICSFleetData::get_last_flight($id));
        	$this->set('allairlines', OperationsData::GetAllAirlines());
        	$this->set('aircraft', ICSFleetData::getACbyID($id));
			$this->set('hubs', OperationsData::getAllHubs());
			$this->set('flighttypes', Config::Get('FLIGHT_TYPES'));
			$this->render('ICSFleet/releif_flight.php');
		}

		public function bidflight($string){
			$vars = explode("_",$string);
			$routeid = $vars[0];
			$aircraftid = $vars[1];
			if (!Auth::LoggedIn()) {
				$this->set('message', 'Oh boy, you\'ll need access for that!');
				$this->show('core_error.php');
				$this->render('login_form.php');
				return;
			}

			if ($routeid == '') {
				$this->set('message', 'Oh Snap! Something went wrong. There were some numbers missing, please try again.');
				$this->show('core_error.php');
				$this->view();
				return;
			}

			// See if this is a valid route
			$route = SchedulesData::findSchedules(array('s.id' => $routeid));

			if (!is_array($route) && !isset($route[0])) {
				$this->set('message', 'Invalid Route! The route selected was invalid, please try again.');
				$this->show('core_error.php');
				$this->view();
				return;
			}

			$aircraft = ICSFleetData::getACbyID($aircraftid);

			if (!isset($aircraft) || $aircraft=='') {
				$this->set('message', 'Invalid Aircraft! The aircraft selected was invalid, please try again.');
				$this->show('core_error.php');
				$this->view();
				return;
			}

			if(Auth::$pilot->rankid < $aircraft->minrank)
			{
				$this->set('message', 'Reserved Aircraft! The aircraft selected is reserved for staff. Please select a different aircraft!');
				$this->show('core_error.php');
				$this->view();
				return;
			}

			CodonEvent::Dispatch('bid_preadd', 'Schedules', $routeid);

			/* Block any other bids if they've already made a bid
			*/
			if (Config::Get('DISABLE_BIDS_ON_BID') == true) {
				$bids = SchedulesData::getBids(Auth::$pilot->pilotid);

				# They've got somethin goin on
				if (count($bids) > 0) {
					$this->set('message', 'Hey, this bid already exists!');
					$this->show('core_error.php');
					return;
				}
			}

			$ret = SchedulesData::addBid_ac(Auth::$pilot->pilotid, $routeid,$aircraft->id);
			CodonEvent::Dispatch('bid_added', 'Schedules', $routeid);

			if ($ret == true) {
				$this->set('message', 'Congratulations! Bid has been added. Briefing has been loaded.');
				$this->show('core_success.php');
			} else {
				$this->set('message', 'Hey, you have already bidded this route! Happy Flying!');
				$this->show('core_error.php');
			}

			$schedule = SchedulesData::getScheduleDetailed($routeid);
			$this->set('schedule', $schedule);
			$this->render('schedule_briefing.php');
		}
		public function process_relief_flight() {



			$post = $this->post;
    		$data = array();
    		$data['code'] = $post->code;
    		$data['flightnum'] = $post->flightnum;
    		$data['depicao'] = $post->depicao;
    		$data['arricao'] = $post->arricao;

    		if($post->route == '') {
				$data['route'] = "DCT";
    		} else {
    			$data['route'] = $post->route;
    		}


    		$data['distance'] = OperationsData::getAirportDistance($this->post->depicao, $this->post->arricao);
    		$data['flightlevel'] = $post->flightlevel;
    		$data['aircraft'] = $post->aircraft;
    		$data['deptime'] = $post->deptime;
    		$data['arrtime'] = $post->arrtime;
    		$data['flighttime'] = $post->flighttime;
    		$data['notes'] = $post->notes;
    		$data['enabled'] = 1;
    		$data['price'] = '10000';
    		$data['payforflight'] = '10000';


			$addSch = SchedulesData::addSchedule($data);
			if($addSch == true) {


				// Add bid
				$code = $data['code'];
				$flightnum = $data['flightnum'];

				$sql = "SELECT `id` FROM `phpvms_schedules` WHERE `code` = '$code' AND `flightnum` = '$flightnum'";
				$result = DB::get_row($sql);

				$route_id = $result->id;
				$aircraftid = $post->aircraft;
				// THIS METHOD IS SPECIAL FOR UPSVAC. REMOVE IT IN OTHER VA's!
				if($aircraftid == '') {
					 $this->set('message', 'Oh Snap! Aircraft ID missing.');
					 $this->show('core_error.php');
					 return;
				}

				$bid = SchedulesData::addBid_ac(Auth::$pilot->pilotid, $route_id, $aircraftid);
				$this->set('message', 'Relief Schedule '.$data['code'].$data['flightnum'].' was added. A bid was placed for you. Happy flying!');
				$this->render('core_success.php');


				// Send Notifications.
				$fleet = ICSFleetData::getACbyID($post->aircraft);
				$message = Template::getTemplate('ICSFleet/email_repositioning.php', true, true);
				$aicraft_name = $fleet->registration.' - '.$fleet->fullname;
				$message = str_replace('{PILOT_NAME}', Auth::DisplayName(), $message);
				$message = str_replace('{DEPICAO}', $data['depicao'], $message);
				$message = str_replace('{ARRICAO}', $data['arricao'], $message);
				$message = str_replace('{AICRAFT}', $aicraft_name, $message);
				$message = str_replace('{FLIGHTNUM}', $data['flightnum'], $message);
				$message = str_replace('{PRICE}', $data['payforflight'], $message);

				MailData::send_new_mail(Auth::$userinfo->pilotid, 2, "$fleet->registration | Repositioning Confirmation", $message, 0, time());
				$depicao = $data['depicao'];
				$arricao = $data['arricao'];
				$discord_message = "@everyone [NEW REPOSITIONING CLEARANCE] Aircraft Repositioning clearance has been issued to ".Auth::$userinfo->code.Auth::$userinfo->pilotid." ".Auth::DisplayName()."
				to reposition $aircraft_name from $depicao to $arricao. ".SITE_NAME." HQ commends their action. ";
				DiscordData::deliver($discord_message, JUMPCREW_WEBHOOK);



				$schedule = SchedulesData::getScheduleDetailed($route_id);
				$this->set('schedule', $schedule);
				$this->render('schedule_briefing.php');
			} else {
				$this->set('message', 'Was unable to add '.$data['code'].$data['flightnum'].', please try again');
				$this->render('core_error.php');
				$this->index();
			}


		}
	}

