<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 * @author     Markus Domin, Tim Mallwitz
 */
class Trainingssystem_Plugin_Module_Zertifikate{


	public function __construct() {

	}

	/**
	 * FRONTEND
	 * Displays the certificate overview in the frontend
	 */
	public function listzertifikate($atts) {

		$heading = isset($atts['titel']) ? $atts['titel'] : 'Zertifikate';
		$show_certificate_title = false;
		if(isset($atts['show_certificate_title']) && (trim($atts['show_certificate_title']) == "1" || trim($atts['show_certificate_title']) == "true")) {
            $show_certificate_title = true;
        }

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		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 {

			$trainings = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($current_user->ID);
			$allCertificates = Trainingssystem_Plugin_Database::getInstance()->Certificate->getAllCertificates();

			$trainingIDs = array();
			$certificates = array();
			$noCertificates = true;

			foreach($trainings as $t){
				$trainingIDs[] = $t->getID();
			}
			foreach($allCertificates as $c){

				if(in_array($c->getTraining_id(), $trainingIDs)){
					$certificates[$c->getTraining_id()][] =$c;
					$noCertificates = false;
				}
			}

			$notrainings = true;
			if(sizeof($trainings)>0){
				$notrainings = false;
			}

			$posts = get_posts([
				'post_type' => 'zertifikate',
				'post_status' => 'publish',
				'numberposts' => -1
				// 'order'    => 'ASC'
			]);
	
			$outputarr = array();
			$certFindates = array();
			$trainingFindates = array();

			foreach($posts as $post){
				$certFindates[$post->ID] = $post->post_date;
			}
			
			foreach($trainings as $training){
				if($training->getFin() >= 100){
					if(isset($certificates[$training->getID()])){
						$training->setZertifikat($certificates[$training->getID()]);
						$outputarr[] = $training;
						$trainingLektionen = $training->getLektionsliste();
						$maxDate = "1970-01-01";
						
						foreach($trainingLektionen as $trainingLektion){
							if(!is_null($trainingLektion->getFindate())){
								if($maxDate < $trainingLektion->getFindate()){
									$maxDate = $trainingLektion->getFindate();
									$trainingFindates[$training->getID()] = $trainingLektion->getFindate();
								}
							}	
						}
						
						if($maxDate != "1970-01-01"){
							foreach($certificates[$training->getID()] as $certificate){
								$certFindates[$certificate->getCertificate_id()] = $maxDate;
							}
						}
						else{
							foreach($certificates[$training->getID()] as $certificate){
								if(isset($trainingFindates[$training->getID()])){
									if($trainingFindates[$training->getID()] > $certFindates[$certificate->getCertificate_id()]){
										$trainingFindates[$training->getID()] = $certFindates[$certificate->getCertificate_id()];
									}
								}
								else{
									$trainingFindates[$training->getID()] = $certFindates[$certificate->getCertificate_id()];
								}
								
							}
						}
						
					}
					
				}
			}

			$defaultimglink = get_header_image();
			$isDemoUser = get_user_meta($current_user->ID, 'demo_user', true);
			
			echo $twig->render('zertifikate/zertifikate-overview.html',[
				"current_user" => $current_user,
				"trainings"=>$outputarr,
				"notrainings" => $notrainings,
				"nocertificates" => $noCertificates,
				"heading" => $heading,
				"defaultimglink" => $defaultimglink,
				"certFindates" => $certFindates,
				"trainingFindates" => $trainingFindates,
				"profile_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]),
				"isDemoUser" => $isDemoUser,
				"show_certificate_title" => $show_certificate_title
			]);
		}

		return ob_get_clean();
	}


	/**
	 * BACKEND
	 * Adding the meta boxes to the edit page
	 */
	public function add_zertifikate_meta_box(){
		add_meta_box("zertifikate-header-meta-box", "Zertifikat-Header", array($this, "custom_zertifikate_header_meta_box_markup"), "zertifikate", "normal", "high", null);
		add_meta_box("zertifikate-content-meta-box", "Zertifikat-Inhalt", array($this, "custom_zertifikate_content_meta_box_markup"), "zertifikate", "normal", "high", null);
		add_meta_box("zertifikate-footer-meta-box", "Zertifikat-Footer", array($this, "custom_zertifikate_footer_meta_box_markup"), "zertifikate", "normal", "high", null);
		add_meta_box("zertifikate-preview-meta-box", "Vorschau", array($this, "custom_zertifikate_preview_meta_box_markup"), "zertifikate", "normal", "high", null);
		add_meta_box("zertifikate-export-meta-box", "&nbsp;", array($this, "custom_zertifikate_export_meta_box_markup"), "zertifikate", "side", "high", null);
	}


