<?php defined( 'ADMIN_MOD_DIR' ) OR DIE;

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	if( $_POST['nonce'] !== uss::nonce( 'user-new' ) ) uss::console( ':alert', "Security Check Failed" );
	
	else {
		
		// Trim all inputs;
		
		$_POST = core::sanitize($_POST, 'trim');
		
		
		// Generate New User Code;
		
		$_POST['user']['usercode'] = core::keygen(6);
		
		
		// Case Insensitive Email
		
		$_POST['user']['email'] = strtolower($_POST['user']['email']);
		
		
		// Case Insensitive Username;
		
		if( empty($_POST['user']['username']) ) {
			$_POST['user']['username'] = null;
		} else $_POST['user']['username'] = strtolower($_POST['user']['username']);
		
		
		// Prepare User Image;
		
		$image = dashboard::call( 'upload_image', $_FILES['avatar'], 'profile' );
		
		if( $image ) $_POST['meta'] = array( 'avatar' => $image );
		
		
		
		// --------- [ Create an event @ users/new::post ] ------------
		
		events::addListener('admin/users/new::post', function() {
			
			$progress = [];
			
			// Validate Username & Email;
			
			$validation = array(
				"username" => [ "/^\w+$/i", "Invalid Username" ],
				"email" => [ core::regex('email', true), "Invalid Email Address" ]
			);
			
			foreach( $validation as $key => $data ) {
				if( empty($_POST['user'][$key]) ) continue;
				if( !preg_match( $data[0], $_POST['user'][$key] ) ) {
					$progress[] = false;
					uss::console( ":toastr.error.{$key}", $data[1] );
				};
			};
			
			
			// Check For errors;
			
			if( !in_array(false, $progress) ) {
			
			
				$prefix = DB_TABLE_PREFIX;
				
				
				// encrypt password;
				
				$_POST['user']['password'] = dashboard::call('encrypt:password', $_POST['user']['password'] );
				
				
				// Insert user to database;
				
				$SQL = sQuery::insert( "{$prefix}_users", $_POST['user'], uss::$global['mysqli'] );
				
				$progress[] = $status = uss::$global['mysqli']->query( $SQL );
				
				
				// If insertion was successful;
				
				if( $status ) {
					
					$userid = uss::$global['mysqli']->insert_id;
					
					// Add the user meta detail;
					
					foreach( $_POST['meta'] as $key => $value ) {
							$progress[] = uss::$global['usermeta']->set( $key, $value, $userid );
					};
					
					// Prepare Default Role;
					
					dashboard::call( 'user:assign-role', $userid, uss::$global['options']->get('user:default-role') );
					
					if( !empty($_POST['notify-user']) ) {
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
						# SEND NOTIFICATION;
					};
					
				} else {
					
					// Deliver some error notification;
					
					foreach( ['email', 'username'] as $key ) {
						if( empty($_POST['user'][$key]) ) continue;
						$exists = dashboard::fetch_assoc( "{$prefix}_users", $_POST['user'][$key], $key );
						if( $exists ) uss::console( ":toastr.error.{$key}", "The {$key} already exists" );
					};
					
				};
			
			};
			
			
			// Final Check For Errors;
			
			uss::$global['status'] = !in_array(false, $progress);
			
			
			// Display an alert message;
			
			events::addListener( 'admin/users/new@form::above', function() {
				
				$type = uss::$global['status'] ? 'success' : 'danger';
				
				if($type == 'success') {
					
					$href = core::url( ROOT_DIR . '/' . ADMIN_FOCUS_URI . "/users/{$_POST['user']['usercode']}" );
					
					uss::$global['message'] = "
						<div class='d-flex'>
							<i class='mdi mdi-account-check fs-1_5rem me-2'></i> 
							<div> 
								The user account was successfully added. <br>
								<a href='{$href}'>Click here</a> to manage the user account
							</div>
						</div>
					";
					
				} else {
					
					uss::$global['message'] = "
						<div class='d-flex'>
							<i class='mdi mdi-account-question fs-1_5rem me-2'></i> 
							<div>It seems an error occured</div>
						</div>
					";
					
				};
				
				$message = uss::$global['message'];
				
				echo "<div class='alert alert-{$type} mb-4 text-sm'>{$message}</div>";
				
			}, EVENT_FLOAT );
			
			
		}, EVENT_FLOAT ); // [ end event @ users/new::post ] 
		
		
		
		# ------------- [ event ] ------------
		
		events::exec( 'admin/users/new::post' );
		
		
	};
	
};