<?php 

require __DIR__ . '/config.php';

$prefix = DB_TABLE_PREFIX;

$SQL = "
	SELECT 
	
		{$prefix}_questions.*,
			{$prefix}_subjects.name as subject,
				{$prefix}_solutions.answer AS selected
				
	FROM {$prefix}_portals
	
	INNER JOIN {$prefix}_exams
		ON {$prefix}_portals.portal_id = {$prefix}_exams.portal
		
	INNER JOIN {$prefix}_departments
		ON {$prefix}_departments.id = {$prefix}_exams.department_id
		
	LEFT JOIN {$prefix}_questions
		ON {$prefix}_questions.exam_id = {$prefix}_exams.id
			
	LEFT JOIN {$prefix}_solutions
		ON (
		    {$prefix}_solutions.question_id = {$prefix}_questions.id
		    AND {$prefix}_solutions.portal_id = {$prefix}_portals.id  
		 )
		
	INNER JOIN {$prefix}_subjects
		ON {$prefix}_questions.subject_id = {$prefix}_subjects.id
		
	WHERE 
		{$prefix}_exams.status = 1
		AND {$prefix}_portals.id = {$_SESSION['portal']}
		ORDER BY RAND()
";

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

$data = array();

if( $results->num_rows ) {
	
	while( $result = $results->fetch_assoc() ) {
	    
		// convert subject to key;
		$key = $result['subject'];
		if( !isset($data[$key]) ) $data[ $key ] = array();
		
		// unset secret keys;
		$unset = ['correct', 'subject', 'subject_id', 'exam_id', 'period'];
		foreach( $unset as $index ) unset($result[ $index ]);
		
		// get question image;
		if( !empty($result['image']) ) 
			$result['image'] = core::url( DASHBOARD_MOD_DIR . "/assets/images/{$result['image']}" );
		
		// prepare question;
		$data[$key][] = $result;
		
	};
	
};

$string = base64_encode( json_encode($data) );

$portal = cbt::getClientPortal( $_SESSION['portal'], uss::$global['user']['id'] );

$epoch = !empty($portal['epoch']) ? $portal['epoch'] : $portal['exam_time'];

uss::stop(false, null, array(
	'questions' => $string, 
	'time' => cbt::timer($epoch)
));