	/**
	 * BACKEND
	 * Adds the certificate header box
	 */
	public function custom_zertifikate_header_meta_box_markup(){

		global $post;
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$certificate_header = Trainingssystem_Plugin_Database::getInstance()->Certificate->getCertificateHeaderById($post->ID);
			
		echo $twig->render('zertifikate/backend-zertifikat-header.html', [
			"certificate_header" => $certificate_header
		]);
	}

	/**
	 * BACKEND
	 * Adds the certificate content box
	 */
	public function custom_zertifikate_content_meta_box_markup(){

		global $post;

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$certificate_content = Trainingssystem_Plugin_Database::getInstance()->Certificate->getCertificateContentById($post->ID);

		$allTrainings = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();
		$selectedTraining = get_post_meta( get_the_ID(), 'training_dropdown', true );
		
		echo $twig->render('zertifikate/backend-zertifikat-content.html', [
			"allTrainings" => $allTrainings,
			"selectedTraining" => $selectedTraining,
			"certificate_content" => $certificate_content
		]);
	}

	/**
	 * BACKEND
	 * Adds the certificate footer box
	 */
	public function custom_zertifikate_footer_meta_box_markup(){

		global $post;

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$certificate_footer = Trainingssystem_Plugin_Database::getInstance()->Certificate->getCertificateFooterById($post->ID);
				
		echo $twig->render('zertifikate/backend-zertifikat-footer.html', [
			"certificate_footer" => $certificate_footer
		]);
	}

	/**
	 * BACKEND
	 * Adds the certificate preview box
	 */
	public function custom_zertifikate_preview_meta_box_markup(){
		
		global $post;

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		echo $twig->render('zertifikate/backend-zertifikat-preview.html', [
			"postid" => $post->ID
		]);
	}

	/**
	 * BACKEND
	 * Add the box in the sidebar with duplicate button
	 */
	public function custom_zertifikate_export_meta_box_markup(){

		global $post;

		echo '<div class="wrapper-admin-backend"><button type="button" class="btn btn-secondary backend-duplicate-zertifikat mt-3" zertifikat-id="' . $post->ID . '"><i class="fas fa-clone"></i>&nbsp;Zertifikat duplizieren</button></div>';
	}

	/**
	 * BACKEND/ADMIN
	 * Adds a duplicate button to each certificate row action list
	 */
	public function backendZertifikatAddActions($actions, $post){
		if(strtolower($post->post_type) === "zertifikate") {
			$actions['duplicate_link'] = '<div class="wrapper-admin-backend" style="display:inline"><button type="button" class="btn btn-secondary btn-sm backend-duplicate-zertifikat" zertifikat-id="' . $post->ID . '">Duplizieren</button></div>';
		}

		return $actions;
	}

	/**
	 * BACKEND
	 * Saves the content of a certificate
	 */
	public function saveZertifikat(){
		
		if(isset($_POST['certificate_id']) && is_numeric($_POST['certificate_id']) &&
			isset($_POST['training_id']) && is_numeric($_POST['training_id']) &&
			isset($_POST['certificate_header']) && strlen(trim($_POST['certificate_header'])) > 1 &&
			isset($_POST['certificate_content']) && strlen(trim($_POST['certificate_content'])) > 1 &&
			isset($_POST['certificate_footer']) && strlen(trim($_POST['certificate_footer'])) > 1){

			$certificate_id = $_POST['certificate_id'];
			$training_id = $_POST['training_id'];
			$certificate_header_str = $_POST['certificate_header'];
			$certificate_content_str = $_POST['certificate_content'];
			$certificate_footer_str = $_POST['certificate_footer'];

			$certificate_header = json_decode(stripslashes($certificate_header_str), true);
			$certificate_content = json_decode(stripslashes($certificate_content_str), true);
			$certificate_footer = json_decode(stripslashes($certificate_footer_str), true);
			
			if(is_string(get_post_status($certificate_id)) && json_last_error() === JSON_ERROR_NONE){
				
				update_post_meta($certificate_id, 'training_dropdown', $training_id);
				if(Trainingssystem_Plugin_Database::getInstance()->Certificate->deleteCertificateData($certificate_id)){
					if(Trainingssystem_Plugin_Database::getInstance()->Certificate->insertCertificateData($certificate_id, $training_id, json_encode($certificate_header), json_encode($certificate_content), json_encode($certificate_footer))){
						echo "success";
					}
					else{
						echo "error";
					}
				}

			}
		}
		wp_die();
	}

