<?php
/**
 * phpVMS - Virtual Airline Administration Software
 * Copyright (c) 2008 Nabeel Shahzad
 * For more information, visit www.phpvms.net
 *	Forums: http://www.phpvms.net/forum
 *	Documentation: http://www.phpvms.net/docs
 *
 * phpVMS is licenced under the following license:
 *   Creative Commons Attribution Non-commercial Share Alike (by-nc-sa)
 *   View license.txt in the root, or visit http://creativecommons.org/licenses/by-nc-sa/3.0/
 *
 * @author Nabeel Shahzad
 * @copyright Copyright (c) 2008, Nabeel Shahzad
 * @link http://www.phpvms.net
 * @license http://creativecommons.org/licenses/by-nc-sa/3.0/
 */

class Schedules extends CodonModule {


	public function flight_map() {
		$this->render('schedule_flights_map.php');
	}

	public function airports_json() {
		$sql = "SELECT * FROM `phpvms_airports` WHERE `hub` = 1";
		header('Content-Type: application/json');
		echo json_encode(DB::get_results($sql));
	}

	public function flights_from_location_api($icao) {
		$data = ICSScheduleMap::flights_from_location($icao, 200);
		header('Content-Type: application/json');
		echo json_encode($data);
	}

	public function current_location_api() {
		$data = ICSScheduleMap::current_location();
		header('Content-Type: application/json');
		echo json_encode($data);
	}

