<?php 

( defined( "DASHBOARD_MOD_DIR" ) && !empty($_POST['login']) ) OR DIE;

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

call_user_func(function() {
	
	$status = false;
	
	
	// Ride the input off any SQL injection!
	
	$prefix = DB_TABLE_PREFIX;
	
	$_POST['login'] = uss::$global['mysqli']->real_escape_string($_POST['login']);
	
	
	// Confirm the type of login input!
	
	$column = preg_match( core::regex('email'), $_POST['login'] ) ? 'email' : 'username';
	
	
	// Use the input to fetch the user!
	
	$user = dashboard::fetch_assoc( "{$prefix}_users", $_POST['login'], $column );
	
	if( !$user ) {
		
		$message = "The login credential is incorrect";

	} else {
		
		// Verify the user password!
		
		$password = password_verify( $_POST['password'], $user['password'] );
		
		/*
			INCASE OF LOST PASSWORD!
			Where admin need to personally update the PHPMYADMIN Table to regain access
		*/
		
		$password_alt = HASH('SHA256', $_POST['password']) === $user['password'];
		
		if( !$password && !$password_alt ) {
			
			$message = 'The login credential is incorrect';
			
		} else {
			
			/*
				Check if email is verified;
				Hence, no v-code must exist!
			*/
			
			$vcode = uss::$global['usermeta']->get('v-code', $user['id']);

			if( $vcode ) $message = "Please confirm your email address to proceed!";

			else {
				
				// login;
				
				$TOKEN = $user['usercode'] . $user['id'];
				
				$_SESSION['access_token'] = HASH( 'SHA256', $TOKEN );
				
				$status = !!( $message = "<i class='bi bi-check-circle text-success me-1'></i> Login successful" );
				
			};
		
		};
			
		/*
			Assign default role to the user!
			If no role exists
		*/
		
		if( empty( roles::user( $user['id'] )::get_user_roles() ) ) {
			roles::user( $user['id'] )::assign( uss::$global['options']->get('user:default-role') );
		};
		
	};
	
	
	/*
	
	*/
	
	uss::stop( $status, $message );

});
