<?php
// IN Admin/modules/PIREPAdmin, the default PIREP page's reviewing option has been changed
// from PIREP_PEnding to PIREP_INPROGRESS.
class ICSData extends CodonData
{

    public static function autoevaluate()
    {

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

        function add_comment($pirepid, $comment, $added_by)
        {
            PIREPData::addComment($pirepid, $added_by, $comment);
        }

        function process_landingrate($landingrate)
        {
            if ($landingrate == 0)
            {
                return 1;
            }
            else if ($landingrate >= LANDING_RATE_LIMIT)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        $params = array();
        $params['p.accepted'] = PIREP_PENDING;
        $allpireps = PIREPData::findPIREPS($params);

        $total = count($allpireps);
        // echo $total;
        $count = 0;
        if ($total > 0)
        {
            foreach ($allpireps as $pirep)
            {
                sleep(3);
                $reason = array();
                $errors = 0;
                $manual_review = 0;

                $pilotdata = PilotData::getPilotData($pirep->pilotid);

                // Landing Rate.
                if (process_landingrate($pirep->landingrate) == 1)
                {
                    // echo "Landing Rate: OK";
                    
                }
                else
                {
                    $errors++;
                    $reason['landing_rate'] = 'Landing rate was above / equal to ' . LANDING_RATE_LIMIT . ' FPM';
                }

                /* Parameters to check the ACARS log. Add new key for each entry. If you don't have a
                a specific key, you can just add a random key for the array.
                */
                $checks = array();
                // $checks['overspeed'] = 'Exceeded 250 KIAS below 10,000 feet MSL';
                $checks['stalling'] = 'Stall';
                $checks['refueling'] = 'Fuel Quantity';
                $checks['simulation_rate'] = 'Simulation rate';
                $checks['fuelquantity'] = 'Fuel quantity increased';
              //  $checks['refueling'] = 'Sim unpaused';

                $log = explode('*', $pirep->log);
                foreach ($log as $line)
                {
                    foreach ($checks as $check)
                    {
                        if (strpos($line, $check) !== false)
                        {
                            // echo $line .' -- PIREP Log check: NOT OKAY';
                            if ($check == 'stalling' || $check == 'simulation_rate' || $check == 'fuelquantity')
                            {
                                $error++; // Recommends to REJECT PIREP
                                $reason[$check] = 'PIREP log contains ' . $line;
                            }
                            else
                            {
                                $manual_review++; // Recommends for Manual Review
                                $reason[$check] = 'PIREP log contains ' . $line;
                            }
                        }
                        else
                        {

                        }
                    }
                }

                if ($errors == 0)
                {
                    if ($manual_review != 0)
                    {
                        //////////////////////////////////////////////////////////
                        // MANUAL REVIEW PIREP                                  //
                        //////////////////////////////////////////////////////////
                        $who_to = $pirep->pilotid;
                        $who_from = 1;
                        $subject = 'PIREP #' . $pirep->pirepid . ' under manual Review | PIREP Bot';
                        $newmessage = 'This is to inform you that your PIREP #' . $pirep->pirepid . ' is under manual review due to the following reason(s) <br />';
                        foreach ($reason as $rr)
                        {
                            $newmessage .= $rr;
                            $newmessage .= '<br />';
                        }
                        $newmessage .= 'It may take upto 6 hours for your PIREP to be reviewed. <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 = '[PIREPBot] Manual Review required for PIREP #' . $pirep->pirepid . ' (' . $pirep->depicao . ' - ' . $pirep->arricao . ') by ' . $pilotdata->firstname . ' ' . $pilotdata->lastname . ' due to: ';
                        foreach ($reason as $rr)
                        {
                            $discord_message .= $rr;
                            $discord_message .= ' | ';
                        }

                        PIREPData::ChangePIREPStatus($pirep->pirepid, 3);
                        $link = SITE_URL . '/admin/index.php/pirepadmin/editpirep?pirepid=' . $pirep->pirepid;
                        $color = 'f08800';
                        $tag = $time;
                        DiscordData::delive_detailed($tag, $color, $discord_message, $link, MANUAL_REVIEW_DISCORD_CHANNEL);

                    }
                    else
                    {

                        //////////////////////////////////////////////////////////
                        // ACCEPT PIREP                                         //
                        //////////////////////////////////////////////////////////
                        $who_to = $pirep->pilotid;
                        $who_from = 1;
                        $subject = 'PIREP #' . $pirep->pirepid . ' is accepted | PIREP Bot';
                        $newmessage = 'This is to inform you that your PIREP #' . $pirep->pirepid . ' for flight ' . $pirep->code . $pirep->flightnum . ' (' . $pirep->depicao . ' - ' . $pirep->arricao . ') has been accepted by the PIREP Bot.
					 Your location has been updated to ' . $pirep->arricao;
                        $newmessage .= '. <br><br> <a href="' . SITE_URL . '/index.php/pireps/view/' . $pirep->pirepid . '" class="btn btn-xs btn-success">POST FLIGHT REVIEW</a> <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);

                        // Check if first PIREP
                        $pilotdata = PilotData::getPilotData($pirep->pilotid);

                        if ($pirep->landingrate > SMOOTH_LANDING_LIMIT)
                        {
                        	$pirep_details = $pirep;
                            $recommendation = 'ADD AWARD (SL)';
                            $reason = 'Smooth Landing - ' . $pirep->landingrate.'fpm';

                            $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(1, '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 . '';
                            }
                        }

                        if ($pilotdata->lastpirep == '0000-00-00 00:00:00')
                        {
                            $recommendation = 'ADD AWARD (FF)';
                            $reason = 'First Flight';

                            $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(1, '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);
                        }

                        SchedulesData::IncrementFlownCount($pirep->code, $pirep->flightnum);
                        PIREPData::ChangePIREPStatus($pirep->pirepid, PIREP_ACCEPTED); // 1 is accepted
                        PilotData::UpdatePilotStats($pirep->pilotid);

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

                        $discord_message = '[PIREPBot] PIREP #' . $pirep->pirepid . ' (' . $pirep->depicao . ' - ' . $pirep->arricao . ') by ' . $pilotdata->firstname . ' ' . $pilotdata->lastname . ' has been `ACCEPTED`';

                        $link = SITE_URL . '/admin/index.php/pirepadmin/editpirep?pirepid=' . $pirep->pirepid;
                        $color = '00b500';
                        $tag = $time;
                        DiscordData::delive_detailed($tag, $color, $discord_message, $link, MANUAL_REVIEW_DISCORD_CHANNEL);

                    }
                }
                else
                {

                    //////////////////////////////////////////////////////////
                    // REJECT PIREP                                         //
                    //////////////////////////////////////////////////////////
                    

                    $who_to = $pirep->pilotid;
                    $who_from = 5640;
                    $subject = 'PIREP #' . $pirep->pirepid . ' was Rejected | PIREP Bot';
                    $newmessage = 'We are sorry to inform you that your PIREP #' . $pirep->pirepid . ' was rejected due to the following reason(s) <br />';
                    foreach ($reason as $rr)
                    {
                        $newmessage .= $rr;
                        $newmessage .= '<br />';
                    }
                    $newmessage .= 'To fix this, 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 = '[PIREPBot] Rejected PIREP #' . $pirep->pirepid . ' (' . $pirep->depicao . ' - ' . $pirep->arricao . ') by ' . $pilotdata->firstname . ' ' . $pilotdata->lastname . ' due to: ';
                    foreach ($reason as $rr)
                    {
                        $discord_message .= $rr;
                        $discord_message .= ' | ';
                    }
                    $link = SITE_URL . '/admin/index.php/pirepadmin/editpirep?pirepid=' . $pirep->pirepid;
                    $color = 'e00000';
                    $tag = $time;
                    PIREPData::ChangePIREPStatus($pirep->pirepid, PIREP_REJECTED);
                    LogData::addLog(1, 'Rejected PIREP #' . $pirep->pirepid . ' due to ' . $reason . '');
                    DiscordData::delive_detailed($tag, $color, $discord_message, $link, MANUAL_REVIEW_DISCORD_CHANNEL);
                }
                unset($reason);
                unset($manual_review);
                unset($accept);
                unset($errors);
            }
        }

    }

    public static function insertExamData($firstname, $lastname, $email)
    {
        $sql = "INSERT INTO `icrew_registration` (`id`, `email`, `firstname`, `lastname`, `time`)
		VALUES (NULL, '$email', '$firstname', '$lastname', CURRENT_TIMESTAMP);";
        return DB::get_results($sql);
    }

    public static function GetExamData($email)
    {
        $sql = "SELECT * FROM `icrew_registration`
							WHERE `email` = $email";

        return DB::get_results($sql);

    }

    public static function setRandomCode($pilotid, $randomstring)
    {
        /*UPDATE `phpvms_pilots` SET `password_reset` = 'leonard1234' WHERE `phpvms_pilots`.`pilotid` = 4*/

        $sql = "UPDATE " . TABLE_PREFIX . "pilots
				SET `password_reset` = '$randomstring'
				WHERE `pilotid` = $pilotid";

        return DB::get_results($sql);
    }

    public static function GetPilotByAuthCode($authcode)
    {

        return DB::get_row('SELECT * FROM ' . TABLE_PREFIX . 'pilots
							WHERE `password_reset`=' . $authcode);
    }

    public static function getPilotData($authcode)
    {
        $pilot = PilotData::findPilots(array(
            'p.password_reset' => $authcode
        ) , 1);

        if (!$pilot)
        {
            return false;
        }

        return $pilot[0];
    }

    public static function DestroyAuth($id)
    {
        $sql = "UPDATE " . TABLE_PREFIX . "pilots
				SET `password_reset` = 'AUTHENTICATION CODE EXPIRED'
				WHERE `pilotid` = $id";

        return DB::get_results($sql);
    }

    public static function ChangePassword($pilotid, $newpassword)
    {
        $salt = md5(date('His'));
        $password = md5($newpassword . $salt);
        RegistrationData::$salt = $salt;

        //, confirmed='y'
        $sql = "UPDATE " . TABLE_PREFIX . "pilots
				SET password='$password',
					salt='$salt'
				WHERE pilotid=$pilotid";

        $res = DB::query($sql);

        if (DB::errno() != 0) return false;

        return true;
    }

}

