<?php include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/_global/dir_root.php'); ?>

<?php

ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);

$output['result'] = "";
$output['success'] = "";
$output['debug'] = "";
$output['session'] = "";

function debug($string)
{
    $GLOBALS['output']['debug'] .= "[Debug - " . $string . "] ";
}

function error($string)
{
    $GLOBALS['output']['debug'] .= "[Error - " . $string . "] ";
}

function sendOutput()
{
    echo json_encode($GLOBALS['output']);
}
    
    debug("Attempting To Connect");	
	$conn = new mysqli("localhost", "ps2020", "ps2020pass");

	if ($conn->connect_errno) {
		echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
	}
	else {
		debug("Successful Connection");
		// debug($conn->host_info);
	}

	// if db connection success
	if($conn->select_db('ps2020')) { debug("Using ps2020"); }
    else { error($conn->error); }
    
    //Here is the random Code generator
    function getRandomString() {

        $n=10;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
      
        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, strlen($characters) - 1);
            $randomString .= $characters[$index];
        }
      
        return $randomString;
    }
    
    if($_SERVER["REQUEST_METHOD"] == "POST") {
        $fname = $_POST["fname"];
        $lname = $_POST["lname"];
        $username = mysqli_real_escape_string($conn,$_POST["username"]);
        $email = mysqli_real_escape_string($conn,$_POST["email"]);
        $password = hash('sha256', mysqli_real_escape_string($conn,$_POST["password"]), false);
        $code = $_POST["specify-code"];
        $school_id = 0; // 0 = particpants don't belong to a school 
        $class_id = 0; // 0 = particpants don't belong to a school 
        $account = 0; // every one is a particpant by default
        $completed_survey = 0;
        $sql = "SELECT * FROM school";
        $result = $conn->query($sql);

    if($result->num_rows > 0){
        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"];
                $account = 2;
                break;
            }
            
        }
	}
	
	$sql = "SELECT * FROM school_class";
    $result = $conn->query($sql);

    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"];
                $account = 1;
                break;
            }
            
        }
	}

        //The value below are unallocated and needs to work upon them
       
        $verify_code = getRandomString();
        
        $id_set = false;

		$result = $conn->query("SELECT * FROM user_account");
			if($result) {
				$id = 1;
				while ( $row = $result->fetch_assoc() ){
					
					if ($id == $row['user_id'] && $id_set == false){  //if 'id' already exist, increment
						$id++;
					}
					else if ($id < $row['user_id']){  //no more increment
						$id_set = true;
					}
				}
			}
            //The active will be zero as all the accounts need to be verified
            if ($conn->query("INSERT INTO user_account VALUES ('$id', '$username', '$password', '$email', $account, '$school_id', '$class_id', NOW(), NOW(), '$verify_code', '$completed_survey', 0)") === TRUE) {
            
                //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 = "Account-Verification Code For GEESE";

                $message = "<b>Welcome to GEESE.</b>";
                $message .= "<h1>" . $username . "we would like to thank you for joining GEESE</h1>";
                $message .= "<p>Your Verfication Code is: " . $verify_code . "</p>";

                $header = "From:teamgeese1@gmail.com \r\n";
                $header .= "Cc:teamgeese1@gmail.com \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...";
                }

                session_start();
                $_SESSION['username'] = $username;
                $_SESSION['accountType'] = $accountType;	
                // $_SESSION['code'] = $verify_code;
                $_SESSION['email'] = $email;
                
                $output['success'] = true;
                $output['session'] = array("user" => $_SESSION['user'], "accountType" => $_SESSION['accountType']);
    
                // header('location: '.dirname(__FILE__).'./../logged.php');
                header('location: '.dir_rootPHP.'_a_tanuj/verifyEmail.php');
            } else {
                error($conn->error);
            }
       }
       sendOutput();
       $conn->close();        

?>
