<?php 

class grading {

	public $grades;
	public $rating_key;
	public $mode_of_scoring;

	public function __construct() {
		$this->grades = get_option('grades');
		$this->rating_key = get_option('rating_key');
		$this->mode_of_scoring = get_option('mode_of_scoring');
		$this->split_grades();
		$this->split_rating();
		$this->split_mode_of_scoring();
	}

	private function split_grades() {
		$res = [];
		foreach ($this->grades as $grade) {
			$res[] = $this->trim_array(explode(',', $grade), ['grade', 'min', 'max', 'description']);
		}
		$this->grades = $res;
	}

	private function split_rating() {
		$res = [];
		foreach ($this->rating_key as $rating) {
			$res[] = $this->trim_array(explode(',', $rating), ['rating', 'description']);
		}
		$this->rating_key = $res;
	}

	private function split_mode_of_scoring() {
		$res = [];
		foreach ($this->mode_of_scoring as $mode) {
			$res[] = $this->trim_array(explode(',', $mode), ['mode_of_scoring', 'max']);
		}
		$this->mode_of_scoring = $res;
	}

	private function trim_array($input, $key_tags) {
		$res = [];
		if(_count($input) > 0) {
			foreach ($input as $key => $value) {
				if(isset($key_tags[$key])) {
					$res[$key_tags[$key]] = trim($value);
				} else {
					continue;
				}
			}
		}
		return $res;
	}

	public function get_grades() {
		return $this->grades;
	}

	public function get_ratings() {
		return $this->rating_key;
	}

	public function get_mode_of_scoring() {
		return $this->mode_of_scoring;
	}

	public function root_mode_of_scoring() {
		$output = [];
		foreach ($this->mode_of_scoring as $key => $value) {
			$output[$value['mode_of_scoring']] = $value;
		}
		$this->mode_of_scoring = $output;
	}

	public function get_rating($rate) {
		foreach ($this->rating_key as $rating) {
			if($rate == $rating['rating']) {
				return $rating;
			}
		}
		return ['rating' => (string) $rate, 'description' => 'Not Available'];
	}

	public function get_grade($score) {
		foreach ($this->grades as $grade) {
			if($score == 0) {
				return ['grade' => '-', 'description' => '-'];
			}
			if($score >= $grade['min'] && $score <= $grade['max']) {
				return $grade;
			}
		}
		return ['grade' => 'NA', 'description' => 'Not Available'];
	}

}