<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	$prefix = DB_TABLE_PREFIX;
	
	$_POST = array_map('trim', $_POST);
	$_POST['login'] = strtolower( $_POST['login'] );
	//$_POST['password'] = password_hash( $_POST['password'], PASSWORD_DEFAULT );
	
	$_POST = array_map( array(uss::$global['mysqli'], 'real_escape_string'), $_POST );
	
	$SQL = "
		SELECT 
			{$prefix}_users.*,
				{$prefix}_usermeta._value as enrid
		FROM {$prefix}_users
		INNER JOIN {$prefix}_usermeta
		ON {$prefix}_users.id = {$prefix}_usermeta._ref
		WHERE 
			{$prefix}_usermeta._key = 'user:enrid'
			AND ( {$prefix}_users.email = '{$_POST['login']}' OR {$prefix}_usermeta._value = '\"{$_POST['login']}\"' )
	";
	
	$user = uss::$global['mysqli']->query( $SQL )->fetch_assoc();
	
	if( $user && !password_verify( $_POST['password'], $user['password'] ) ) $user = null;
	
	if( !$user ) uss::console( ':alert', "Incorrect login credential" );
	
	else {
		
		$_SESSION['access_token'] = HASH( 'SHA256', $user['usercode'] . $user['id'] );
		
		uss::$global['user'] = $user;
		
		$exam = dashboard::fetch_assoc( "{$prefix}_exams", $_POST['portal'], "portal" );
		
		if( !$exam ) uss::console( ':alert', "Incorrect Portal ID" );
		
		else {
			
			if( empty($exam['status']) ) uss::console( ':alert', "The Portal Is not available at the moment. <br> Please try later" );
			
			else {
				
				$SQL = "
					SELECT * FROM {$prefix}_portals
					WHERE 
						userid = {$user['id']}
						AND portal_id = '{$exam['portal']}'
				";
				
				$portalExists = uss::$global['mysqli']->query( $SQL );
				
				if( !$portalExists->num_rows ) {
				
					$data = array(
						"userid" => $user['id'],
						"portal_id" => (string)$exam['portal']
					);
					
					$SQL = sQuery::insert( "{$prefix}_portals", $data );
					
					$status = uss::$global['mysqli']->query( $SQL );
					
					if( $status ) $_SESSION['portal'] = uss::$global['mysqli']->insert_id;
					
					else uss::console( ':alert', "Exam session could not be started" );
					
				} else {
					
					$portal = $portalExists->fetch_assoc();
					
					if( $portal['userid'] == $user['id'] ) $_SESSION['portal'] = $portal['id'];
					
					else uss::console( ':alert', "Exam session could not be stabilized" );
					
				}
				
			}
			
		}
		
	}
	
}