<?php
/**
 * Evaluate Categories
 * 
 * @author      Helge Nissen <helge.nissen@th-luebeck.de> 
 *              Max Sternitzke <max.sternitzke@th-luebeck.de>
 *              Tim Mallwitz  <tim.mallwitz@th-luebeck.de>
 * 
 * @package     Evaluate Categories
 */

class Trainingssystem_Plugin_Module_Evaluate{


	public function __construct() {

	}

	public function showDragDropCategories($atts){
		
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$formid = (isset($atts['form_id']) && is_numeric($atts['form_id']) && get_post_type($atts['form_id']) == "formulare") ? $atts['form_id'] : null;
		$formData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($formid, Trainingssystem_Plugin_Public::getTrainingUser());
		$data = array();

		foreach($formData as $row){
			foreach($row as $formField){
				if(!empty($formField->getFormdata())){
					$dataFormField = $formField->getFormdata();
					$data[] = trim($dataFormField->getData());
				}
			}
			
		}


		$category_head_colors = array();
		$category_title_colors = array();
		$category_body_colors = array();
		$colorerror = false;

		if(isset($atts['category_head_colors']) && trim($atts['category_head_colors']) != ""){
			$category_head_colors_raw = explode(",", $atts['category_head_colors']);
			foreach($category_head_colors_raw as $c_head_color){
				if(trim($c_head_color) != ""){
					if(preg_match("/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){1}|([a-f]|[A-F]|[0-9]){3}|([a-f]|[A-F]|[0-9]){5})?\b/", $c_head_color)) {
						$category_head_colors[] = $c_head_color;
					}
					else{
						$colorerror = true;
						break;
					}
				}
				else{
					$category_head_colors[] = "";
				}
				
			}
		}
		
		if(isset($atts['category_title_colors']) && trim($atts['category_title_colors']) != ""){
			$category_title_colors_raw = explode(",", $atts['category_title_colors']);
			foreach($category_title_colors_raw as $c_title_color){
				if(trim($c_title_color) != ""){
					if(preg_match("/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){1}|([a-f]|[A-F]|[0-9]){3}|([a-f]|[A-F]|[0-9]){5})?\b/", $c_title_color)) {
						$category_title_colors[] = $c_title_color;
					}
					else{
						$colorerror = true;
						break;
					}
				}
				else{
					$category_title_colors[] = "";
				}
				
			}
		}

		if(isset($atts['category_body_colors']) && trim($atts['category_body_colors']) != ""){
			$category_body_colors_raw = explode(",", $atts['category_body_colors']);
			foreach($category_body_colors_raw as $c_body_color){
				if(trim($c_body_color) != ""){
					if(preg_match("/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){1}|([a-f]|[A-F]|[0-9]){3}|([a-f]|[A-F]|[0-9]){5})?\b/", $c_body_color)) {
						$category_body_colors[] = $c_body_color;
					}
					else{
						$colorerror = true;
						break;
					}
				}
				else{
					$category_body_colors[] = "";
				}
				
			}
		}

		$categories = array();
		$category_titles = array();

		if(isset($atts['categories']) && trim($atts['categories']) != ""){
			$categories_raw = explode(",", $atts['categories']);
			foreach($categories_raw as $ci => $c) {
				$category_atts = array();
				$category_atts['title'] = trim($c);
				$category_titles[] = trim($c);

				$category_atts['head_color'] = "";
				if(isset($category_head_colors[$ci])){
					$category_atts['head_color'] = $category_head_colors[$ci];
				}

				$category_atts['title_color'] = "";
				if(isset($category_title_colors[$ci])){
					$category_atts['title_color'] = $category_title_colors[$ci];
				}

				$category_atts['body_color'] = "";
				if(isset($category_body_colors[$ci])){
					$category_atts['body_color'] = $category_body_colors[$ci];
				}

				$categories[] = $category_atts;
			}
		}

		$saveFormId = "";
		if(isset($atts['save_form_id']) && trim($atts['save_form_id']) != "" && is_numeric($atts['save_form_id']) && get_post_type($atts['save_form_id']) == "formulare") {
            $saveFormId = trim($atts['save_form_id']);
        } elseif( !isset($atts['save_form_id'])) {
            $saveFormId = "";
        }

		$savedData = array();
		$saveFormData = array();
		if($saveFormId != ""){
			$saveFormData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($saveFormId, Trainingssystem_Plugin_Public::getTrainingUser());
			if(!empty($saveFormData)){
				foreach($saveFormData[0] as $saveFormField){
					
					if(!empty($saveFormField->getFormdata())){
						$categoryLists = json_decode($saveFormField->getFormdata()->getData());
						foreach($categoryLists as $categoryName => $categoryList){
							$savedData[$categoryName] = array();
							foreach($categoryList as $categoryItem){
								// saved item is still in multiform available
								if(in_array($categoryItem, $data)){
									$savedData[$categoryName][] = $categoryItem;
								}
							}
						}
					}
				}
			}
		}

		// check for new items
		if(!empty($savedData)){
			foreach($data as $dataItem){
				$itemFound = false;
				foreach($savedData as $savedDataCategory){
					if(in_array($dataItem, $savedDataCategory)){
						$itemFound = true;
					}
				}

				if(!$itemFound){
					$savedData['drag_drop_categories_start_area'][] = $dataItem;
				}
			}
		}

		// check for new or altered/deleted categories
		if(!empty($savedData)){
			foreach($savedData as $savedDataCatagoryTitle => $savedDataCatagoryList){
				if($savedDataCatagoryTitle != 'drag_drop_categories_start_area'){
					// category was altered/deleted
					if(!in_array($savedDataCatagoryTitle, $category_titles)){
						foreach($savedDataCatagoryList as $savedCategoryItem){
							$savedData['drag_drop_categories_start_area'][] = $savedCategoryItem;
						}
						unset($savedData[$savedDataCatagoryTitle]);
					}
				}
			}
			// new category
			foreach($category_titles as $category_title){
				if(!isset($savedData[$category_title])){
					$savedData[$category_title] = array();
				}
			}

		}



		$random_number=mt_rand();

		if(!is_null($formid) && sizeof($categories) > 0 && !$colorerror){
			return $twig->render('evaluate-categories/drag-drop-categories.html',[
				"data" => $data,
				"categories" => $categories,
				"saveFormId" => $saveFormId,
				"rand" => $random_number,
				"savedData" => $savedData
			]);
		}
		else{
			return $twig->render("evaluate-categories/drag-drop-categories-error.html");
		}


	}

