<?php 

defined( "DASHBOARD_MOD_DIR" ) OR DIE;

# ------------------------------------------

call_user_func(function() {
	
	$loginPage = core::url( ROOT_DIR . '/' . DASHBOARD_FOCUS_URI );
	
	$prefix = DB_TABLE_PREFIX;
	
	$status = false;
	
	
	/*
		Check if the email address is valid;
	*/
	
	if( !preg_match( core::regex('email'), $_POST['email'] ) ) {
		
		$message = "The email address is not valid";
		
		
	/*
		Check if username is valid;
	*/
	
	} elseif( isset($_POST['username']) && !preg_match("/^\w+$/i", $_POST['username']) ) {
		
		$message = "Username can only contain number, letter and underscore";
	
	
	/* 
		Check if password matches;
	*/
	
	} elseif ( $_POST['password'] !== $_POST['confirm_password'] ) {
		
		$message = "Password does not match";

	
	} else {
		
		/*
			Check if the email address already exists;
		*/
		
		$email_exists = dashboard::fetch_assoc( "{$prefix}_users", $_POST['email'], 'email' );
		
		if( $email_exists  ) 
			
			$message = "The email already exists";
			
		else {
			
			/*
				Check if the username already exists;
			*/
			
			$username = $_POST['username'] ?? null;
			$username_exists = dashboard::fetch_assoc( "{$prefix}_users", $username, 'username' );
			
			if( !empty($username) && $username_exists ) {
				
				$message = "The username already exists";
				
			} else {
				
				/*
					If parent ID is supplied:
					Then: confirm that the parent exists!
				*/
				
				if( isset($_POST['parent']) && !empty(uss::$global['options']->get('user:affiliation')) ) {
					$parent = dashboard::fetch_assoc("{$prefix}_users", $_POST['parent']);
					if( $parent ) $parent = $parent['id'];
				} else $parent = null;
				
				/* 
					Great! All validation process has been confirmed!
				*/
				
				$data = array(
					"email" => $_POST['email'],
					"password" => password_hash( $_POST['password'], PASSWORD_DEFAULT ),
					"username" => $username,
					"usercode" => core::keygen(7),
					"parent" => $parent
				);
				
				/*
					Insert into database;
				*/
				
				$SQL = sQuery::insert( "{$prefix}_users", $data, uss::$global['mysqli'] );
				
				$status = uss::$global['mysqli']->query( $SQL );
				
				if( $status ) {
					
					/* 
						Assign a role to the new user!;
					*/
					
					roles::user( uss::$global['mysqli']->insert_id )::assign( uss::$global['options']->get('user:default-role') );
					
					$message = "<i class='bi bi-check-circle text-success me-1'></i> Your registration was successful";
					
					/*
						Send verification email;
					*/
					
					$confirm = !empty( uss::$global['options']->get('user:confirm-email') );
					
					if( $confirm ) {
						
						$sent = dashboard::call( 'email:confirm_user_email', $data['email'] );
						
						$className = 'mt-3 pt-3 border-top fs-14px';
						
						if( $sent ) {
							
							$message .= "
								<div class='{$className} text-success'> 
									Please confirm the link sent to your email
								</div>
							";
							
						} else {
							
							$message .= "
								<div class='{$className} text-danger'> 
									Email confirmation link failed to send. <br> Try requesting for a new link in the login form
								</div>
							";
						
						};
						
					};
				
					# ------- [ End Email Verification ] -----------
					
				} else $message = "<i class='bi bi-x-circle text-danger me-1'></i> The registration was not successful";
			
			}
			
		}
		
	};
	
	/*
		Send the output
	*/
	
	uss::stop( $status, $message, array( 'redirect' => $loginPage ) );
	
});

