<?php require __DIR__ . '/index.php';

// Avoid Bad Request;

if( $_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['nonce']) ) DIE( 'STRICTLY' );


// Confirm Security;

if( $_POST['nonce'] !== uss::nonce( $_SESSION['uss_session_id'] ) ) {
	
	uss::stop( false, "<i class='mdi mdi-shield-off me-1'></i> Security Check Failed" );
	
} else if( empty(uss::$global['user']) ) {
	
	uss::stop( false, "<i class='mdi mdi-account-lock me-1'></i> Account is signed out" );
	
};


// get ready;

$prefix = DB_TABLE_PREFIX;

$_POST['userid'] = uss::$global['mysqli']->real_escape_string( $_POST['userid'] );


// confirm valid userid;

if( !is_numeric($_POST['userid']) ) {
	
	uss::stop( false, "<i class='mdi mdi-account-alert'></i> <br> Invalid account specification" );
	
};


// get the account;

$SQL = sQuery::select( "{$prefix}_users", "id = {$_POST['userid']}" );

$user = uss::$global['mysqli']->query( $SQL )->fetch_assoc();


// confirm account priorities;

if( !$user ) {
	
	uss::stop( false, "<i class='mdi mdi-account-question fs-1_7rem'></i> <br> The account could not be found!" );
	
} else if( $user['id'] == uss::$global['user']['id'] ) {
	
	uss::stop( false, "<i class='mdi mdi-account-heart fs-1_7rem'></i> <br> You cannot delete your own account!" );
	
} else {
	
	if( !roles::user( uss::$global['user']['id'] )::hasPermission( 'manage-users') ) {
		
		uss::stop( false, "<i class='mdi mdi-account-heart fs-1_7rem'></i> <br> You do not have sufficient permission to take this action" );
		
	} else {
		
		$userAuth = roles::user( $user['id'] )::authority();
		$selfAuth = roles::user( uss::$global['user']['id'] )::authority();
		
		if( $userAuth >= $selfAuth ) {
			
			uss::stop( false, "<i class='mdi mdi-account-key fs-1_7rem'></i> <br> You cannot delete an account with greater or same authority as you" );
			
		};
	
	};
	
}


// Delete user;

events::addListener('admin.user::delete', function($user) {
	
	$status = dashboard::call( 'user:delete', $user['id'] );
	
	$msg = [
		"<i class='mdi mdi-account-circle fs-1_7rem'></i> <br> Something went wrong! <br> The account was not deleted",
		"<i class='mdi mdi-account-cancel fs-1_7rem'></i> <br> The account was successfully deleted"
	];
	
	uss::stop( $status, empty($status) ? $msg[0] : $msg[1] );
	
}, EVENT_FLOAT );


events::exec( 'admin.user::delete', $user );


