<?php
	// use PHPMailer\PHPMailer\PHPMailer;

	include($_SERVER['DOCUMENT_ROOT'] ."/_ps2020/config/connect.php");
	include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/_global/dir_root.php');
   
	if($_SERVER["REQUEST_METHOD"] == "POST") {

		// username and password sent from form
		$username = mysqli_real_escape_string($conn,$_POST["username"]);
		$password = hash('sha256', mysqli_real_escape_string($conn,$_POST["password"]), false);
		$email = mysqli_real_escape_string($conn,$_POST["email"]);
		$accountType = 0; // 0 = Participant (Base AccountType)
		$school_id = 0; // 0 = Unallocated (particpants don't belong to a school)
        $class_id = 0; // 0 = Unallocated (particpants don't belong to a class)
		$verify_code = 0;
		$completed_demographic = 0;
		$completed_survey = 0;

			// generate 'id'
				$result = $conn->query("SELECT * FROM user_account");
					if($result) {
						$id = 1;
						while ( $row = $result->fetch_assoc() ){
							
							if ($id <= $row['user_id']){  //if 'id' already exist, increment
								$id = $row['user_id'] +1;
							}
						}
					}

			// set Account-Type (by access-code)
				$code = $_POST["specify-code"];

				if ( !empty($code) ){
					$result = $conn->query("SELECT * FROM school");
						while($row = $result->fetch_assoc()) {
				            //This is to check if code is for a 'teacher'
				            if($row["specific_teacherCode"] == $code){
				                $school_id = $row["school_id"];
				                $accountType = 2;
				            }
				            //This is to check if code is for a 'school-admin'
				            else if($row["specific_sAdminCode"] == $code){
				                $school_id = $row["school_id"];
				                $accountType = 3;
				            }
				        }

					$result = $conn->query("SELECT * FROM school_class");
						while($row = $result->fetch_assoc()) {
				            //This is to check if it is a 'student' code
				            if($row["specific_classCode"] == $code){
				                $school_id = $row["school_id"];
				                $class_id = $row["class_id"];
				                $accountType = 1;
				            }
				        }
				}

			// random Code generator (for 'verify_code')
				function getRandomCode() {

			        $n=10;
			        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			        $randomString = '';
			      
			        for ($i = 0; $i < $n; $i++) {
			            $index = rand(0, strlen($characters) - 1);
			            $randomString .= $characters[$index];
			        }
			      
			        return $randomString;
			    }
			    $verify_code = getRandomCode();


		//The 'active' will be zero, before account is verified
		if ($conn->query("INSERT INTO user_account VALUES ('$id', '$username', '$password', '$email', $accountType, '$school_id', '$class_id', NOW(), NOW(), '$verify_code', '$completed_demographic', '$completed_survey', 0)") === TRUE) {
			
			// E-mail

				$email = $email;
				$name = "(no-reply) Team GEESE";
			    $subject = 'GEESE Verification Code';
				$content = "
					<h1 style='font-size: 22px;'><center>" . $email . "</center></h1>

					<p>Hi " . $username . ",</p>
	        
                    <p>We are team behined project GEESE. We would like to extend our gratitude for your joining to GEESE Surveys.</p>

                    <p>Although your account has already been setup. But we need to verify your account before you can use it.</p>

                    <p>This is just to validate your input credentials, and for security reasons and we research purposes.</p>

                    <p>Once you sign-up/sign-in for the first time you will directed to a page to activate your account by putting in a specific verify code generated from our website.</p>

                    <p>Your verification code is: <b>".$verify_code."</b></p>
				";

				// Mailing [function]
					include_once "send_email.php";

					if($mail->send()){
			            // Logged-in
						session_start();
						$_SESSION['userID'] = $id;
						$_SESSION['user'] = $username;
						$_SESSION['email'] = $email;
						$_SESSION['accountType'] = $accountType;
						
						$output['success'] = true;
						$output['session'] = array("user" => $_SESSION['user'], "accountType" => $_SESSION['accountType']);

						// header('location: '.dirname(__FILE__).'./../logged.php');
						header('location: '.dir_root.'verify-email.php');
			        }else{
			            // Logged-in
						session_start();
						$_SESSION['userID'] = $id;
						$_SESSION['user'] = $username;
						$_SESSION['email'] = $email;
						$_SESSION['accountType'] = $accountType;
						
						$output['success'] = true;
						$output['session'] = array("user" => $_SESSION['user'], "accountType" => $_SESSION['accountType']);

						// header('location: '.dirname(__FILE__).'./../logged.php');
						header('location: '.dir_root.'verify-email.php');
			        }

		} else {
			error($conn->error);
		}
   }
   sendOutput();
   $conn->close();
?>