<?php 

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	$prefix = DB_TABLE_PREFIX;
	
	if( (int)$_POST['_from'] >= (int)$_POST['_to'] ) {
		
		$status = !( $message = "Invalid grade format! <br> <strong>From</strong> cannot be equal or greater than <strong>To</strong>" );
		
	} else {
		
		$_POST['_type'] = strtoupper( $_POST['_type'] );
		$_POST['_name'] = ucwords( $_POST['_name'] );
		
		if( $_POST['id'] ?? null ) {
			
			$SQL = sQuery::update( "{$prefix}_grades", $_POST, "id = {$_POST['id']}" , uss::$global['mysqli'] );
			
			$status = uss::$global['mysqli']->query( $SQL );
			
			$type = 'updated';
			
		} else {
			
			$SQL = sQuery::insert( "{$prefix}_grades", $_POST, uss::$global['mysqli'] );
			
			$status = uss::$global['mysqli']->query( $SQL );
			
			$type = 'added';
			
		};
		
	}
	
	if( empty($message) ) {
		if( $status ) 
			$message = "<i class='mdi mdi-check text-success me-1'></i> The grade has been successfully %s <br> <a href='../grades'>Go Back</a>";
		else {
			$message = "<i class='mdi mdi-alert-outline text-danger me-1'></i> The grade was not %s";
		};
	};
	
	$message = sprintf( $message, $type ?? null );
	
	events::addListener('--alert', function() use($message, $status) {
		$status = $status ? "success" : "danger";
		echo "
			<div class='alert alert-{$status} text-center text-sm'>
				{$message}
			</div>
		";
	});
	
};


if( isset($_GET['delete']) ) {
	
	$grade = dashboard::fetch_assoc( "{$prefix}_grades", $_GET['delete'] );
	
	if( $grade ) {
		
		$SQL = "DELETE FROM {$prefix}_grades WHERE id = {$grade['id']}";
		
		$result = uss::$global['mysqli']->query( $SQL );
		
		if( $result ) uss::console( ':alert', "The grade was successfully deleted" );
		else uss::console( ':alert', "Error! The grade was not deleted" );
		
	};
	
};

