<?php 

defined( 'ADMIN_FOCUS_URI' ) OR DIE;

uss::focus( ADMIN_FOCUS_URI . '/users/\w+', function() use($menu_title) {
	
	//! 
	
	$usercode = uss::query(2);
	
	if( $usercode === 'new' ) return;
	
	
	//! Keep the list menu active
	
	uss::$global['menu']->get( $menu_title )->get('list')->set_attr('active', true);
	
	$prefix = DB_TABLE_PREFIX;
	
	
	// handel post request if any;
	
	require __DIR__ . '/POST/user-edit.php';
	
	
	// proceed to fetching user detail;
	
	$SQL = sQuery::select( "{$prefix}_users", "usercode = '{$usercode}'" );
	
	$user = uss::$global['mysqli']->query( $SQL )->fetch_assoc();
	
	
	// add javascript codes;
	
	if( $user ) {
		events::addListener('@body::after', function() {
			$src = core::url( ADMIN_MOD_DIR . '/assets/js/user-edit.js' );
			echo "\t<script src='{$src}'></script>\n";
		});
	};
	
	// display the dashboard;
	
	dashboard::view(function() use($user) {
		
		if( empty($user) ) {
			
			dashboard::call('empty:no-result', function() {
				$list = core::url( ROOT_DIR . '/' . ADMIN_FOCUS_URI . '/users' );
				$info = "<p class='mb-2'>It seems the user has been removed</p>";
				$info .= "<a href='{$list}' class='btn btn-primary'>
					<i class='lni lni-users me-1'></i> return to list
				</a>";
				echo $info;
			});
			
			return;
			
		};
		
		/*
			Form name use cases:
			-------- () --------
			user[x] - will update user table
			meta[x] - will update usermeta table
			action[x] - will perform an action based on user
			...[x] - will be executed by custom event;
		*/
		
		$user_permit = roles::user( $user['id'] )::get_user_roles();
		
		$self = ( uss::$global['user']['id'] === $user['id'] );
		
	?>
				
		<div class='container-fluid py-3'>
		
			<div class='d-flex justify-content-between flex-wrap align-items-center user-info'>
				
				<div class='mb-3 mb-sm-0'>
				
					<h5 class='mb-1 fw-semibold'>
						<i class='mdi mdi-account-<?php echo $self ? 'heart' : 'edit'; ?> fs-26px'></i> - 
						<?php if( !empty($user['username']) ) echo $user['username']; ?>
						( <?php echo $user['usercode']; ?> )
					</h5>
					
					<div class='cursor-default text-capitalize'>
						<?php
							foreach( $user_permit as $role ):
								$color = $role == 'blocked' ? 'bg-warning' : 'bg-secondary';
						?>
							<span class='badge <?php echo $color; ?> bg-opacity-50 rounded-4'> 
								<?php echo $role; ?> 
							</span>
						<?php endforeach; ?>
					</div>
					
				</div>
				
				<div class='mx-4'></div>
				
				<div class='fs-12px'>
					<div class='mb-1'> Registered: <span class='text-primary'> <?php echo $user['register_time']; ?> </span> </div>
					<div class='mb-1'> 
						Last Seen: <span class='text-secondary'> 
							<?php echo core::elapse( $user['last_seen'] ); ?> 
						</span> 
					</div>
					<div class='mb-1'> User ID: <span class='text-secondary'> <?php echo $user['id']; ?> </span> </div>
				</div>
			
			</div>
			
			<hr>
			
			<form method='POST' enctype='multipart/form-data'>
				<fieldset>
					
					<div class='user-form-content'>
						<div class='row py-4'>
							
							<?php 
								
								/*
									This content comes first!
								*/
								
								events::exec( 'admin.user-edit-form::before', $user, true );
								
							?>
							
							<div class='col-sm-12 col-md-7 col-lg-8 mb-4'>
							
								<div class='row mb-3'>
									<label class='form-label col-sm-3'>Username:</label>
									<div class='col-sm-9'>
										<input type='text' class='form-control' name='user[username]' value='<?php echo $user['username']; ?>'>
									</div>
								</div>
								
								<div class='row mb-4'>
									<label class='form-label col-sm-3'>Email:</label>
									<div class='col-sm-9'>
									
										<input type='email' required name='user[email]' value='<?php echo $user['email']; ?>' class='form-control'>
										
										<?php if( uss::$global['usermeta']->get('v-code', $user['id']) ): ?>
										<div class='mt-1'>
											<p class='text-danger fs-12px'>
												<i class='mdi mdi-alert-outline me-1'></i> The email has not been confirmed
											</p>
											<div class='form-check text-muted'>
												<input type='checkbox' name='action[confirm]' class='form-check-input' id='email-check'>
												<label class='form-check-label fs-12px' for='email-check'>Confirm account email</label>
											</div>
										</div>
										<?php endif; ?>
										
									</div>
								</div>
				
								<div class='border-top mb-4'></div>
								
								<?php
									events::addListener( 'admin.user-edit-form:col-left', function() use($user) {
								?>
									<div class='text-center d-inline-block mb-2'>
										<div class='user-avatar mb-3'>
											<img src='<?php echo dashboard::call('user:avatar', $user['id']); ?>' class='img-fluid' id='avatar-img'>
										</div>
										<div class='position-relative'>
											<input type='file' accept='.jpg,.png,.gif,.jpeg,.webp' name='avatar' class='form-control d-none' id='avatar-input' data-uss-image-preview='#avatar-img'>
											<button type='button' class='btn btn-outline-primary btn-sm' data-uss-trigger-click='#avatar-input'>
												Change Avatar
											</button>
										</div>
									</div>
								<?php }, 'input-avatar' ); ?>
									
								<?php 
									
									/*
										This is the content
									*/
									
									events::exec( 'admin.user-edit-form:col-left', $user, true ); 
									
								?>
								
							</div>
							
							<div class='col-sm-12 col-md-5 col-lg-4 mb-5'>
								
								<div class='border mb-3 fs-0_9rem rounded-2 overflow-auto card'>
									<div class='bg-light p-2 text-center'>
										<i class='far fa-star text-warning'></i> - Access Control
									</div>
									<div class='p-3'>
											
										<?php 
										
											$roles = array_keys( roles::get() );
											
											foreach( $roles as $role ):
												
												$attrs = array();
												$input = $disabled = null;
												
												$priority = roles::get( $role, 'priority' );
												
												# -----------------------
												
												if( roles::user( $user['id'] )::hasRole($role) ) $attrs['checked'] = 'checked';
												
												# ------------------------
												
												$authority = roles::user( uss::$global['user']['id'] )::maxPriority();
													
												if( $authority < $priority ) $disabled = 'hide';
												else if( $authority === $priority ) {
													$disabled = ($self || !empty($attrs['checked'])) ? 'disabled' : 'hide';
												}
												
												# ------------------------
												
												if( $disabled ) {
													$attrs['disabled'] = 'disabled';
													if( !empty($attrs['checked']) ) {
														$input = "<input type='hidden' name='roles[]' value='{$role}'>";
													};
												};
												
												$capid = "role-{$role}";
										
										?>
										
											<div class='form-check text-capitalize <?php if( $disabled == 'hide' ) echo 'd-none'; ?>'>
												<input type='checkbox' class='form-check-input' name='roles[]' value='<?php echo $role; ?>' id='<?php echo $capid; ?>' <?php echo core::array_to_html_attrs($attrs); ?> data-priv required>
												<label class='form-check-label' for='<?php echo $capid; ?>'><?php echo $role; ?></label>
												<?php echo $input; ?>
											</div>
											
										<?php endforeach; ?>
								
									</div>
								</div>
								
								<div class='border mb-3 fs-0_9rem rounded-2 overflow-auto'>
									<div class='bg-light p-2 text-center'>
										<i class='bi bi-lock'></i> - Change Password
									</div>
									<div class='p-3'>
											
										<input type='text' name='password' class='form-control form-control-sm mb-1' placeholder='New Password'>
								
									</div>
								</div>
								
								<?php 
									events::addListener('admin.user-edit-form:col-right', function() use($user) {
										$userpriv = roles::user( $user['id'] )::authority();
										$selfpriv = roles::user( uss::$global['user']['id'] )::authority();
										if( $userpriv > $selfpriv ) return;
								?>
									
									<div class='mb-3 text-center user-remove-btn border-top py-3'>
										<button type='button' class='btn btn-danger btn-sm d-inline-flex align-items-center justify-content-center w-100' id='delete-account' data-user='<?php echo $user['id']; ?>'>
											<i class='mdi mdi-account-cancel-outline fs-22px me-1'></i> 
											<span>Delete Account</span>
										</button>
									</div>
								<?php }, EVENT_FLOAT ); ?>
								
								<?php events::exec( 'admin.user-edit-form:col-right', $user, true ); ?>
								
							</div>
							
							<?php events::exec( 'admin.user-edit-form::after', $user, true ); ?>
							
							<div class='col-12 border-top pt-3'>
								<div class='row'>
									<div class='col-md-4 col-lg-3'>
										<input type='hidden' name='nonce' value='<?php echo uss::nonce( $user['usercode'] ); ?>'>
										<button class='btn btn-success w-100 d-inline-flex align-items-center justify-content-center'>
											<i class='mdi mdi-account-check fs-22px me-1'></i> 
											<span>Update Account</span>
										</button>
									</div>
								</div>
							</div>
							
						</div>
					</div>
					
				</fieldset>
			</form>

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