	/**
	 * BACKEND
	 * Deletes the selected certificate
	 */
	public function backendDeleteZertifikat($postid){

        if(strtolower(get_post_type($postid)) === "zertifikate") {
			delete_post_meta($postid, "training_dropdown");
			Trainingssystem_Plugin_Database::getInstance()->Certificate->deleteCertificateData($postid);
		}
	}

	/**
	 * Duplicates the selected certificate and and returns a link to the edit page of the new certificate
	 */
	public function backendDuplicateZertifikat(){

		if(isset($_POST['zertifikatId']) && is_numeric($_POST['zertifikatId']) && strtolower(get_post_type($_POST['zertifikatId'])) === "zertifikate"){

			$export = $this->exportZertifikat($_POST['zertifikatId']);
			$importdata = json_decode($export, true);
			
			if(isset($importdata['title'])){
				$importdata['title'] .= " Kopie";
			}

			$import = $this->importZertifikat($importdata);
			if($import != null && is_numeric($import)){
				echo get_edit_post_link($import, "");
			}
		}
		wp_die();
	}

	/**
	 * HELPER
	 * Exports a certificate, either as JSON or as PHP Array
	 */
	public function exportZertifikat($zertifikatId, $jsonencoded = true){
		$ret = array();

		if(strtolower(get_post_type($zertifikatId)) === "zertifikate") {

			$ret['title'] = get_the_title($zertifikatId);
			$certificate_data = Trainingssystem_Plugin_Database::getInstance()->Certificate->getCertificateById($zertifikatId);
			$ret['training_ID'] = $certificate_data->getTraining_id();
			$ret['training_dropdown'] = get_post_meta($zertifikatId, 'training_dropdown', true);
			$ret['certificate_header'] = $certificate_data->getCertificate_header();
			$ret['certificate_content'] = $certificate_data->getCertificate_content();
			$ret['certificate_footer'] = $certificate_data->getCertificate_footer();
		}

		if($jsonencoded){
			return json_encode($ret);
		}
		else{
			return $ret;
		}
	}

	/**
	 * HELPER
	 * Imports a certificate
	 */
	public function importZertifikat($data){

		if(!is_array($data)) {
			$jsondata = json_decode($data, true);
			if(json_last_error() == JSON_ERROR_NONE) {
				$data = $jsondata;
			}
		}

		if(is_array($data) && isset($data['title']) && isset($data['training_ID']) &&
			isset($data['training_dropdown']) && isset($data['certificate_header']) &&
			isset($data['certificate_content']) && isset($data['certificate_footer'])){

			$wp_zertifikat = array(
				"post_title" => $data['title'],
				"post_status" => "publish",
				"post_type" => "zertifikate"
			);

			$wp_zertifikat_id = wp_insert_post($wp_zertifikat);

			if(!is_wp_error($wp_zertifikat_id)){
				update_post_meta($wp_zertifikat_id, "training_dropdown", $data['training_dropdown']);

				if(Trainingssystem_Plugin_Database::getInstance()->Certificate->insertCertificateData($wp_zertifikat_id, $data['training_ID'], $data['certificate_header'], $data['certificate_content'], $data['certificate_footer'])){
					return $wp_zertifikat_id;
				}
				else{
					delete_post_meta($wp_zertifikat_id, "training_dropdown");

					wp_delete_post($wp_zertifikat_id, true);

					return null;
				}
			}
			else{
				return null;
			}
		}
		else{
			return null;
		}
	}
	
}
