<?php
	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_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"];

				$result = $conn->query("SELECT * FROM school, school_class");
					if($result->num_rows > 0){
				        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;
				            }
				            //This is to check if code is for a 'teacher'
				            else 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;
				            }
				        }
					}

			// 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_survey', 0)") === TRUE) {
			
			// E-mail
				//Now that everything has been inserted 
                //Now we need to email the user with a verify code and all
                //The user's email accout is sent the code
                $to = $email;
                $subject = "GEESE Verification Code";

                $message = "<h4>Welcome to GEESE.</h4>";
                $message .= "<h4>Hi '" . $username . "'', we would like to thank you for joining GEESE</h4>";
                $message .= "<span>Your Verfication Code is: <h1>" . $verify_code . "</h1></span>";

                $header = "From:no-reply@geese.com \r\n";
                $header .= "Cc: \r\n";
                $header .= "MIME-Version: 1.0\r\n";
                $header .= "Content-type: text/html\r\n";
                //This is to send the verify code to the user
                $retval = mail ($to,$subject,$message,$header);

                if( $retval == true ) {
                echo "Message sent successfully...";
                }else {
                echo "Message could not be sent...";
                }

			
			// 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();
?>