<?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://creat ivecommons.org/licenses/by-nc-sa/3.0/
 */

class Registration extends CodonModule
{
	public function HTMLHead() {
		/*Show our password strength checker
			*/
		if($this->get->page == 'register') {
			$this->renderTemplate('registration_javascript.tpl');
		}
	}


	public function index()
	{

                //updated to Google noCaptcha 1/15
		require_once CORE_LIB_PATH.'/recaptcha/recaptchalib.php';

		if(Auth::LoggedIn()) { // Make sure they don't over-ride it
			$this->render('login_already.tpl');
			return;
		}

		# If Entrance exam is ON, then will show the exam beginning process.
		# else, it will show the registration form.


		if(Config::Get('REQUIRE_ENTRANCE_EXAM') == 1) {
			if(isset($_POST['submit'])) {
				$this->ProcessRegistration();
			}
			// else if($_POST['ce_exam'] == 'passed') {
			// 	# The exam page should return a post value to show the reg form.
			// 	$this->ShowForm();
			// }
			else {
				$this->ShowExam();
			}
		} else {
			if(isset($_POST['submit'])) {
				$this->ProcessRegistration();
			}
			else {
				$this->ShowForm();
			}
		}




	}

	public function ShowExam() {
		$this->render('registration_exam.php');
	}

