<?php 

defined( "DASHBOARD_MOD_DIR" ) OR DIE;

call_user_func(function() {
	
	
	$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 none of the above conditions are met, the user detail are correctly inputed;
				
				$data = array(
					"email" => $_POST['email'],
					"password" => $_POST['password'],
					"username" => $username,
					"usercode" => core::keygen(6)
				);
				
				
				// Insert into database;
				
				$SQL = sQuery::insert( "{$prefix}_users", $data, uss::$global['mysqli'] );
				
				$status = uss::$global['mysqli']->query( $SQL );
				
				if( $status ) {
					
					$user = dashboard::fetch_assoc( "{$prefix}_users", $data['usercode'], 'usercode' );
					
					// assign role;
					
					dashboard::call('user:assign-role', $user['id']);
					
					$message = "<i class='fas fa-check 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'] );
						if( $sent ) {
							$message .= "<br>Please confirm the link sent to your email";
						} else $message .= "<br>Email confirmation link failed to send. Try requesting for a new link in the login form";
					};
				
				} else $message = "<i class='fas fa-times text-danger me-1'></i> The registration was not successful";
			
			}
			
		}
		
	};
	
	/*
		Send the output
	*/
	
	uss::$global['status'] = $status;
	uss::$global['message'] = $message;
	uss::$global['data'] = [ core::url( ROOT_DIR . '/' . DASHBOARD_FOCUS_URI ) ];

});