<?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':
				
						$selfcap = dashboard::call( 'user:has-role', null, uss::$global['user']['id'] );
						
						$deleted = array();
						
						foreach( $_POST['bulk_values'] as $userid ) {
							$usercap = dashboard::call('user:has-role', null, $userid );
							if( $usercap < $selfcap ) $deleted[] = dashboard::call( 'user:delete', $userid );
						};
						
						$message = "<i class='fas fa-trash-alt 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/users/list::post:bulk' );
				
			}
			
		};
		
	} else {
		
		// ----------- [{ For Singular Actions }] ----------
		
		if( isset($_POST['action']) && $_POST['action'] == 'delete' ) {
			
			$userid = $_POST['userid'];
			
			$selfcap = dashboard::call('user:has-role', null, uss::$global['user']['id']);
			$usercap = dashboard::call('user:has-role', null, $userid);
			
			if( $usercap < $selfcap ) {
				
				$status = dashboard::call( 'user:delete', $userid );
				
				if( $status ) {
					$message = "<i class='mdi mdi-account-remove fs-1_5rem me-1'></i> &mdash; Account deleted successfully";
				} else {
					$message = "<i class='lni lni-close  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-1_5rem me-1'></i> &mdash; You can neither delete your account nor a highly authorized account." );
			}
			
		} else {
			
			events::exec( 'admin/users/list::post:single' );
			
		}
		
	}
	
};