	public function BeginCrewTest() {

		$email = $this->post->examinee_email;

		#Checking if the pilot already has any records of entrance exams with us!

		$sql = "SELECT * FROM `icrew_entrance_exams` WHERE `email` LIKE '$email'";
		$ret = DB::get_row($sql);

		if($ret == '') { # if there are no records, then proceed with this.
			// Continue
			// Status 1 = Taking Exam
			// Status 2 = Failed Exam


			# checking if the Email ID is a valid one, this is to avoid jerks and Bots ;)

			if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    			$checks = PilotData::getPilotByEmail($email);

				if($checks == '') { # No previous records found for this email ID, all clear to take the exam!

					# Since there are no previous records, this will be the place where the data gets stored into the DB
						$sql = "INSERT INTO `icrew_entrance_exams` (`email`, `status`, `marks`) VALUES ('$email', '1', '0')";
						DB::query($sql);
						$this->render('registration_exam_questions.php');

				} else {
						#Email ID is already of a pilot who has registered with us.
						$this->set('message', 'This email ID is already registered with us! Try loggin in? If you forgot your password, hit the Password reset link!');
						$this->show('core_error.php');
						$this->ShowExam();
				}
			} else {
				# This page just simply dies, "By dieing, thou shall kill the bots!" LOL
				$message = 'A scam bot registration was averted by icrewsystems WebProtector protocol. Details : ERR165(C), action taken : Added email ID to bot prevention list, and informed icrewsystems HQ and VA HQ! Time : '.date("h:i:s A");
				DiscordData::deliver($message, $url = '');
				die("Looks like $email is not a valid email address, please try again with a proper email ID, and oh yes! We're a bot proof website ;)");

			}
		} else {

			# There are previous records of this pilot taking entrance exam.

			$date = $ret->time;
			$expirytime = $date;
			$time = strtotime($expirytime);
			$endTime = date('Y-m-d H:i:s', strtotime('+1 hours', $time));
			#Since expiry time is 12 hours, we are adding 12 hours.
			$currenttime = date('Y-m-d H:i:s');

			$endTimeN = date('H:i:s A d-m-Y', strtotime('+1 hours', $time));

			// die(print_r($ret));
			$exam_status = $ret->status;
			if($exam_status == 2) {
				# if the status of the previous exam is FAIL, then this code is executed....

					# If the pilot has failed, and his cooling period is over, then he can take the next exam...else he has to wait

					if(strtotime($currenttime) > strtotime($endTime)) {

							#waiting period over

							$update = "UPDATE `icrew_entrance_exams` SET `time` = '$currenttime' WHERE `id` = $ret->id";
							DB::query($update);
							$this->set('message', 'Your waiting period is over!');
							$this->render('registration_exam_questions.php');


						} else {
							$this->set('error', 'You have failed an exam previously, please wait until the cooling period is over (12 hours). Your waiting period will end at '.$endTimeN.'');
							$this->render('registration_error');
						}
			} else {

				$this->render('registration_exam_questions.php');
			}
					// die('You have taken exam already!');

		}



	}

	public function EndCrewTest()  {
				$exam_id = DB::escape($this->post->exam_id);
        $howmany = DB::escape($this->post->howmany);
        $passing = DB::escape($this->post->passing);
        $version = DB::escape($this->post->version);
        $email = DB::escape($this->post->examinee_email);
        $i=1;
        $correct=0;
        // Template::Show('exams/exam_question_result_header.php');
        while ($i<= $howmany):

            $id = 'question_id' . $i;
            $question_id = DB::escape($this->post->$id);
            $id2 = 'question' . $i;
            $answer = DB::escape($this->post->$id2);

            $cor = ExamsData::compare_answer($question_id, $answer);
            if ($cor->correct_answer == $answer) {
                Template::ClearVars($wrong);
                $question = ExamsData::get_question($question_id);
                Template::Set('question', $question->question );
                if ($question->correct_answer == '1') {Template::Set('answer', $question->answer_1 );}
                elseif ($question->correct_answer == '2') {Template::Set('answer', $question->answer_2 );}
                elseif ($question->correct_answer == '3') {Template::Set('answer', $question->answer_3 );}
                elseif ($question->correct_answer == '4') {Template::Set('answer', $question->answer_4 );}
                // Template::Set('number', $i);
                // Template::Set('div', 'success');
                // Template::Show('exams/exam_question_result.php');
                $correct++;
            } else {
                $question = ExamsData::get_question($question_id);
                Template::Set('question', $question->question );
                if ($question->correct_answer == '1') {Template::Set('answer', $question->answer_1 );}
                elseif ($question->correct_answer == '2') {Template::Set('answer', $question->answer_2 );}
                elseif ($question->correct_answer == '3') {Template::Set('answer', $question->answer_3 );}
                elseif ($question->correct_answer == '4') {Template::Set('answer', $question->answer_4 );}

                if ($answer == '1') {Template::Set('wrong', $question->answer_1 );}
                elseif ($answer == '2') {Template::Set('wrong', $question->answer_2 );}
                elseif ($answer == '3') {Template::Set('wrong', $question->answer_3 );}
                elseif ($answer == '4') {Template::Set('wrong', $question->answer_4 );}
                // Template::Set('number', $i);
                // Template::Set('div', 'error');
                // Template::Show('exams/exam_question_result.php');
            }
            $i++;
        endwhile;
        $result = round((($correct / $howmany) * 100), 0);
        if ($result >= $passing) {
            $passfail = 1;
        }
        else {
            $passfail = 0;
        }

        // $pid = Auth::$userinfo->pilotid;

        // $approve = ExamsData::get_setting_info('5');
        // if ($approve->value == '1'); {ExamsData::unassign_exam($pid, $exam_id);}
        // ExamsData::record_results($pid, $exam_id, $exam_description, $result, $passfail, $version);



        if ($result >= $passing) {
        	$sql = "SELECT * FROM `icrew_entrance_exams` WHERE `email` LIKE '$email'";
			$ret = DB::get_row($sql);
            $time_of_req = date('Hi');
            $time_of_req = md5($time_of_req);
            session_start();
            $_SESSION['email'] = $email;
            $update = "UPDATE `icrew_entrance_exams` SET `time` = '$currenttime', `status` = '1', `marks` = '$result' WHERE `id` = $ret->id";
			DB::query($update);
            header('Location: '.SITE_URL.'/index.php/registration/ExamPassed/'.$time_of_req.'/'.$email.'');

        }
        else {
        	$sql = "SELECT * FROM `icrew_entrance_exams` WHERE `email` LIKE '$email'";
			$ret = DB::get_row($sql);

			$currenttime = date('Y-m-d H:i:s');
			$update = "UPDATE `icrew_entrance_exams` SET `time` = '$currenttime', `status` = '2', `marks` = '$result' WHERE `id` = $ret->id";
			DB::query($update);

			$message = '[REGISTRATION EXAM FAIL] E-Mail ID : '.$email.', Marks scored : '.$result.'%';
			DiscordData::deliver($message, $url = '');
            $this->set('error', 'You have scored '.$result.'%. You did not pass the entrance exam. You can have your next attempt after 1 hour');
            $this->ExamResult();



        }
    }

	public function ExamResult() {
		// The function name is just to fool the pilots. This page is to only to display message to the failed pilots.
		$this->render('registration_error.php');
	}

	public function ExamPassed($time_of_req) {
		$time = date('Hi');
		$time = md5($time);
		
			$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
			$numSegments = count($segments);
			$currentSegment = $segments[$numSegments - 1];
			$email = htmlentities($currentSegment);


			$query = "SELECT * FROM `icrew_entrance_exams` WHERE `email` LIKE '$email'";
			$ret = DB::get_results($query);
			
			
		if($time_of_req == $time) {

			foreach ($ret as $ret) {
				$marks = $ret->marks;
			}

			$this->set('success', 'Congratulations, you have passed the exam with '.$marks.'%. You have proved that you have what it takes to be a part of our Crew, please continue with filling out the registration form!');
			$this->ShowForm();
		} else {

			$message = '[REGISTRATION EXAM INVALID AUTHENTICATION] Please authorize '.$email.'\'s registration! Authentication code expired `time of request '.$time_of_req.'`, this maybe due to a slow internet connection, or a page re-load on the EndCrewTest page.';
			DiscordData::deliver($message, $url = '');
			$this->set('error', 'Your exam code generated by our system has been expired!<br><br> This is our security protocol to hold applications temporarily if there has been an expired exam code. Your exam code : '.$time_of_req.' (please note it down)<br> <br> Our staff has been notified about this, you will be contacted within 48 hours, if not, please stop by at our facebook/twitter/instagram/discord page(s) and let us know!');
			$this->ExamResult();
		}







	}


	protected function ShowForm()
	{
                //Google reCaptcha
                //updated to Google noCaptcha 1/15
                $this->set('sitekey', RECAPTCHA_PUBLIC_KEY);
                $this->set('lang', 'en');

				$field_list = RegistrationData::GetCustomFields();
				$this->set('extrafields', $field_list);
                $this->set('field_list', $field_list);

                $airline_list = OperationsData::getAllAirlines(true);
				$this->set('allairlines', $airline_list);
                $this->set('airline_list', $airline_list);

                $hub_list = OperationsData::getAllHubs();
                $this->set('allhubs', $hub_list);
                $this->set('hub_list', $hub_list);
                $country_list = Countries::getAllCountries();
				$this->set('countries', $country_list);
				$this->set('country_list', $country_list);
				$this->render('registration_mainform.tpl');
	}

	/**
	 * Registration::ProcessRegistration()
	 *
	 * @return
	 */
	protected function ProcessRegistration()
	{

		// Yes, there was an error
		if(!$this->VerifyData()) {
			$this->ShowForm();
            return;
        }

		$data = array(
			'firstname' => $this->post->firstname,
			'lastname' => $this->post->lastname,
			'email' => $this->post->email,
			'password' => $this->post->password1,
			'code' => $this->post->code,
			'location' => $this->post->location,
			'hub' => $this->post->hub,
			'confirm' => false
		);

		if(CodonEvent::Dispatch('registration_precomplete', 'Registration', $_POST) == false) {
			return false;
		}

		$ret = RegistrationData::CheckUserEmail($data['email']);

		if($ret) {
			$this->set('error', Lang::gs('email.inuse'));
			$this->render('registration_error.tpl');
			return false;
		}

		$val = RegistrationData::AddUser($data);
		if($val == false) {
			$this->set('error', RegistrationData::$error);
			$this->render('registration_error.tpl');
			return;
		} else {

			$pilotid = RegistrationData::$pilotid;

			/* Automatically confirm them if that option is set */
			if(Config::Get('PILOT_AUTO_CONFIRM') == true) {
				PilotData::AcceptPilot($pilotid);
				RanksData::CalculatePilotRanks();

				$pilot = PilotData::getPilotData($pilotid);
				$this->set('pilot', $pilot);
				$this->render('registration_autoconfirm.tpl');
			} else { /* Otherwise, wait until an admin confirms the registration */
				RegistrationData::SendEmailConfirm($email, $firstname, $lastname);
				$this->render('registration_sentconfirmation.tpl');
			}
		}
		
		$pilot = PilotData::getPilotData($pilotid);
		$flarum_username = $pilot->code.''.$pilot->pilotid.' | '.$pilot->firstname.' '.$pilot->lastname;
		$flarum_email = $pilot->email;
		$password = $this->post->password1;
		FlarumData::create_user($flarum_username, $flarum_email, $password);
		CodonEvent::Dispatch('registration_complete', 'Registration', $_POST);

		// Registration email/show user is waiting for confirmation
		$sub = 'A user has registered';
		$message = "[NEW REGISTRATION] The user {$data['firstname']} {$data['lastname']} ({$data['email']}) has registered, and is awaiting confirmation. Please authorize as soon as possible, we don't want our aspiring pilots to wait!";
		DiscordData::deliver($message, $url = '');
		$email = Config::Get('EMAIL_NEW_REGISTRATION');
		if(empty($email)) {
			$email = ADMIN_EMAIL;
		}
		
		
		Util::SendEmail($email, $sub, $message);
		
		// Send email to user
		$this->set('firstname', $data['firstname']);
		$this->set('lastname', $data['lastname']);
		$this->set('userinfo', $data);

		$message = Template::Get('email_registered.tpl', true);
		Util::SendEmail($data['email'], 'Registration at '.SITE_NAME, $message);

		$rss = new RSSFeed('Latest Pilot Registrations', SITE_URL, 'The latest pilot registrations');

        $pilot_list = PilotData::GetLatestPilots();
		foreach($pilot_list as $pilot) {
			$rss->AddItem('Pilot '.PilotData::GetPilotCode($pilot->code, $pilot->pilotid)
							. ' ('.$pilot->firstname .' ' . $pilot->lastname.')',
							SITE_URL.'/admin/index.php?admin=pendingpilots','','');
		}

		$rss->BuildFeed(LIB_PATH.'/rss/latestpilots.rss');

	}

	/*
	 * Process all the registration data
	 */
	protected function VerifyData()
	{
		$error = false;

                //Google reCaptcha
                //updated to Google noCaptcha 1/15
                $resp = null;
                $reCaptcha = new ReCaptcha(RECAPTCHA_PRIVATE_KEY);
                // Was there a reCAPTCHA response?
                if ($_POST["g-recaptcha-response"]) {
                        $resp = $reCaptcha->verifyResponse(
                        $_SERVER["REMOTE_ADDR"],
                        $_POST["g-recaptcha-response"]
                    );
                }

                //check if reCaptcha response was valid
                if ($resp == null) {
                     $error = true;
                     $this->set('message', 'reCaptcha Validation Error');
                }
                //end Google reCaptcha

		/* Check the firstname and last name
		 */
		if($this->post->firstname == '') {
			$error = true;
			$this->set('message', 'Please fill all the fields');
		} else {

		}

		/* Check the last name
		 */
		if($this->post->lastname == '') {
			$error = true;
			$this->set('message', 'Please fill all the fields');
		}
		else {
			
		}

		/* Check the email address
		 */
		if(filter_var($this->post->email, FILTER_VALIDATE_EMAIL) == false) {
			$error = true;
			$this->set('message', 'Please fill all the fields');
		} else {
			
		}


		/* Check the location
		 */
		if($this->post->location == '') {
			$error = true;
			$this->set('message', 'Please fill all the fields');
		} else {
		}

		// Check password length
		if(strlen($this->post->password1) <= 5) {
			$error = true;
			$this->set('message', 'The password is too short!');
		} else {
		}

		// Check is passwords are the same
		if($this->post->password1 != $this->post->password2) {
			$error = true;
			$this->set('message', 'The passwords do not match!');
		} else {
			
		}

		//Get customs fields
		$fields = RegistrationData::getCustomFields();

		if(count($fields) > 0) {
		    foreach ($fields as $field) {
			$value = Vars::POST($field->fieldname);
			$value1 = DB::escape($value);
			if ($field->required == 1 && $value1 == '') {
				$error = true;
				$this->set('custom_'.$field->fieldname.'_error', true);
				$this->set('message', 'Please fill all the fields');
			} else {
				
			}
		    }
		}

		if($error == true) {
			$this->render('core_error.php');
			return false;
		}

		return true;
	}
}
