<?php

defined( 'ADMIN_MOD_DIR' ) OR DIE;

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	if( isset($_POST['bulk_table']) && isset($_POST['bulk_nonce']) ) {
		
		// ---------- [{ For Bulk Action Only }] ---------
		
		if( $_POST['bulk_nonce'] !== uss::nonce( "domtablet-{$_POST['bulk_table']}" ) ) {
			
			uss::console( ':alert', "
				<div class='d-flex'>
					<i class='mdi mdi-shield-off me-2'></i>
					<div>
						Security Check Failed! <br>
						Bulk action cannot be applied.
					</div>
				</div>
			" );
			
		} else {
			
			switch( $_POST['bulk_action'] ) {
				
				case 'delete':
				
						$authorized = roles::user( uss::$global['user']['id'] )::hasPermission( 'manage-users' );
						
						if( !$authorized ) {
							uss::console( ':alert', "
								<i class='mdi mdi-lock-off fs-20px me-1'></i> You do not have sufficient permission to execute the request
							" );
							break;
						};
						
						$selfAuth = roles::user( uss::$global['user']['id'] )::authority();
						
						$deleted = array();
						
						foreach( $_POST['bulk_values'] as $userid ) {
							$userAuth = roles::user( $userid )::authority();
							if( $userAuth < $selfAuth ) $deleted[] = dashboard::call( 'user:delete', $userid );
						};
						
						$message = "<i class='bi bi-trash3 me-2'></i> &mdash; ";
						$message .= count($deleted) . " out of " . count( $_POST['bulk_values'] ) . " accounts were deleted";
						
						uss::console( ':alert', $message );
						
					break;
					
				default:
					
					// check if bulk_action matches your request before executing the event;
					
					events::exec( 'admin.user-list::post-bulk' );
				
			}
			
		};
		
	} else {
		
		// ----------- [{ For Singular Actions }] ----------
		
		if( isset($_POST['action']) && $_POST['action'] == 'delete' ) {
			
			$userid = $_POST['userid'];
			
			$selfAuth = roles::user( uss::$global['user']['id'] )::authority();
			$userAuth = roles::user( $userid )::authority();
			
			if( $userAuth < $selfAuth ) {
				
				$status = dashboard::call( 'user:delete', $userid );
				
				if( $status ) {
					$message = "<i class='mdi mdi-account-remove fs-20px me-1'></i> &mdash; Account deleted successfully";
				} else {
					$message = "<i class='lni lni-close fs-20px me-1 text-danger'></i> &mdash; Account could not be deleted";
				};
				
				uss::console( ':alert', $message );
				
			} else {
				uss::console( ':alert', "
					<i class='mdi mdi-account-key fs-20px me-1'></i> &mdash; You can neither delete your account nor a highly authorized account." );
			}
			
		} else {
			
			events::exec( 'admin.user-list::post-single' );
			
		}
		
	}
	
};