<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST'  && $exam ) {
	
	$prefix = DB_TABLE_PREFIX;
	
	$folder = "exam-{$exam['id']}";
	
	if( !empty($_POST['clear-image']) ) $_POST['question']['image'] = null;
	else {
		$image = dashboard::call('upload_image', $_FILES['image'], $folder );
		if( $image ) $_POST['question']['image'] = $image;
	};
	
	$_POST = core::sanitize( $_POST, array( uss::$global['mysqli'], 'real_escape_string' ) );
	
	if( empty($_POST['id']) ) {
		
		$SQL = sQuery::insert( "{$prefix}_questions", $_POST['question'] );
		$type = 'added';
		
	} else {
		
		$SQL = sQuery::update( "{$prefix}_questions", $_POST['question'], "id = '{$_POST['id']}'" );
		$type = 'updated';
		
	};
	
	$invoke = uss::$global['mysqli']->query( $SQL );
	
	if( $invoke ) {
		$message = sprintf( 
			"The question was successfully %s. <br> Add a new question or <a href='./manager?id={$exam['id']}'>Return to the exam</a>", 
			$type 
		);
		$color = 'success';
	} else {
		$message = sprintf( "The question was not %s, please try again!", $type );
		$color = 'danger';
	};
	
	events::addListener('exam-question', function() use($message, $color) {
		echo "<div class='alert alert-{$color} text-center text-sm'>
			{$message}
		</div>";
	});
	
};