	public function jumpseat_new($from, $to) {
		$pilotid = Auth::$userinfo->pilotid;
		
		
		// Distance BW both the Airports
            	$distance = floor(OperationsData::getAirportDistance($from, $to));

            	//Algorithm for calculating the Money.
            	$operations_cost = JUMPSEAT_OPERATIONS_COST;
            	$jumpseat_cost = ($distance * $operations_cost);

            	//Check if Pilot has that money
            	$account_balance = Auth::$userinfo->totalpay;
        		if($jumpseat_cost > $account_balance) {
        			$this->set('message', 'You donot have sufficient money to purchase a staff flight ticket from your current location.');
        			$this->render('core_error.php');
        			return;
        		} else {
        			//Reduce Money from the Pilot's Account.
	            	$pilotid = Auth::$userinfo->pilotid;
	            	$charges = $account_balance - $jumpseat_cost;
	            	$sql = "UPDATE `".TABLE_PREFIX."pilots` SET `totalpay` = '$charges' WHERE `".TABLE_PREFIX."pilots`.`pilotid` = $pilotid";
					DB::query($sql);
        		}




			//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', '')";
			DB::query($sql);


				$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! '.Config::Get('MONEY_UNIT').''.$jumpseat_cost.' has been deducted from your Pilot Account. '.Config::Get('MONEY_UNIT').''.Auth::$userinfo->totalpay.' is your account balance.<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);
	}

	public function jumpseat_to_hub() {
		$current_location = ICSScheduleMap::current_location();
		$current = $current_location->icao;

		$hub = Auth::$userinfo->hub;
		if($current != $hub) {
			self::jumpseat_new($current, $hub);
			$this->set('message', 'You are now relocated to '.$hub);
			$this->show('core_success.php');
			$this->index();
		} else {
			$this->set('message', 'You are already in your hub');
			$this->show('core_error.php');
			$this->index();
		}

	}
	
	
	public function jumpseat_to_departure() {
		
		$redir = $this->post->redir;
		$current = $this->post->current;
		$dest = $this->post->destination;
		self::jumpseat_new($current, $dest);
		
		header('Location: '.$redir.'');
	}

	public function route_network($icao) {
		if($icao == '') {
			$icao  = Auth::$userinfo->hub;
		}
		$this->set('icao', $icao);
		$this->render('schedule_route_network.php');
	}


     public function VADS() {
        if (!Auth::LoggedIn())
            return;

        $this->set('bids', SchedulesData::GetBids(Auth::$pilot->pilotid));
        $this->render('schedule_flightbrf.tpl');
    }

    public function bidSchedule($routeid) {

    	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])) {
            echo 'Invalid Route';
            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, Looks like you already have a flight on your bid.');
                $this->show('core_error.php');
                return;
            }
        }

        $ret = SchedulesData::AddBid(Auth::$pilot->pilotid, $routeid);
        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 search() {
    	$icao = $this->get->icao;
    	$params = array();
		$params['s.arricao'] = $icao;
		$schedule_list = SchedulesData::findSchedules($params);
		$this->set('allroutes', $schedule_list); #deprecated
		$this->set('schedule_list', $schedule_list);
		$this->set('message', 'Showing schedules for <strong>'.$icao.'</strong> airport, happy exploring!');
		$this->show('core_notification.php');
		$this->render('schedule_results.tpl');
    }

    public function VADS_dispatch($routeid = '') {
        if ($routeid == '') {
            $this->set('message', 'You must be logged in to access this feature!');
            $this->render('core_error.tpl');
            return;
        }

        $schedule = SchedulesData::getScheduleDetailed($routeid);
        $this->set('schedule', $schedule);
        $this->render('schedule_brief_own.tpl');
    }

	public function rosterForm() {
		$this->render('schedules_rosterform.php');
	}
	public function generateRosters()	{
			$dep 		= $this->post->depicao;
			$count 		= $this->post->count;
			$duration  = $this->post->duration;

			$roster = array();
			for ($i = 0; $i < $count; $i++) {
				$schedule = SchedulesData::getSchedulesforRoster($dep);
				if($schedule == '') {
					$dep = $_POST['depicao'];
					$roster[$i] = "no flights";
				} else {
					foreach ($schedule as $s) {
						$dep = $s->arricao;
						$roster[$i] = $s->id;
					}
				}


			}
			$this->set('post', $this->post);
			$this->set('roster', $roster);
			$this->render('schedules_rosters.php');
		}
    /**
     * Schedules::index()
     *
     * @return
     */
    public function index() {
        $this->view();
    }

    /**
     * Schedules::view()
     *
     * @return
     */


    public function view() {
        if (isset($this->post->action) && $this->post->action == 'findflight') {
            $this->FindFlight();
            return;
        }

        $this->showSchedules();
    }
    
    
    /**
     * To check if an airport exists.
     * 
	*/
    public function verify_jumpseat_airport($airport = null) {
    	
		$response = array();
		
		$airport = strtoupper($airport);
		
		header('Content-Type: application/json');
		
		if($airport != null) {
			if(strlen($airport) > 3) {
				$airport_data = OperationsData::getAirportInfo($airport);		
				
				if($airport_data) {
					$response['code'] = '200';
					$response['message'] = 'Able to jumpseat to '. $airport_data->icao.' - '.$airport_data->name;			
					$response['data'] = $airport_data;
				} else {
					$response['code'] = '400';
					$response['message'] = 'Unable to find an airport with ICAO '. $airport . ' in our database';		
				}
				
				
				
			} else {
				$response['code'] = '400';
				$response['message'] = 'Please provide a proper 3 letter ICAO code';		
			}
		} else {
			$response['code'] = '400';
			$response['message'] = 'You have not provided a valid ICAO code';
		}
		
		
		
		
    	echo json_encode($response);
    	return;
    }

    public function jumpseat() {
    	/*Well, Just don't touch this Fam. Experimental Version of Jumpseat Travel.*/
        if ($this->post->submit == 'Get Jumpseat' || $this->post->action == 'Get Jumpseat') {

            $dest = strtoupper($this->post->destination);
            $cur_loc = strtoupper($this->post->currentloc);
            
            
            	// Distance BW both the Airports
            	$distance = floor(OperationsData::getAirportDistance($cur_loc, $dest));

            	//Algorithm for calculating the Money.
            	$operations_cost = JUMPSEAT_OPERATIONS_COST;
            	$jumpseat_cost = ($distance * $operations_cost);

               //$jumpseat_cost = JUMPSEAT_OPERATIONS_COST;
               // To add a live cost, just comment this. Added on 12.06.2018, Leonard.

            	//Check if Pilot has that money
            	$account_balance = Auth::$userinfo->totalpay;

            		if($jumpseat_cost > $account_balance) {
            			$this->set('message', 'You donot have sufficient money to purchase a staff flight ticket from your current location.');
            			$this->render('core_error.php');
            		} else

            		{
            				//Reduce Money from the Pilot's Account.

            	$pilotid = Auth::$userinfo->pilotid;
            	$charges = $account_balance - $jumpseat_cost;
              $charges = $account_balance - $jumpseat_cost;

            	$sql = "UPDATE `".TABLE_PREFIX."pilots` SET `totalpay` = '$charges' WHERE `".TABLE_PREFIX."pilots`.`pilotid` = $pilotid";
				DB::query($sql);


				//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', '$cur_loc', '$dest',
				'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', '')";
				DB::query($sql);


				$thread_id = time();
				$who_to = $pilotid;
				$who_from = ADMIN_BOT_ACCOUNT;
				$subject = 'JUMPSEAT CONFIRMED';
				$new_message = 'Your Jumpseat travel from <strong>'.$cur_loc.'</strong> to <strong>'.$dest.'</strong> has been executed. Your current location has been updated to '.$cur_loc.' & you will now be able to access
				all flights from this station. Happy flying!
				<br><br><span class="text-muted">
				<i><small>This iMail was generated automatically, donot reply to this iMail.</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);
				$newmessage = 'You were successfully re-located to '.$dest.' from '.$cur_loc.', your current location will be updated soon! '. Config::get('MONEY_UNIT') . $jumpseat_cost .' will be auto-debited from your account. Happy flying!';
				$this->set('message', $newmessage);
				$this->render('core_success.php');

				$name = Auth::$userinfo->firstname.' just flew jumpseat from '.$cur_loc.' to '.$dest;
				$posted_by = 'Jumpseat Monitor';
				$privacy = '1';
				ICSActs::new_ics_activity($name, $posted_by, $privacy);
        	}
         }
		$this->showSchedules();
    }

    /**
     * Schedules::detail()
     *
     * @param string $routeid
     * @return
     */
    public function detail($routeid = '') {
        $this->details($routeid);
    }

    /**
     * Schedules::details()
     *
     * @param string $routeid
     * @return
     */
    public function details($routeid = '') {
        //$routeid = $this->get->id;

        if (!is_numeric($routeid)) {
            preg_match('/^([A-Za-z]{3})(\d*)/', $routeid, $matches);
            $code = $matches[1];
            $flightnum = $matches[2];

            $params = array('s.code' => $code, 's.flightnum' => $flightnum);
        } else {
            $params = array('s.id' => $routeid);
        }

        $schedule = SchedulesData::getScheduleDetailed($routeid);
        $this->set('schedule', $schedule);
        $this->render('schedule_details.tpl');
        $this->render('route_map.tpl');
    }

    /**
     * Schedules::brief()
     *
     * @param string $routeid
     * @return
     */
    public function brief($routeid = '') {
        if ($routeid == '') {
            $this->set('message', 'You must be logged in to access this feature!');
            $this->render('core_error.tpl');
            return;
        }

        $schedule = SchedulesData::getScheduleDetailed($routeid);
        $this->set('schedule', $schedule);
        $this->render('schedule_briefing.tpl');
    }

    /**
     * Schedules::boardingpass()
     *
     * @param mixed $routeid
     * @return
     */
    public function boardingpass($routeid) {
        if ($routeid == '') {
            $this->set('message', 'You must be logged in to access this feature!');
            $this->render('core_error.tpl');
            return;
        }

        $schedule = SchedulesData::getScheduleDetailed($routeid);

        $this->set('schedule', $schedule);
        $this->render('schedule_boarding_pass.tpl');
    }

    /**
     * Schedules::bids()
     *
     * @return
     */
    public function bids() {
        if (!Auth::LoggedIn())
            return;

        $this->set('bids', SchedulesData::GetBids(Auth::$pilot->pilotid));
        $this->render('schedule_bids.tpl');
    }

    /**
     * Schedules::addbid()
     *
     * @return
     */
    public function addbid() {
        if (!Auth::LoggedIn())
            return;

        $routeid = $this->get->id;

        if ($routeid == '') {
            echo 'No route passed';
            return;
        }

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

        if (!is_array($route) && !isset($route[0])) {
            echo 'Invalid Route';
            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) {
                echo 'Bid exists!';
                return;
            }
        }

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

        if ($ret == true) {
            echo 'Bid added';
        } else {
            echo 'Already in bids!';
        }
    }

    /**
     * Schedules::removebid()
     *
     * @return
     */
    public function removebid() {
        if (!Auth::LoggedIn())
            return;

        SchedulesData::RemoveBid($this->post->id);
    }

    /**
     * Schedules::showSchedules()
     *
     * @return
     */
    public function showSchedules() {

        $depapts = OperationsData::GetAllAirports();
        $equip = OperationsData::GetAllAircraftSearchList(true);
        $airlines = OperationsData::GetAllAirlines();

        $this->set('airlines', $airlines); #deprecated
        $this->set('airline_list', $airlines);

        $this->set('depairports', $depapts);

        $this->set('equipment', $equip); # deprecated
        $this->set('aircraft_list', $equip);

        $this->render('schedule_searchform.tpl');

    }

    /**
     * Schedules::findFlight()
     *
     * @return
     */
    public function findFlight() {

		$last_flight = PIREPData::getLastReports(Auth::$userinfo->pilotid, 1, PIREP_ACCEPTED);
		if(!$last_flight) {
        	$current_location = Auth::$userinfo->hub;
            	} else {
            		$current_location = $last_flight->arricao;
    	}

        $params = array();
        if($this->post->airlines != '') {
            $params['s.code'] = $this->post->airlines;
        }

       $params['s.depicao'] = $current_location;

        if ($this->post->arricao != '') {
            $params['s.arricao'] = $this->post->arricao;
        }

				if ($this->post->type != '') {
            $params['s.flighttype'] = $this->post->type;
        }

        if ($this->post->equipment != '') {
            $params['a.name'] = $this->post->equipment;
        }

        if ($this->post->distance != '') {
            if ($this->post->type == 'greater')
                $value = '> ';
            else
                $value = '< ';

            $value .= $this->post->distance;

            $params['s.distance'] = $value;
        }

        $params['s.enabled'] = 1;

        $schedule_list = SchedulesData::findSchedules($params);
        $this->set('allroutes', $schedule_list); #deprecated
        $this->set('schedule_list', $schedule_list);

        $this->render('schedule_results.tpl');
    }

    /**
     * Schedules::statsdaysdata()
     *
     * @param mixed $routeid
     * @return
     */
    public function statsdaysdata($routeid) {

        $schedule = SchedulesData::findSchedules(array('s.id' => $routeid));
        $schedule = $schedule[0];

        // Last 30 days stats
        $data = PIREPData::getIntervalDataByDays(array(
            'p.code' => $schedule->code,
            'p.flightnum' => $schedule->flightnum,
            ), 30);

        $this->create_line_graph('Schedule Flown Counts', $data);
    }

    /**
     * Schedules::create_line_graph()
     *
     * @param mixed $title
     * @param mixed $data
     * @return
     */
    protected function create_line_graph($title, $data) {

        if (!$data) {
            $data = array();
        }

        $titles = array();
        $bar_titles = array();
        foreach ($data as $val) {
            $titles[] = $val->ym;
            $values[] = floatval($val->total);
        }

        OFCharts::add_data_set($titles, $values);
        echo OFCharts::create_line_graph($title);
    }
}
