<?php

/**
 * The functionality of the module.
 *
 * @package    Studienexport
 * @author     Max Sternitzke <max.sternitzke@th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Study_Export {

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {

    }


	public function showStudyExportPage() {

		$heading = isset($atts['titel']) ? $atts['titel'] : 'Studien-Export'; 

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("dataexport"))
		{
			ob_start();

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			} else {
				
				$alltrainings = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();
				$allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllNutzer(false, false, false);
				$allscalematrixforms = Trainingssystem_Plugin_Database::getInstance()->Formfield->getScaleMatrixForms();

				foreach($alltrainings as $training) {

					$tsformids = get_post_meta($training->getId(), 'tsformids', true);
					if(strlen($tsformids) > 1) {
						$training->setTsFormIds(explode(";", $tsformids));
					}

					foreach($training->getLektionsliste() as $lektion) {
						
						$tsformids = get_post_meta($lektion->getId(), 'tsformids', true);
						if(strlen($tsformids) > 1) {
							$lektion->setTsFormIds(explode(";", $tsformids));
						}
					}
				}
			
				echo $twig->render('study-export/study-export-overview.html',[	
					"trainings"=>$alltrainings,
					"allscalematrixforms" => $allscalematrixforms,
					"allusers" => $allusers,
					"heading" => $heading
					]);

			}
			return ob_get_clean();
		} 
		else
		{
			return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);

		}
	}

	public function studyexportDownload() {
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("dataexport"))
		{
			if(isset($_POST['data']) && trim($_POST['data']) != "" && isset($_POST['user']) && trim($_POST['user']) != "") {

				$data = json_decode(stripslashes(sanitize_text_field($_POST['data'])), true);
				$user = json_decode(stripslashes(sanitize_text_field($_POST['user'])), true);

				if(json_last_error() === JSON_ERROR_NONE) {

					if(sizeof($user) == 0 || sizeof($data['trainings']) == 0) {
						return;
						wp_die();
					}

					foreach($data['trainings'] as $trainingid => $training) {
						update_post_meta($trainingid, 'tsformids', implode(";", $training['tsformids']));

						foreach($training['lektionen'] as $lektionid => $tsformids) {
							update_post_meta($lektionid, 'tsformids', implode(";", $tsformids));
						}
					}
					header("Content-type: text/csv, charset=utf-8");
            		header("Content-disposition: attachment; filename=Studienexport-" . current_time("d-m-Y-H-i-s") . ".csv");

					$csvdata = array();
					$headerdata = array();
					foreach($user as $u) {
						foreach($data['trainings'] as $trainingid => $training) {
							$trainingprefix = array();
							$trainingprefix[] = $u;
							$trainingprefix[] = get_the_title($trainingid);
							$trainingprefix[] = "-"; // Training hat keine Lektion

							if(sizeof($training['tsformids']) > 0) {
								foreach($training['tsformids'] as $tsformid) {
									$trainingprefix[] = get_the_title($tsformid);
									$formdata = $this->getFormData($u, $tsformid);
									$headerdata[$tsformid] = sizeof($formdata);
									$trainingprefix = array_merge($trainingprefix, $formdata);
								}
							}
							
							if(sizeof($training['lektionen']) > 0) {
								foreach($training['lektionen'] as $lektionid => $tsformids) {
									if(sizeof($tsformids) > 0) {

										$trainingprefix[2] = get_the_title($lektionid); // Overwrite Lektion Title
										$csvdata[$u.'-'.$lektionid] = $trainingprefix;

										foreach($tsformids as $tsformid) {
											$csvdata[$u.'-'.$lektionid][] = get_the_title($tsformid);
											$formdata = $this->getFormData($u, $tsformid);
											$headerdata[$tsformid] = sizeof($formdata);
											$csvdata[$u.'-'.$lektionid] = array_merge($csvdata[$u.'-'.$lektionid], $formdata);
										}
									}
								}
							} else {
								$csvdata[$u.'-'.$trainingid] = $trainingprefix;
							}
						}
					}

					// Test if all rows in the final CSV file have the same amount of columns; if not exit
					if(sizeof($csvdata) > 0) {
						foreach($csvdata as $row) {
							$count = sizeof($row);
							break;
						}

						foreach($csvdata as $row) {
							if(sizeof($row) !== $count) {
								wp_die();
								return;
							}
						}
					} else {
						wp_die();
						return;
					}

					// Build header 
					$header = array();
					$header[] = "User-ID";
					$header[] = "Training";
					$header[] = "Lektion";
					$j = 1;
					foreach($headerdata as $hd_count) {
						$header[] = "Formular_".$j."_Titel";
						for ($i = 1; $i <= $hd_count; $i++) {
							$header[] = "Formular_".$j."_Option_".$i;
						}
						$j++;
					}
					
					$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
					echo $twig->render('study-export/study-export-csv.html', ["header" => $header, "csvdata"=>$csvdata, "sep" => ";"]);

				} else {
					echo "0";
				}
			}
		}
		wp_die();
	}

	private function getFormData($userid, $tsformid) {
		$ret = array();

		$userformdata = Trainingssystem_Plugin_Database::getInstance()->Formfield->getUserFormfieldsByForm($tsformid, $userid);

		foreach($userformdata as $formgroup => $formgroupdata) {
			foreach($formgroupdata as $formfieldindex => $formfield) {
				if(($formfield->getType() == "scale" && $formfield->getFormdata() != null && $formfield->getFormdata()->dataIsArray() && 
						sizeof($formfield->getAttributesJsonDecoded()['elements']) == sizeof($formfield->getFormdata()->getDataJsonDecoded())) 
					||
					($formfield->getType() == "matrix" && $formfield->getFormdata() != null && $formfield->getFormdata()->dataIsArray() && 
						sizeof($formfield->getAttributesJsonDecoded()['questions']) == sizeof($formfield->getFormdata()->getDataJsonDecoded()))) {
					
					foreach($formfield->getFormdata()->getDataJsonDecoded() as $data) {
						$ret[] = $data;
					}
					
				} else if(($formfield->getType() == "scale" || $formfield->getType() == "matrix") && $formfield->getFormdata() == null) {
					if($formfield->getType() == "scale") {
						for($i = 0; $i < sizeof($formfield->getAttributesJsonDecoded()['elements']); $i++) {
							$ret[] = "";
						}
					} else if($formfield->getType() == "matrix") {
						for($i = 0; $i < sizeof($formfield->getAttributesJsonDecoded()['questions']); $i++) {
							$ret[] = "";
						}
					}
				} else if(($formfield->getType() == "scale" && sizeof($formfield->getAttributesJsonDecoded()['elements']) != sizeof($formfield->getFormdata()->getDataJsonDecoded())) ||
							($formfield->getType() == "matrix") && sizeof($formfield->getAttributesJsonDecoded()['questions']) != sizeof($formfield->getFormdata()->getDataJsonDecoded())) {
					foreach($formfield->getFormdata()->getDataJsonDecoded() as $data) {
						$ret[] = $data;
					}

					for($i = sizeof($ret); $i < sizeof($formfield->getAttributesJsonDecoded()['elements']); $i++) {
						$ret[] = "";
					}
				}
			}
		}
		
		return $ret;
	}
}