<?php 

defined( 'ADMIN_MOD_DIR' ) OR DIE;

/*
	Add a menu to the list!
*/

uss::$global['menu']->get( $menu_title )->add('list', array(
	'label' => 'All users',
	'href' => core::url( ROOT_DIR . '/' . ADMIN_FOCUS_URI . '/users' )
));


uss::focus( ADMIN_FOCUS_URI . '/users', function() use($menu_title) {
	
	// Activate the menu!
	
	uss::$global['menu']->get( $menu_title )->get('list')->set_attr('active', true);
	
	
	// Handle _POST request!
	
	require __DIR__ . '/POST/user-list.php';
	
	
	/*
		Prepare MYSQLI Query!
		The query can be altered by a module based on search key!
	*/
	
	$prefix = DB_TABLE_PREFIX;
	
	$SQL = sQuery::select( "{$prefix}_users", "1 ORDER BY id DESC");
	
	
	/*
		Prepare The DOMTablet
		Which is an extension of the DOMTable class
	*/
	
	$table = new DOMTablet( 'users' );
	
	
	/*
		Create An Event to update the SQL Query;
	*/
	
	events::addListener('admin.user-list::QUERY', function($data) use($prefix) {
		
		if( empty($_GET['search']) ) return;
		
		$search = uss::$global['mysqli']->real_escape_string( $_GET['search'] );
		
		$uss_users = $prefix . '_users';
		
		$data['SQL'] = "
			SELECT {$uss_users}.*
			FROM {$uss_users}
			LEFT JOIN (
				SELECT * FROM {$prefix}_usermeta
				WHERE _key = 'roles'
			) as usermeta_alt
			ON {$uss_users}.id = usermeta_alt._ref
			WHERE
				{$uss_users}.email LIKE '%{$search}%' 
				OR {$uss_users}.username LIKE '%{$search}%'
				OR {$uss_users}.usercode LIKE '%{$search}%'
				OR usermeta_alt._value LIKE '%{$search}%'
			ORDER BY {$uss_users}.id DESC
		";
		
	}, EVENT_FLOAT );
	
	
	/*
		Create an event to establish DOMTable with the SQL Query
	*/
	
	events::addListener('admin.user-list::QUERY', function($data) {
		
		// ------ [{ Proceed }] -------
		
		$result = uss::$global['mysqli']->query( $data['SQL'] );
		
		$table = &$data['table'];
		
		// --- [{ Get DOMTablet Object }] ---
		
		$table->data( $result );
		
		$columns = array(
			'email',
			'confirmed',
			'role' => "role",
			'usercode' => 'code',
			'action' => ''
		);
		
		if( !empty(uss::$global['options']->get('user:collect-username')) ) array_unshift($columns, 'username');
		
		
		$table->columns($columns);
		
		$table->wrap();
		
		$table->widget('search', true);
		
		$table->widget('bulk', array(
			'delete' => 'delete'
		), 'id');
	
	}, EVENT_FLOAT + 0.1 );
	
	
	// -------- [{ Allow Module Change }] -----
	
	events::exec('admin.user-list::QUERY', array(
		'table' => &$table,
		'SQL' => &$SQL
	));
	
	
	/*
		View Admin Panel!
	*/
	
	dashboard::view(function() use( &$table ) {
		
	?>
		
		<?php 
			events::addListener('admin.user-list::dropdown', function($data) { 
			
				$href = core::url( ROOT_DIR . '/' . ADMIN_FOCUS_URI . "/users/{$data['usercode']}" );
		?>
			<li>
				<a class='dropdown-item' href='<?php echo $href; ?>'>
					<i class='lni lni-user me-1'></i> Edit
				</a>
			</li>
			<li>
				<button class='dropdown-item' name='action' value='delete'>
					<i class='lni lni-close me-1'></i> Delete
				</button>
			</li>
		<?php }); ?>
		
		<div class='container-fluid'>
			<div class='row'>
				<div class='col-lg-12'>
					
					<?php 
						
						$table->prepare(function($data) {
								
							$confirmed = !uss::$global['usermeta']->get('v-code', $data['id']);
							
							$icon = !$confirmed ? 'mdi mdi-alert-remove-outline text-danger' : call_user_func(function() use($data) {
								if( uss::$global['user']['id'] !== $data['id'] ) {
									return 'mdi mdi-checkbox-marked-circle-outline text-primary';
								} else return 'mdi mdi-account-reactivate text-success';
							});
							
							$data['confirmed'] = "<i class='{$icon} fs-24px'></i>";
							
							$data['role'] = call_user_func(function($userid) {
								
								$value = roles::user( $userid )::authority( true );
								
								if( empty($value) ) return '<i class="bi bi-question-circle"></i>';
								
								if( roles::user( $userid )::is( 'blocked' ) ) {
									$color = 'bg-warning';
									$prepend = "<span class='text-danger'>!</span>";
								} else {
									$color = 'bg-secondary';
									$prepend = null;
								};
								
								$badge = "{$prepend} <span class='badge {$color} bg-opacity-50 rounded-3 fw-normal'>{$value}</span>";
								
								return $badge;
								
							}, $data['id']);
							
							$data['action'] = "
							
								<form method='POST' data-uss-confirm='You are about making changes to the user data'>
								
									<input type='hidden' name='userid' value='{$data['id']}'>
									
									<div class='dropstart'>
										
										<a href='javascript:void(0)' class='inline-block p-2' type='button' data-bs-toggle='dropdown' aria-expanded='false'>
											<i class='lni lni-flickr'></i>
										</a>
										
										<ul class='dropdown-menu text-sm'>
							";
								
								// buffer output
								ob_start();
								
								events::exec( 'admin.user-list::dropdown', $data, true );
								
								$data['action'] .= ob_get_clean(); // save buffer
								
							"			</ul>
							
									</div>
									
								<form>
							";
							
							
							// ----- [{ Allow Module Change }] -------
							
							events::exec( 'admin.user-list::table', array( 'data' => &$data ) );
							
							if( array_key_exists('username', $data) ) {
								$data['username'] = trim($data['username']);
								if( empty($data['username']) ) $data['username'] = "<i class='bi bi-exclamation-circle text-muted'></i>";
							};
							
							return $data;
							
						}, true); 
						
					?>

				</div>
			</div>
		</div>
		
	<?php });
	
});