<?php 

defined("DASHBOARD_MOD_DIR") OR DIE;

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	$prefix = DB_TABLE_PREFIX;
	
	$message = null;
	
	if( ($_POST['nonce'] ?? null) === uss::nonce( $nonce_key ) ) {
	
		switch( $_POST['form'] ) {
			
			case 'profile':
					
					try {
						
						$avatar = dashboard::call( 'upload_image', $_FILES['avatar'], 'profile' );
						
						/*
							Email may be empty if input field is disabled!
							Hence, to avoid error, we have to refill it with the user input!
						*/
						
						if( !isset($_POST['email']) ) $_POST['email'] = uss::$global['user']['email'];
						
						
						/*
							Test for email validity;
						*/
						
						$valid_mail = preg_match( core::regex('email'), $_POST['email'] );
						
						
						/*
							If E-Mail is valid!
						*/
						
						if( $valid_mail ) {
							
							$_POST['email'] = strtolower( $_POST['email'] );
							
							$_POST['email'] = uss::$global['mysqli']->real_escape_string( $_POST['email'] );
							
							/*
								- It's great when a user verifies their email after signup
								- Because it shows that the user email is not some sort or formulated trash
								- However, after the login process, a user may decide to change email to `fake@email.com`
								- Probably to aviod receiving email such as subscription messages, notification etc
								
								- To avoid unwanted email, the user has to reconfirm that the new email is correct!
								- Hence, it's a recommeded setting to force user email reconfirmation!
							*/
							
							$reconfirm = !empty(uss::$global['options']->get( 'user:reconfirm-email' ));
							
							if( !$reconfirm || uss::$global['user']['email'] == $_POST['email'] ) {
									
								$SQL = sQuery::update( "{$prefix}_users", array(
									'email' => $_POST['email']
								), "id = " . uss::$global['user']['id'] );
								
								$update = uss::$global['mysqli']->query( $SQL );
								
								if( $update ) {
									
									$message = "<i class='bi bi-check-circle text-success me-1'></i> Profile Updated";
									
									/* 
										Remove the email update key if it exists 
									*/
									
									foreach( ['v-code:update', 'v-code:email'] as $key ) 
										uss::$global['usermeta']->remove( $key, uss::$global['user']['id'] );
										
									uss::$global['user']['email'] = $_POST['email'];
									
								} else $message = "<i class='bi bi-shield-lock text-danger me-1'></i> Profile not updated";
							
							} else {
								
								/*
									dashboard::call( 'email:confirm_user_email', $new_email, $old_email );
								*/
								
								$update = dashboard::call( 'email:confirm_user_email', $_POST['email'], uss::$global['user']['email'] );
								
								if( $update )
									$message = "
										<i class='bi bi-check-circle text-success me-1'></i> 
										Please click the link sent to your email to complete the update
									";
								else $message = "<i class='bi bi-shield-lock text-danger me-1'></i> Profile not updated";
								
							};
							
							if( !empty($avatar) )  uss::$global['usermeta']->set('avatar', $avatar, uss::$global['user']['id']);
						
						} else $message = "Invalid email address";
						
						/*
							What will a module do?!
						*/
						
						events::exec('dashboard.account::post.profile', array( 'message' => &$message ) );
						
					} catch( Exception $e ) {
						// catch from image upload;
						uss::console( ':alert', $e->getMessage() );
					};
					
				break;
				
			
			case 'password':
					
					$approved = password_verify( $_POST['old_password'], uss::$global['user']['password'] );
					
					if( !$approved ) {
						
						$message = '<i class="bi bi-exclamation-triangle me-1"></i> Old password is wrong';
						
					} elseif( $_POST['password'] !== $_POST['confirm_password'] ) {
						
						$message = "<i class='bi bi-exclamation-triangle me-1'></i> Password does not match";
						
					} else {
						
						$SQL = sQuery::update( "{$prefix}_users", array( 
							'password' => password_hash( $_POST['password'], PASSWORD_DEFAULT )
						), "id = " . uss::$global['user']['id'] );
						
						$update = uss::$global['mysqli']->query( $SQL );
						
						if( $update ) {
							$message = "<i class='bi bi-lock me-1'></i> Password successfully updated";
						} else $message = "<i class='bi bi-exclamation-triangle'></i> Password update failed";
						
					}
			
				break;
				
				
			default:
			
				events::exec('dashboard.account::post.custom');
				
		};
	
	} else $message = "<i class='bi bi-shield me-1'></i> Security check failed";
	
	// :alert 
	
	uss::console( ':alert', $message );
	
	// prevent browser resubmit dialog;
	
	dashboard::call( 'form:prevent-resubmit' );
	
};