<?php 

require __DIR__ . '/config.php';

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	$portal = cbt::getClientPortal( $_SESSION['portal'], uss::$global['user']['id'] );
	
	$prefix = DB_TABLE_PREFIX;
	
	if( empty($portal['complete']) ) {
			
		foreach( $_POST as $qid => $info ) {
			
			$epoch = $info['epoch'];
			if( empty($info['answer']) ) $info['answer'] = 0;
			
			$data = array(
				"portal_id" => $portal['id'],
				"student_id" => uss::$global['user']['id'],
				"question_id" => $qid,
				"epoch" => "{$epoch['hour']}.{$epoch['minute']}.{$epoch['second']}",
				"answer" => $info['answer']
			);
			
			$TERMS_AND_CONDITION = "
				student_id = '{$data['student_id']}'
				AND portal_id = '{$data['portal_id']}'
				AND question_id = '{$data['question_id']}'
			";
					
			$TEST = "
				SELECT * FROM {$prefix}_solutions
				WHERE $TERMS_AND_CONDITION
			";
			
			$result = uss::$global['mysqli']->query( $TEST );
			
			if( !$result->num_rows ) {
				
				$SQL = sQuery::insert( "{$prefix}_solutions", $data );
				
			} else {
				
				$solution = array( 'epoch' => $data['epoch'] );
				
				// Trail;
				
				$TEST2 = $TEST . "AND answer = '{$data['answer']}'";
				
				$result = uss::$global['mysqli']->query( $TEST2 );
				
				// If no related answer and submitted answer is not zero;
				
				if( !$result->num_rows && !empty($data['answer']) ) {
					// update answer;
					$solution["answer"] = $data['answer'];
				};
				
				$SQL = sQuery::update( "{$prefix}_solutions", $solution, $TERMS_AND_CONDITION );
				
			};
			
			if( $SQL ) $update = uss::$global['mysqli']->query( $SQL );
		
		}
	
	};
	
}