<?php 

defined( "DASHBOARD_MOD_DIR" ) OR DIE;


isset($_POST['passport']) && isset($_POST['nonce']) OR uss::stop( false, "Intrusive request", null );


call_user_func(function() {
	
	$prefix = DB_TABLE_PREFIX;
	
	if( $_POST['password'] !== $_POST['confirm_password'] ) {
		
		$message = "Password does not match";
		
	} else {
		
		if( $_POST['nonce'] !== uss::nonce( $_SESSION['resetter'] ) ) {
			
			$message = "The request could not be completed! <br> Please contact the support team";
			
		} else {
			
			try {
				
				$passport = explode( "-", str_rot13( base64_decode( $_POST['passport'] ) ) );
				
				$user = dashboard::fetch_assoc( "{$prefix}_users", $passport[1] );
				
				if( !$user ) {
					
					$message = "Authentication detail could not be discovered!";
					
				} else {
					
					$r_code = uss::$global['usermeta']->get( "r-code", $user['id'] );
					
					if( empty($r_code) || $r_code !== $passport[0] ) {
					
						$message = 'Invalid client to server request combination';
						
					} else {
						
						$SQL = sQuery::update( "{$prefix}_users", array(
							"password" => $_POST['password']
						), "id = {$user['id']}" );
						
						if( uss::$global['status'] = uss::$global['mysqli']->query( $SQL ) ) {
							
							uss::$global['usermeta']->remove( 'r-code', $user['id'] );
							
							$message = "Password successfully updated! <br> You can login with you new password now";
							
						} else $message = "Password updated failed";
						
					};
				
				}
			
			} catch(Exception $e ) {
				
				$message = 'Apologies! A critical error occured';
				
			}
		
		}
		
	};
	
	uss::$global['message'] = $message;
	uss::$global['data'] = [ 'redirect' => core::url( ROOT_DIR . '/' . DASHBOARD_FOCUS_URI ) ];

});

