<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	$prefix = DB_TABLE_PREFIX;
	
	$avatar = dashboard::call( 'upload_image', $_FILES['avatar'], 'profile' );
	
	$_POST['user']['email'] = strtolower($_POST['user']['email']);
	
	$user = dashboard::fetch_assoc( "{$prefix}_users", $_POST['user']['email'], "email" );
	
	if( $user ) {
		
		$status = !( $message = "The email is already in use" );
		
	} else if( $_POST['user']['password'] !== $_POST['user']['password2'] ) {
		
		$status = !( $message = "Password does not match" );
		
	} else {
		
		$data = array(
			"email" => $_POST['user']['email'],
			"password" => password_hash( $_POST['user']['password'], PASSWORD_DEFAULT ),
			"usercode" => core::keygen(6)
		);
		
		$SQL = sQuery::insert( "{$prefix}_users", $data );
		
		$insert = uss::$global['mysqli']->query( $SQL );
		
		if( $insert ) {
			
			$userid = uss::$global['mysqli']->insert_id;
			
			foreach( ['bio', 'department', 'enrid'] as $key ) {
				$_key = "user:{$key}";
				uss::$global['usermeta']->set( $_key, $_POST[$key], $userid );
			};
			
			uss::$global['usermeta']->set( 'avatar', $avatar, $userid );
			
			roles::user( $userid )::assign( 'student' );
			
			$root_url = core::url( ROOT_DIR );
			
			$status = !!( $message = "
				Your enrollment was successful <br> 
				Your enrollment ID is <strong class='fw-bold'>{$_POST['enrid']}</strong> <br>
				The admin will provid you with a <i><strong class='fw-bold'>protal ID</strong></i> - <br> which you will use to write your examination <br>
				<a href='{$root_url}'>Visit the exam portal now</a>
			" );
			
			$_POST = array();
		
		} else $status = !( $message = "The enrollment process failed" );
		
	};
	
	events::addListener('notice', function() use($status, $message) {
		$color = $status ? "success" : "danger";
		$icon = $status ? "fas fa-check-circle text-success" : "fas fa-times-circle text-danger";
		echo "<div class='alert alert-{$color} text-center'>
			<i class='{$icon} me-1'></i> {$message}
		</div>";
	});
	
};

