<?php 

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

call_user_func(function() {
	

	$prefix = DB_TABLE_PREFIX;
	
	$_POST['login'] = uss::$global['mysqli']->real_escape_string($_POST['login']);
	
	$column = preg_match( core::regex('email'), $_POST['login'] ) ? 'email' : 'username';
	
	
	// get user;

	$SQL = sQuery::select( "{$prefix}_users", "{$column} = '{$_POST['login']}' AND password = '{$_POST['password']}'" );

	$user = uss::$global['mysqli']->query( $SQL )->fetch_assoc();
	
	if( !$user ) {
		
		$message = "The login credential is incorrect";

	} else {
		
		// check email verification;

		$vcode = uss::$global['usermeta']->get('v-code', $user['id']);

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

		else {
			
			// login;

			$_SESSION['access_token'] = core::keygen(10, true);

			$SQL = sQuery::update( "{$prefix}_users", array( 
				"access_token" => uss::$global['mysqli']->real_escape_string( $_SESSION['access_token'] )
			), "id = {$user['id']}" );

			uss::$global['status'] = $status = uss::$global['mysqli']->query( $SQL );

			if( $status ) {
				
				$message = "<i class='fas fa-check text-success me-1'></i> Login successful";
				
				if( !empty($_POST['remember']) ) {
					$encrypt = sha1( $_SERVER['HTTP_USER_AGENT'] . $_COOKIE['ussid'] ) . ":" . sha1( $_SESSION['access_token'] );
					$approved = setrawcookie( 'uss-client', $encrypt, (time() + (86400 * 14)), '/' );
				};
				
			} else {
				$message = "
					Login process failed <br> 
					Please try again or contact the support team
				";
			}
		
		};
		
		// Assign default role if none exists;
		
		dashboard::call('user:assign-role', $user['id']);
		
	};
	
	uss::$global['message'] = $message;

});
