<?php
	include($_SERVER['DOCUMENT_ROOT'] ."/_ps2020/config/connect.php");
	// include(dirname(__FILE__).'./../config/connect.php');
	include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/_global/dir_root.php');

	if($_SERVER["REQUEST_METHOD"] == "POST") {
		
		// username and password sent from sign-in
		$username = mysqli_real_escape_string($conn,$_POST["email"]);
		$password = hash('sha256', mysqli_real_escape_string($conn,$_POST["password"]), false);


		$result = $conn->query("SELECT * FROM user_account WHERE (username = '$username' OR email = '$username') AND password = '$password'");
		if($result) {
			if($result->num_rows == 1)
			{
				$row = $result->fetch_assoc();
				
					session_start();
					// debug("Session started");
		
					$_SESSION['userID'] = $row['user_id'];
					$_SESSION['user'] = $row['username'];
					$_SESSION['email'] = $row['email'];
					$_SESSION['accountType'] = $row['accountType'];

						$result = $conn->query("SELECT * FROM user_role WHERE role_id=".$row['accountType']);
						if($result) {
							while ( $row_role = $result->fetch_assoc() ){
								$_SESSION['accountType_name'] = $row_role['role'];
							}
						}
		
					$output['success'] = true;
					$output['session'] = array("user" => $_SESSION['user'], "accountType" => $_SESSION['accountType']);

				if($row['active'] == 1)
				{
					header('location: '.dir_root.'account/dashboard.php');
	
					sendOutput();
					exit;
				}
				else
					header('location: '.dir_root.'verify-email.php');
			}
			elseif($result->num_rows > 1)
			{
				$msg = "Duplicate Entries for login details";
				header('location: '.dir_root.'sign-in.php?msg='.$msg);

				$output['success'] = false;
				error($msg);
			}
			else 
			{
				$msg = "Your Login Name or Password is incorrect";
				header('location: '.dir_root.'sign-in.php?msg='.$msg);

				$output['success'] = false;
				error($msg);
			}
		}
		else {
			$output['success'] = false;
			error($conn->connect_error);

			$msg = "Your Login Name or Password is incorrect";
			header('location: '.dir_root.'sign-in.php?msg='.$msg);
		}
	}
	sendOutput();
	   
	$conn->close();
?>