<?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 PIREPAdmin extends CodonModule {
    public function HTMLHead() {
        switch ($this->controller->function) {
            case 'viewpending':
            case 'viewrecent':
            case 'viewall':
                $this->set('sidebar', 'sidebar_pirep_pending.php');
                break;
        }
    }

    public function index() {
        $this->viewpending();
    }

    protected function post_action() {
        if (isset($this->post->action)) {
            switch ($this->post->action) {
                case 'addcomment':
                    $this->add_comment_post();
                    break;

                case 'approvepirep':
                    $this->approve_pirep_post();
                    break;

                case 'deletepirep':

                    $this->delete_pirep_post();
                    break;

                case 'rejectpirep':
                    $this->reject_pirep_post();
                    break;

                case 'editpirep':
                    $this->edit_pirep_post();
                    break;
            }
        }
    }

    public function viewpending() {
        $this->checkPermission(MODERATE_PIREPS);
        $this->post_action();



        if (isset($this->get->hub) && $this->get->hub != '') {
            $params = array('p.accepted' => PIREP_PENDING, 'u.hub' => $this->get->hub, );
            $pireps = PIREPData::findPIREPS($params);
        } else {
            $params = array('p.accepted' => PIREP_PENDING, 'p.accepted' => PIREP_INPROGRESS);
        	$pireps = PIREPData::findPIREPS($params);
        }

        $this->set('pireps', $pireps);
        $this->set('pending', true);
        $this->set('load', 'viewpending');
        $this->render('pireps_list.php');
    }


    public function pilotpireps() {
        $this->checkPermission(MODERATE_PIREPS);
        $this->post_action();

        $this->set('pending', false);
        $this->set('load', 'pilotpireps');

        $this->set('pireps', PIREPData::findPIREPS(array('p.pilotid' => $this->get->pilotid)));
        $this->render('pireps_list.php');
    }


    public function rejectpirep() {
        $this->checkPermission(MODERATE_PIREPS);
        $this->set('pirepid', $this->get->pirepid);
        $this->render('pirep_reject.php');
    }

    public function viewrecent() {
        $this->checkPermission(MODERATE_PIREPS);
        $this->set('title', Lang::gs('pireps.view.recent'));
        $this->set('pireps', PIREPData::GetRecentReports());
        $this->set('descrip', 'These pilot reports are from the past 48 hours');

        $this->set('pending', false);
        $this->set('load', 'viewrecent');

        $this->render('pireps_list.php');
    }

    public function approveall() {
        $this->checkPermission(MODERATE_PIREPS);

        echo '<h3>Approve All</h3>';

        $allpireps = PIREPData::findPIREPS(array('p.accepted' => PIREP_PENDING));

        $total = count($allpireps);
        $count = 0;
        foreach ($allpireps as $pirep_details) {

            if ($pirep_details->aircraft == '') {
                continue;
            }

            # Update pilot stats
            SchedulesData::IncrementFlownCount($pirep_details->code, $pirep_details->flightnum);
            PIREPData::ChangePIREPStatus($pirep_details->pirepid, PIREP_ACCEPTED); // 1 is accepted
            #PilotData::UpdatePilotStats($pirep_details->pilotid);

            #RanksData::CalculateUpdatePilotRank($pirep_details->pilotid);
            RanksData::CalculatePilotRanks();
            #PilotData::GenerateSignature($pirep_details->pilotid);
            #StatsData::UpdateTotalHours();
            CodonEvent::Dispatch('pirep_accepted', 'PIREPAdmin', $pirep_details);

            $count++;
        }

        $skipped = $total - $count;
        echo "$count of $total were approved ({$skipped} has errors)";
    }

	public function autoevaluate() {
        $this->checkPermission(MODERATE_PIREPS);


		$time = '[' . date("h:i:s A") . ']';
		function log_entry($log_msg) {

    	$log_filename = "PIREPBot_logs/";
    	if (!file_exists($log_filename)) {
	        // create directory/folder uploads.
        	mkdir($log_filename, 0777, true);
    	}
    	$log_file_data = $log_filename . '/' . date('d_M_Y') . '.log';
    	file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
		}


        echo '<h3>Auto Evaluate PIREPs &copy; icrewsystems</h3>';

        $allpireps = PIREPData::findPIREPS(array('p.accepted' => PIREP_PENDING));

        $total = count($allpireps);
        $count = 0;
        foreach ($allpireps as $pirep_details) {
        	$landingrate = $pirep_details->landingrate;

            if ($pirep_details->aircraft == '') {
                continue;
            }

            /*	This is the intresting part, I've added custom code
            	so that the PIREP Bot can auto matically evaluate the
            	PIREPs. The good thing is, We would'nt have to wait for
            	an Admin to manually process these PIREPs one by one, it
            	can all be done at a click of a button.

            	-> For Manual PIREPs, Log hours are added, No Money is credited. An iMail is automatically sent.
            	-> For PIREPs with excessive Landing Rates, PIREP is marked as rejected. iMail is dispatched.
            	-> For PIREPs with smooth landing rate, An award is automatically added
            	-> For the Pilot's first flight, an award is auto added.

            	All the default values for these operations can be defined below. PLease be very carefull about what you edit
            	here. This is a payware script specific ONLY to your VA.

            	- Leonard,
            	Lead Tech Devloper,
            	iCrewSystems Ltd.

           	*/

			//Default Values for AUTO EVALUATION :
				// 1 = YES, 0 = NO :)

				//Here, set the ID of the Award you want to alot for the Pilot for his first PIREP.


			//Function for checking if it's the Pilot's first ever flight.
			$landingrate_limit = LANDING_RATE_LIMIT;
			$landingrate_award = $pirep_details->landingrate * -1;
			$pilotdata = PilotData::getPilotData($pirep_details->pilotid);

			 if($pirep_details->landingrate < $landingrate_limit)
			{
				$recommendation = "<font color='#ff0000'><b>REJECT</b></font>";
				$reason = 'Excessive Landing Rate';
				$who_to = $pirep_details->pilotid;
				$who_from = 1;
				$subject = 'PIREP #'.$pirep_details->pirepid.' was Rejected | PIREP Bot';
				$newmessage = 'We are sad to inform you that your PIREP #'.$pirep_details->pirepid.' was rejected due to <strong>Excessive Landing Rate<strong> ('.$pirep_details->landingrate .'). Our margin on the PIREP rate is '.LANDING_RATE_LIMIT.'
				. Please file a manual PIREP.<br><br><br><small><i><span class="text-muted">This was an auto generated email. If you think there was a mistake, contact an admin.</span></i></small>';
				$notam = 0;
				$thread_id = time();
				MailData::send_new_mail($who_to, $who_from, $subject, $newmessage, $notam, $thread_id);

				 $discord_message = '@everyone [PIREPBot] Rejected PIREP #'.$pirep_details->pirepid.' ('.$pirep_details->depicao.' - '.$pirep_details->arricao.') by '.$pilotdata->firstname.' '.$pilotdata->lastname.' due to '.$reason.'';
				 DiscordData::deliver($discord_message);
				//Rejecting the PIREP
				 PIREPData::ChangePIREPStatus($pirep_details->pirepid, PIREP_REJECTED);
				 LogData::addLog(1, 'Rejected PIREP #'.$pirep_details->pirepid.' due to '.$reason.'');
				 $final_report .= '\nRejected PIREP #'.$pirep_details->pirepid.' due to '.$reason.'';

			}
			elseif($landingrate_award < SMOOTH_LANDING_LIMIT)
			{
				$recommendation = 'ADD AWARD';
				$reason = 'Smooth Landing';

				$who_to = $pirep_details->pilotid;
				$who_from = 1;
				$subject = 'You were Awarded for PIREP #'.$pirep_details->pirepid.' | PIREP Bot';
				/*$newmessage = 'We are happy to inform you that your first PIREP, #'.$pirep_details->pirepid.' was evaluated and an award was issued. This was for your encouragement. All the best for all your upcoming flights.
				<br><br><br><small><i>This was an auto generated email.</i></small>';
				*/
				$newmessage = 'That was some amazing landing on '.$pirep_details->submitdate.' you landed as smooth as silk, '.$pirep_details->landingrate.' to be exact. PIREP #'.$pirep_details->pirepid.' was evaluated and an award was issued for your smooth landing. All the best for all your upcoming flights.
				<br><br><br><small><i>This was an auto generated email. If you think this was a mistake, contact an admin.</i></small>';

				$notam = 0;
				$thread_id = time();
				$discord_message = '@everyone [PIREPBot] PIREP #'.$pirep_details->pirepid.' ('.$pirep_details->depicao.' - '.$pirep_details->arricao.') and awarded for to '.$reason.'';
				DiscordData::deliver($discord_message);
				MailData::send_new_mail($who_to, $who_from, $subject, $newmessage, $notam, $thread_id);

				//Accepting the PIREP
				 PIREPData::ChangePIREPStatus($pirep_details->pirepid, PIREP_ACCEPTED);
				 LogData::addLog(786, 'Accepted PIREP #'.$pirep_details->pirepid.' and awarded for to '.$reason.'');

				//Now, the hard stuff...
				//Issuing an award.
				$grt_pilotid = $pirep_details->pilotid;
				$grt_awdid = SMOOTH_LANDING_AWARD_ID;
				if (AWARD_SMOOTH_LANDINGS == 1) {
					vAwardsData::IssueAwardToPilot($grt_pilotid, $grt_awdid);
					$final_report .= '\nAccepted PIREP #'.$pirep_details->pirepid.' and awarded for to '.$reason.'';
				}
				 $count++;
			}

			else if($pilotdata->lastpirep == '0000-00-00 00:00:00') {
				$recommendation = 'ADD AWARD';
				$reason = 'Smooth Landing';

				$who_to = $pirep_details->pilotid;
				$who_from = 1;
				$subject = 'You were Awarded for PIREP #'.$pirep_details->pirepid.' | PIREP Bot';
				$newmessage = 'We are happy to inform you that your first PIREP, #'.$pirep_details->pirepid.' was evaluated and an award was issued. This was for your encouragement. All the best for all your upcoming flights.
				<br><br><br><small><i><span class="text-muted">This was an auto generated email.</span></i></small>';

				$notam = 0;
				$thread_id = time();
				MailData::send_new_mail($who_to, $who_from, $subject, $newmessage, $notam, $thread_id);
				$discord_message = '@everyone [PIREPBot] PIREP #'.$pirep_details->pirepid.' ('.$pirep_details->depicao.' - '.$pirep_details->arricao.') and awarded for to '.$reason.'';
				DiscordData::deliver($discord_message);
				//Accepting the PIREP
				 PIREPData::ChangePIREPStatus($pirep_details->pirepid, PIREP_ACCEPTED);
				 LogData::addLog(786, 'Accepted PIREP #'.$pirep_details->pirepid.' and awarded for to '.$reason.'');

				//Now, the hard stuff...
				//Issuing an award.
				$grt_pilotid = $pirep_details->pilotid;
				$grt_awdid = FIRST_PIREP_AWARD_ID;
				vAwardsData::IssueAwardToPilot($grt_pilotid, $grt_awdid);
				 $count++;
				 $final_report .= '\n Accepted PIREP #'.$pirep_details->pirepid.' and awarded for to '.$reason.'';
			}

				else
			{

				$recommendation = 'ACCEPT';
				$reason = 'No Voilations found';
				$discord_message = '@everyone [PIREPBot] PIREP #'.$pirep_details->pirepid.' ('.$pirep_details->depicao.' - '.$pirep_details->arricao.') was accepted.';
				DiscordData::deliver($discord_message);
			# Update pilot stats
            SchedulesData::IncrementFlownCount($pirep_details->code, $pirep_details->flightnum);
            PIREPData::ChangePIREPStatus($pirep_details->pirepid, PIREP_ACCEPTED); // 1 is accepted
            #PilotData::UpdatePilotStats($pirep_details->pilotid);

            #RanksData::CalculateUpdatePilotRank($pirep_details->pilotid);
            RanksData::CalculatePilotRanks();
            #PilotData::GenerateSignature($pirep_details->pilotid);
            #StatsData::UpdateTotalHours();
            CodonEvent::Dispatch('pirep_accepted', 'PIREPAdmin', $pirep_details);

            $count++;

			}


      $sched = SchedulesData::getScheduleByFlight($pirep_details->code, $pirep_details->flightnum);

      if($sched != '') {
        $time_log = "[".date('h:i:s')."] ";
        $alert = $time_log."[PIREPAdmin.php] called from autoevaluate() function. Line 316, Flight => ".$pirep_details->code."".$pirep_details->flightnum." returned `SUCCESS` (schedule exists on the database at this point). Schedule ID => ".$sched->id."" ;
        DiscordData::deliver($alert, ICS_TEST);
      } else {
        $time_log = "[".date('h:i:s')."] ";
        $alert = $time_log."[PIREPAdmin.php] called from autoevaluate() function. Line 320, Flight => ".$pirep_details->code."".$pirep_details->flightnum." returned `FAILURE` (schedule does not exists on the database at this point)." ;
        DiscordData::deliver($alert, ICS_TEST);
      }



        }

        $skipped = $total - $count;
        echo "PirepBot Report : $count of $total were evaluated successfully. ({$skipped} has errors)";

        echo $final_report;
    }
    public function viewall() {
        $this->checkPermission(MODERATE_PIREPS);
        $this->post_action();

        if (!isset($this->get->start) || $this->get->start == '')
            $this->get->start = 0;

        $num_per_page = 20;
        $this->set('title', 'PIREPs List');

        $params = array();
        if ($this->get->action == 'filter') {
            $this->set('title', 'Filtered PIREPs');

            if ($this->get->type == 'code') {
                $params = array('p.code' => $this->get->query);
            } elseif ($this->get->type == 'flightnum') {
                $params = array('p.flightnum' => $this->get->query);
            } elseif ($this->get->type == 'pilotid') {
                $params = array('p.pilotid' => $this->get->query);
            } elseif ($this->get->type == 'depapt') {
                $params = array('p.depicao' => $this->get->query);
            } elseif ($this->get->type == 'arrapt') {
                $params = array('p.arricao' => $this->get->query);
            }
        }

        if (isset($this->get->accepted) && $this->get->accepted != 'all') {
            $params['p.accepted'] = $this->get->accepted;
        }

        $allreports = PIREPData::findPIREPS($params, $num_per_page, $this->get->start);

        if (count($allreports) >= $num_per_page) {
            $this->set('paginate', true);
            $this->set('admin', 'viewall');
            $this->set('start', $this->get->start + 20);
        }

        $this->set('pending', false);
        $this->set('load', 'viewall');

        $this->set('pireps', $allreports);

        $this->render('pireps_list.php');
    }

    public function editpirep() {
        $this->checkPermission(MODERATE_PIREPS);
        $this->set('pirep', PIREPData::GetReportDetails($this->get->pirepid));
        $this->set('allairlines', OperationsData::GetAllAirlines());
        $this->set('allairports', OperationsData::GetAllAirports());
        $this->set('allaircraft', OperationsData::GetAllAircraft());
        $this->set('fielddata', PIREPData::GetFieldData($this->get->pirepid));
        $this->set('pirepfields', PIREPData::GetAllFields());
        $this->set('comments', PIREPData::GetComments($this->get->pirepid));

        $this->render('pirep_edit.php');
    }

    public function viewcomments() {
        $this->checkPermission(MODERATE_PIREPS);

        $this->set('comments', PIREPData::GetComments($this->get->pirepid));
        $this->render('pireps_comments.php');
    }

    public function deletecomment() {
        $this->checkPermission(MODERATE_PIREPS);

        if (!isset($this->post)) {
            return;
        }

        PIREPData::deleteComment($this->post->id);

        LogData::addLog(Auth::$userinfo->pilotid, 'Deleted a comment');

        $this->set('message', 'Comment deleted!');
        $this->render('core_success.php');
    }

    public function viewlog() {
        $this->checkPermission(MODERATE_PIREPS);

        $this->set('report', PIREPData::GetReportDetails($this->get->pirepid));
        $this->render('pirep_log.php');
    }

    public function addcomment() {
        $this->checkPermission(MODERATE_PIREPS);

        if (isset($this->post->submit)) {
            $this->add_comment_post();

            $this->set('message', 'Comment added to PIREP!');
            $this->render('core_success.php');
            return;
        }


        $this->set('pirepid', $this->get->pirepid);
        $this->render('pirep_addcomment.php');
    }

    /* Utility functions */

    protected function add_comment_post() {
        $this->checkPermission(MODERATE_PIREPS);

        $comment = $this->post->comment;
        $commenter = Auth::$userinfo->pilotid;
        $pirepid = $this->post->pirepid;

        $pirep_details = PIREPData::GetReportDetails($pirepid);

        PIREPData::AddComment($pirepid, $commenter, $comment);

        // Send them an email
        $this->set('firstname', $pirep_details->firstname);
        $this->set('lastname', $pirep_details->lastname);
        $this->set('pirepid', $pirepid);

        $message = Template::GetTemplate('email_commentadded.php', true);
        Util::SendEmail($pirep_details->email, 'Comment Added', $message);

        LogData::addLog(Auth::$userinfo->pilotid, 'Added a comment to PIREP #' . $pirepid);
    }

    public function approvepirep($pirepid) {
        $this->checkPermission(MODERATE_PIREPS);
        $this->post->id = $pirepid;
        $this->approve_pirep_post();

        $this->render('pirepadmin_approved.php');
    }

    /**
     * Approve the PIREP, and then update
     * the pilot's data
     */
    protected function approve_pirep_post() {

        $pirepid = $this->post->id;

        if ($pirepid == '')
            return;

        $pirep_details = PIREPData::getReportDetails($pirepid);

        $this->set('pirep', $pirep_details);

        # See if it's already been accepted
        if (intval($pirep_details->accepted) == PIREP_ACCEPTED)
            return;

        # Update pilot stats

        PIREPData::ChangePIREPStatus($pirepid, PIREP_ACCEPTED); // 1 is accepted
        LogData::addLog(Auth::$userinfo->pilotid, 'Approved PIREP #' . $pirepid);

        # Call the event
        CodonEvent::Dispatch('pirep_accepted', 'PIREPAdmin', $pirep_details);
    }

    /**
     * Delete a PIREP
     */

    protected function delete_pirep_post() {
        $pirepid = $this->post->id;
        if ($pirepid == '')
            return;

        # Call the event
        CodonEvent::Dispatch('pirep_deleted', 'PIREPAdmin', $pirepid);

        PIREPData::deleteFlightReport($pirepid);
        StatsData::UpdateTotalHours();
    }

    /**
     * Reject the report, and then send them the comment
     * that was entered into the report
     */
    protected function reject_pirep_post() {
        $pirepid = $this->post->pirepid;
        $comment = $this->post->comment;

        if ($pirepid == '' || $comment == '')
            return;

        PIREPData::changePIREPStatus($pirepid, PIREP_REJECTED); // 2 is rejected
        $pirep_details = PIREPData::getReportDetails($pirepid);

        // Send comment for rejection
        if ($comment != '') {
            $commenter = Auth::$userinfo->pilotid; // The person logged in commented
            PIREPData::AddComment($pirepid, $commenter, $comment);

            // Send them an email
            $this->set('firstname', $pirep_details->firstname);
            $this->set('lastname', $pirep_details->lastname);
            $this->set('pirepid', $pirepid);

            $message = Template::GetTemplate('email_commentadded.php', true);
            Util::SendEmail($pirep_details->email, 'Comment Added', $message);
        }

        LogData::addLog(Auth::$userinfo->pilotid, 'Rejected PIREP #' . $pirepid);

        # Call the event
        CodonEvent::Dispatch('pirep_rejected', 'PIREPAdmin', $pirep_details);
    }

    protected function edit_pirep_post() {
        if ($this->post->code == '' || $this->post->flightnum == ''
                || $this->post->depicao == '' || $this->post->arricao == ''
                || $this->post->aircraft == '' || $this->post->flighttime == ''
            ) {

            $this->set('message', 'You must fill out all of the required fields!');
            $this->render('core_error.php');
            return false;
        }

        $pirepInfo = PIREPData::getReportDetails($this->post->pirepid);
        if (!$pirepInfo) {
            $this->set('message', 'Invalid PIREP!');
            $this->render('core_error.php');
            return false;
        }

        $this->post->fuelused = str_replace(' ', '', $this->post->fuelused);
        $this->post->fuelused = str_replace(',', '', $this->post->fuelused);
        $fuelcost = $this->post->fuelused * $this->post->fuelunitcost;

        # form the fields to submit
        $data = array(
            'pirepid' => $this->post->pirepid,
            'code' => $this->post->code,
            'flightnum' => $this->post->flightnum,
            'depicao' => $this->post->depicao,
            'arricao' => $this->post->arricao,
            'aircraft' => $this->post->aircraft,
            'flighttime' => $this->post->flighttime,
            'load' => $this->post->load,
            'price' => $this->post->price,
            'pilotpay' => $this->post->pilotpay,
            'fuelused' => $this->post->fuelused,
            'fuelunitcost' => $this->post->fuelunitcost,
            'fuelprice' => $fuelcost,
            'expenses' => $this->post->expenses
        );

        if (!PIREPData::updateFlightReport($this->post->pirepid, $data)) {
            $this->set('message', 'There was an error editing your PIREP');
            $this->render('core_error.php');
            return false;
        }

        PIREPData::SaveFields($this->post->pirepid, $_POST);

        //Accept or reject?
        $this->post->id = $this->post->pirepid;
        $submit = strtolower($this->post->submit_pirep);

        // Add a comment
        if (trim($this->post->comment) != '' && $submit != 'reject pirep') {
            PIREPData::AddComment($this->post->pirepid, Auth::$userinfo->pilotid, $this->post->comment);
        }

        if ($submit == 'accept pirep') {
            $this->approve_pirep_post();
        } elseif ($submit == 'reject pirep') {
            $this->reject_pirep_post();
        }

        StatsData::UpdateTotalHours();

        # Refresh the PIREP
        # $pirepInfo = PIREPData::getReportDetails($this->post_action->pirepid);
        PilotData::updatePilotStats($pirepInfo->pilotid);

        LogData::addLog(Auth::$userinfo->pilotid, 'Edited PIREP #' . $this->post->id);
        return true;
    }
}
