<?php 

class ft_comment {
	public $comments;
	public $class;
	public $promotion_order;

	public function __construct() {
		$this->comments = get_option('default_comment');
		$this->split_comments();
	}

	private function split_comments() {
		$res = [];
		foreach ($this->comments as $comment) {
			$res[] = $this->trim_array(explode(',', $comment), ['min', 'max', 'comment']);
		}
		$this->comments = $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_comments() {
		return $this->comments;
	}

	public function get_comment($average) {
		foreach ($this->comments as $comment) {
			if($average >= $comment['min'] && $average <= $comment['max']) {
				return $comment['comment'];
			}
		}
		return 'Fair Performance';//default comment
	}

	public function get_annual_comment($average, $results) {
		if(!isset($this->promotion_order)) {
			$this->promotion_order = db_post_unique(['type' => 'promotion_order', 'class' => $this->class]);
			if($this->promotion_order) {
				$this->promotion_order['condition'] = _unserialize($this->promotion_order['condition']);
			}
		}
		if(!isset($this->grading)) {
			$this->grading = new grading;
		}
		if(!$this->promotion_order) {
			return "Promoted";
		}
		if(round($average) < $this->promotion_order['average']) {
			return "Not Promoted";
		}
		if(_count($this->promotion_order['condition'])) {
			$test = array();
			foreach ($this->promotion_order['condition'] as $course_id => $condition) {
				$grade = $this->grading->get_grade($results[$course_id]['average'])['grade'];
				$grade = strtolower($grade);
				if($condition === "must_pass" && $grade == "f") {
					return "Not Promoted";
				} else {
					$test[$condition][] = $grade; 
				}
			}
			if(isset($test["optional1"])) {
				$check = false;
				foreach ($test["optional1"] as $grade) {
					if($grade != "f") {
						$check = true;
					}
				}
				if(!$check) return "Not Promoted";
			}
			if(isset($test["optional2"])) {
				$check = false;
				foreach ($test["optional2"] as $grade) {
					if($grade != "f") {
						$check = true;
					}
				}
				if(!$check) return "Not Promoted";
			}
			if(isset($test["optional3"])) {
				$check = false;
				foreach ($test["optional3"] as $grade) {
					if($grade != "f") {
						$check = true;
					}
				}
				if(!$check) return "Not Promoted";
			}
		}
		return "Promoted";
	}
}