<?php 

defined( 'ADMIN_MOD_DIR' ) OR DIE;

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	if( $_POST['nonce'] !== uss::nonce( $usercode ) ) 
		
		uss::console( ':alert', "<span class='mdi mdi-shield-off me-1 fs-20px'></span> Account Security Check Failed!" );
	
	else if( !roles::user( uss::$global['user']['id'] )::hasPermission('manage-users') ) {
		
		uss::console( ':alert', "<i class='mdi mdi-lock-off me-1 fs-20px'></i> You do not have the permission to complete the request!" );
		
	} else {
		
		unset($_POST['nonce']);
		
		$SQL = sQuery::select( "{$prefix}_users", "usercode = '{$usercode}'" );
		$user = uss::$global['mysqli']->query( $SQL )->fetch_assoc();
		
		$progress = array();
		
		if( $user ) {
			
			if( isset($_FILES['avatar']) ) {
				
				$upload = dashboard::call( 'upload_image', $_FILES['avatar'], "profile" );
				
				if( $upload ) $_POST['meta']['avatar'] = $upload;
			
			};
			
			// --- manage user data based on division of array keys ---
			
			foreach( $_POST as $key => $data ) {
				
				switch( $key ) {
					
					case 'user':
							
							$data = array_map( array(uss::$global['mysqli'], 'real_escape_string'), $data );
							
							$data['email'] = strtolower($data['email']);
							
							if(empty($data['username'])) {
								$data['username'] = null;
							} else $data['username'] = strtolower($data['username']);
							
							// validate username && password;
							
							$validation = array(
								'username' => "/^\w+$/i",
								'email' => core::regex('email', true)
							);
							
							foreach( $validation as $column => $regex ) {
								if( empty($data[$column]) ) continue;
								$progress[] = $status = preg_match($regex, $data[$column]);
								if( !$status ) uss::console( ":toastr.error.{$column}", "The {$column} is invalid" );
							}
							
							// If no error in validation, proceed:
							
							if( !in_array(false, $progress) ) {
									
								$SQL = sQuery::update( "{$prefix}_users", $data, "usercode = '{$usercode}'" );
								
								$status = uss::$global['mysqli']->query( $SQL );
								$progress[] = $status;
								
								if( !$status ) {
									foreach( ['username', 'email'] as $key ) {
										if( empty($data[$key]) ) continue;
										$SQL = sQuery::select( "{$prefix}_users", "
											{$key} = '{$data[$key]}'
											AND usercode <> '{$usercode}'
										" );
										$error = uss::$global['mysqli']->query( $SQL )->num_rows;
										if( $error ) uss::console( ":toastr.error.{$key}", "The {$key} already exists" );
									};
								};
							
							};
							
						break;
						
					case 'meta':
					
							foreach( $data as $name => $value ) {
								$status = uss::$global['usermeta']->set( $name, $value, $user['id'] );
								$progress[] = $status;
							};
							
						break;
						
					case 'roles':
							
							$roles = roles::user( $user['id'] )::get_user_roles();
							foreach( $roles as $role ) roles::user( $user['id'] )::unassign( $role );
							
							$progress[] = $status = roles::user( $user['id'] )::assign( $data );
							
						break;
						
					case 'password':
					
							$data = trim($data);
							
							if( !empty($data) ) {
								
								$password = password_hash( $data, PASSWORD_DEFAULT );
								
								$SQL = sQuery::update( "{$prefix}_users", array( 'password' => $password ), "usercode = '{$usercode}'" );
								$status = uss::$global['mysqli']->query( $SQL );
								
								events::addListener('admin.user-edit-form::before', function() use($status, $data) {
									
									$data = uss::htmlentities($data);
									
									if( $status ) {
										$message = "<i class='mdi mdi-lock-check fs-1_4rem'></i> Account password changed to &mdash; {$data}";
										$type = 'info';
									} else {
										$message = "<i class='mdi mdi-lock-remove fs-1_4rem'></i> Account password not changed";
										$type = 'danger';
									}
									
									echo "
										<div class='col-12'>
											<div class='alert alert-{$type} text-sm'>{$message}</div>
										</div>
									";
									
								});
								
							};
							
						break;
						
					case 'action':
					
							foreach( $data as $key => $value ) {
								if( $key == 'confirm' ) 
									uss::$global['usermeta']->remove( 'v-code', $user['id'] );
							}
							
						break;
						
					default:
					
						events::exec( "admin.user-edit::post", array(
							"group" => $key,
							"data" => $data,
							"progress" => &$progress
						), true);
					
				};
				
			};
			
			/*
				
			*/
			
			if( in_array(true, $progress) && in_array(false, $progress) ) {
				$type = 'warning';
				$message = "<i class='mdi mdi-alert-circle-check-outline fs-16px'></i> Error occured &mdash; Account updated partially ";
			} elseif( !in_array(false, $progress) ) {
				$type = 'success';
				$message = "<i class='mdi mdi-check-circle-outline fs-16px'></i> Account successfully updated";
			} else {
				$type = 'danger';
				$message = "<i class='mdi mdi-close-outline fs-16px'></i> Account not updated";
			};
			
			events::addListener( 'admin.user-edit-form::before', function() use($type, $message) {
				echo "
					<div class='col-lg-12'>
						<div class='alert alert-{$type} mb-5 text-sm text-capitalize'>
							$message
						</div>
					</div>
				";
			});
		
		};
		
	}
	
};