	/**
	 * Renders a polar chart for x categories that can be changed with sliders
	 * 
	 * @param WordPress Shortcode Attributes
	 * 
	 * @return HTML Code
	 */
	public function evaluateCategories($atts)
	{
			$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

			$formid = (isset($atts['form_id']) && is_numeric($atts['form_id']) && get_post_type($atts['form_id']) == "formulare") ? $atts['form_id'] : null;
			$formData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($formid, Trainingssystem_Plugin_Public::getTrainingUser());
			$formfieldCount = isset($formData[0]) ? sizeof($formData[0]) : 0;

			$categories = array();
			if(isset($atts['categories']) && trim($atts['categories']) != ""){
				$categories_raw = explode(",", $atts['categories']);
				foreach($categories_raw as $c) {
					$categories[] = trim($c);
				}
			}

			$alpha = 127; // 50% 
			if(isset($atts['alpha']) && trim($atts['alpha']) != "" && is_numeric($atts['alpha'])){
				$alpha = intval((intval(trim($atts['alpha']))/100)*255);
			}

			$categoryItems = array();
			$categoryItemsFormid = (isset($atts['form_id_category_items']) && is_numeric($atts['form_id_category_items']) && get_post_type($atts['form_id_category_items']) == "formulare") ? $atts['form_id_category_items'] : null;
			if(!is_null($categoryItemsFormid)){
				$savedCategoryData = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($categoryItemsFormid, Trainingssystem_Plugin_Public::getTrainingUser());
				if(!empty($savedCategoryData)){
					foreach($savedCategoryData[0] as $saveFormField){
						if(!empty($saveFormField->getFormData())){
							$savedCategoryLists = json_decode($saveFormField->getFormdata()->getData());
							foreach($savedCategoryLists as $savedCategoryName => $savedCategoryList){
								$categoryItems[$savedCategoryName] = array();
								foreach($savedCategoryList as $categoryItem){
									$categoryItems[$savedCategoryName][] = $categoryItem;
								}
							}
						}
					}
				}
			}
			
			$colors = array();
			$colorerror = false;
			if(isset($atts['colors'])){
				if(trim($atts['colors']) != ""){
					$colors_raw = explode(",", $atts['colors']);
					foreach($colors_raw as $c) {
						if(preg_match("/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){1}|([a-f]|[A-F]|[0-9]){3}|([a-f]|[A-F]|[0-9]){5})?\b/", $c)) {
							$colors[] = trim($c);
						} else {
							$colorerror = true;
							break;
						}
					}
				} else {
					$colorerror = true;
				}
			} else {
				for($i = 0; $i < sizeof($categories); $i++) {
					$colors[] = $this->random_color($alpha);
				}
			}

			if(!is_null($formid) && sizeof($categories) > 0 && !$colorerror && sizeof($categories) == sizeof($colors) && isset($formData[0]) && sizeof($categories) == $formfieldCount) {

				$data = array();
				foreach($formData[0] as $field) {
					if(!is_null($field->getFormdata())) {
						$data[] = $field->getFormdata()->getData();
					} elseif(isset($field->getAttributesJsonDecoded()['value'])) {
						$data[] = $field->getAttributesJsonDecoded()['value'];
					} else {
						$data[] = 0;
					}
				}

				$showLegend = false;
				if(isset($atts['showlegend']) && $atts['showlegend'] == "true") {
					$showLegend = true;
				}

				$showPointLabel = true;
				if(isset($atts['showpointlabel']) && $atts['showpointlabel'] == "false") {
					$showPointLabel = false;
				}

				$centerPointLabel = true;
				if(isset($atts['centerpointlabel']) && $atts['centerpointlabel'] == "false") {
					$centerPointLabel = false;
				}

				$adjustSliderColor = false;
				if(isset($atts['adjustslidercolor']) && $atts['adjustslidercolor'] == "true") {
					$adjustSliderColor = true;
				}

				$sliderCategoryItems = array();
				if(!is_null($categoryItemsFormid)){
					$sliderForm = Trainingssystem_Plugin_Database::getInstance()->Formfield->getFormfieldsByForm($formid);
					foreach($sliderForm as $sliderElement){
						$sliderElementId = $sliderElement->getFieldId();
						$sliderCategoryItems[$sliderElementId] = array();
						$sliederElementAttributes = $sliderElement->getAttributesJsonDecoded();
						$sliderElementLabel = $sliederElementAttributes['label'];
						if(isset($categoryItems[$sliderElementLabel])){
							$sliderCategoryItems[$sliderElementId] = $categoryItems[$sliderElementLabel];
						}
					}
				}
				
				return $twig->render('evaluate-categories/evaluate-categories.html',[
						"categories" => $categories,
						"colors" => $colors,
						"data" => $data,
						"form_id" => $formid,
						"showLegend" => $showLegend,
						"showPointLabel" => $showPointLabel,
						"centerPointLabel" => $centerPointLabel,
						"adjustSliderColor" => $adjustSliderColor,
						"random" => bin2hex(random_bytes(32)),
						"sliderCategoryItems" => $sliderCategoryItems
						]
					);
			} else {
				return $twig->render("evaluate-categories/evaluate-categories-error.html");
			}
	}

	/**
	 * HELPER
	 * 
	 * Generates a random color part
	 * 
	 * @return 2 chars of [0-9a-f]
	 */
	private function random_color_part() {
        return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
    }

	/**
	 * HELPER
	 * 
	 * Generates a random hex-color #xxxxxx
	 * 
	 * @param int alpha
	 * 
	 * @return random color with leading #
	 */
    private function random_color($alpha) {
        return "#" . $this->random_color_part() . $this->random_color_part() . $this->random_color_part() . str_pad( dechex( $alpha ), 2, '0', STR_PAD_LEFT);
    }
}
