<?php 

// Set HREF Location;

$LOCATION =  PANEL_URI . '/solutions';

// Set Page Menu;

uss::$global['menu']->add('solution', array(
	'label' => 'Solutions',
	'href' => core::url( ROOT_DIR . "/{$LOCATION}" ),
	'icon' => "<i class='bi bi-check2-circle'></i>",
	'active' => $_GET['query'] == $LOCATION
));


// Create Page Exams;

uss::focus( $LOCATION, function() {
	
	$prefix = DB_TABLE_PREFIX;
	
	if( isset($_GET['delete']) ) {
		$id = (int)($_GET['delete']);
		$SQL = "DELETE FROM {$prefix}_portals WHERE id = {$id}";
		uss::$global['mysqli']->query( $SQL );
	};
	
	$SQL = "
		SELECT 
		
			{$prefix}_portals.*,
			{$prefix}_users.email,
			COUNT( {$prefix}_solutions.id ) AS answered
		
		FROM (
			SELECT 
				{$prefix}_portals.*, 
					COUNT( {$prefix}_questions.id ) as questions
			FROM {$prefix}_portals
			INNER JOIN {$prefix}_exams
				ON {$prefix}_exams.portal = {$prefix}_portals.portal_id
			LEFT JOIN {$prefix}_questions
				ON {$prefix}_questions.exam_id = {$prefix}_exams.id
			GROUP BY {$prefix}_portals.portal_id, {$prefix}_portals.userid
		) AS {$prefix}_portals
		
		INNER JOIN {$prefix}_users
			ON {$prefix}_portals.userid = {$prefix}_users.id
			
		LEFT JOIN {$prefix}_solutions
			ON {$prefix}_portals.id = {$prefix}_solutions.portal_id
		
		GROUP BY {$prefix}_solutions.portal_id, {$prefix}_solutions.student_id
	";
	
	$result = uss::$global['mysqli']->query( $SQL );
	
	$table = new DOMTablet( 'solved' );
	$table->data( $result );
	$table->columns(array(
		"portal_id" => "portal",
		"email",
		"questions",
		"answered",
		"score",
		"rate",
		"complete" => 'status',
		"delete" => ''
	));
	
	dashboard::view(function() use($table) { ?>
	
		<div class='container-fluid'>
			<div class='row'>
			
				<div class='col-lg-12'>
					<div class='card'>
						<div class='card-body'>
						
							<?php 
							
								echo $table->prepare(function($data) {
									
									$score = cbt::getScores( $data['id'], $data['userid'] );
									
									$data['score'] = "
										<div class='text-nowrap'>
										{$score['score']} / {$score['grade']['points']}
										</div>
									";
									
									$data['rate'] = $score['grade']['percent'] . '%';
									
									if( !empty($data['complete']) ) {
										$value = "<i class='fas fa-check-circle text-success me-1'></i> Answered";
									} else {
										$value = "<i class='fas fa-times-circle text-danger me-1'></i> Answering";
									};
									
									$data['complete'] = "<span class='text-nowrap'>{$value}</span>";
									
									$data['delete'] = "
										<a href='?delete={$data['id']}' class='btn btn-danger' data-uss-confirm='Wait a minute... <br> This will delete the user answers. Do you want to proceed?' data-uss-btn='No,Yes'>
											<i class='bi bi-trash'></i>
										</a>";
									
									return $data;
									
								}); 
								
							?>
						
						</div>
					</div>
				</div>
			
			</div>
		</div>
	
	<?php });
	
});