<?php

/**
 *  
 */

class Trainingssystem_Plugin_Module_Mailbox
{

	public function __construct()
	{
		add_action('wp', array($this, 'maybe_schedule_mailbox_notifications'));
		add_action('mailbox_send_notifications', array($this, 'send_notifications'));
		add_action(TRAININGSSYSTEM_PLUGIN_ACTION_LEKTION_FIN, array($this, 'inform_trainer_about_lektion_fin'), 10, 2);
	}

	public function maybe_schedule_mailbox_notifications()
	{
		if (!wp_next_scheduled('mailbox_send_notifications')) {
			wp_schedule_event(current_time('timestamp'), 'daily', 'mailbox_send_notifications');
		}
	}

	public function inform_trainer_about_lektion_fin($page)
	{
		global $wpdb;

		$current_user = wp_get_current_user();
		$to_id = get_user_meta($current_user->ID, 'coachid', true);
		$lektion =  $page->getLektionid();
		$training = $page->getTrainingid();

		//Benutzerdefinierten Coaching-Modus checken - coach nur informieren, wenn 'umfassend' also 2 gewählt ist
		$usermetaEntryMode = get_user_meta($current_user->ID, 'coaching_needed', true);
		if (!empty($usermetaEntryMode)) {
			$selectedCoachingModes = (array) json_decode($usermetaEntryMode);
			if (isset($selectedCoachingModes[$training]) && $selectedCoachingModes[$training] == "2" && Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingAutoForLektion($current_user->ID, $training, $lektion) == "2") {
				$post = get_post($lektion);
				$title = $post->post_title;

				$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
				$subject_default = '[username] hat das Training "[training]" beendet';
				$message_default = '[username] hat das Training "[training]" am [date] um [time] abgeschlossen und wartet auf Feedback von Dir.';

				$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
				$subject = (isset($settings['mailbox_training_feedback_subject']) && !empty($settings['mailbox_training_feedback_subject'])) ? $settings['mailbox_training_feedback_subject'] : $subject_default;
				$message = (isset($settings['mailbox_training_feedback_body']) && !empty($settings['mailbox_training_feedback_body'])) ? $settings['mailbox_training_feedback_body'] : $message_default;

				$subject = str_replace(array("[username]", "[training]"), array($current_user->display_name, $title), $subject);
				$message = str_replace(array("[username]", "[training]", "[date]", "[time]"), array($current_user->display_name, $title, current_time("d.m.y"), current_time("H:i") . ' Uhr'), $message);

				$post_id = wp_insert_post(array(
					'post_title' => $subject,
					'post_type' => 'nachrichten',
					'post_author' => $current_user->ID,
					'post_content' => $message,
					'post_status' => 'publish',
				), true);

				$sql = $wpdb->prepare("INSERT INTO $tn ( post_id, from_id, to_id ,type_flag, lektion_id ) VALUES ('%d','%d','%d','%s', '%d')", $post_id, $current_user->ID, $to_id, 'ask_for_feedback', $lektion);
				$mysql_results = $wpdb->get_results($sql);

				$this->send_notification_to($to_id, true);
			}
		}
	}


	/**
	 * inserts a badge-div into the menu-item which points to the mailbox
	 */
	function mailbox_count_bubble_to_nav($items, $args)
	{
		$mailboxurl = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"]);

		$unread_messages = $this->get_unread_count();
		if ($unread_messages > 0) {
			if ($args->theme_location == 'primary-menu') {
				$regx = '/<li(.*?)><a(.*?)href="' . preg_quote($mailboxurl, '/') . '"(.*?)>(.*?)<\/a>(.*?)<\/li>/i';
				$replace = '<li$1><a$3href="' . $mailboxurl . '">$4<div class="mailbox-count-bubble badge badge-info" style="margin-left: 1em;background:#E56222">' . $unread_messages . '</div></a></li>';
				$items = preg_replace($regx, $replace, $items);
			}
		}
		return $items;
	}
	/**
	 * 
	 */

	public function mailbox_io()
	{

		if (!is_user_logged_in()) {
			return 0;
		}

		$posted_data =  isset($_POST) ? $_POST : array();
		switch ($posted_data["mailbox-action"]) {
			case "feedback":
				$this->send_feedback();
				break;
			case "send":
				$this->send_message();
				break;
			case "outbox":
				$this->get_outbox();
				break;
			case "history":
				$this->get_history();
				break;
			case "get-message":
				$this->get_message();
				break;
			case "get-users":
				$this->get_users();
				break;
			case "inbox":
			default:
				$this->get_inbox();
				break;
		}

		die();
	}

	/**
	 * nachrichten für user/trainer
	 */
	public function show_mailbox($atts)
	{

		$heading = isset($atts['titel']) ? $atts['titel'] : 'Nachrichten'; 

		$backlink = $_SERVER["HTTP_REFERER"] ?? null;

		$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()]);
		}

		$backtoorigin = false;
		$refurl = get_home_url();
		if (isset($_GET['backtoorigin']) && is_numeric($_GET['backtoorigin'])) {
			$backtoorigin = true;
			if (isset($_GET['backtouserid']) && is_numeric($_GET['backtouserid'])) {
				$refurl = add_query_arg('userid', $_GET['backtouserid'], get_permalink(sanitize_text_field($_GET['backtoorigin'])));
			} else {
				$refurl = get_permalink(sanitize_text_field($_GET['backtoorigin']));
			}
		}

		echo $twig->render('mailbox/mailbox.html', [
			'ajaxurl' => admin_url('admin-ajax.php'),
			'myid' => $current_user->ID,
			'backtoorigin' => $backtoorigin,
			'refurl' => $refurl,
			'heading' => $heading,
			'back_link' => $backlink,
			'vuejs_script_path' => plugin_dir_url(dirname(__FILE__)) . '../../assets/external/vuejs/vue.js',
			'axios_script_path' => plugin_dir_url(dirname(__FILE__)) . '../../assets/external/vuejs/axios.min.js',
		]);

		return ob_get_clean();
	}

	/**
	 * info über posteingang, alle x tage von wp_cron
	 */
	public function send_notifications()
	{
		global $wpdb;

		$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
		$mailboxurl = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"]);

		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$tu = $wpdb->users; //"wp_users";
		$sql = "SELECT to_id as id ,COUNT(*) as count ,user_email as email, user_nicename as name from $tn LEFT JOIN $tu ON $tn.to_id=$tu.ID WHERE read_at IS NULL GROUP BY to_id;";
		$mysql_results = $wpdb->get_results($sql);
		foreach ($mysql_results as $user) {
			if ($user->email) {
				$notification_setting = get_user_meta($user->id, 'mailbox_notifications', true);
				if ($notification_setting == "2") {
					$lastNotitication = get_user_meta($user->id, 'notification-send-for-unread-messages', true);
					$now = new DateTime("now");
					$days = intval(date_diff(date_create($lastNotitication), $now)->format('%r%a'));
					$interval = intval(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_notification_interval"]);
					if ($interval > 0 && ($lastNotitication == "" || $days > $interval)) {
						$to = $user->email;

						$subject = get_bloginfo('name') . ' - Postfach';
						if (isset($settings['mailbox_email_unread_messages_subject']) && trim($settings['mailbox_email_unread_messages_subject']) !== "") {
							$subject = $settings['mailbox_email_unread_messages_subject'];
						}
						$body = "Sie haben " . ($user->count > 1 ? $user->count . " ungelesene Nachrichten.\n" : "eine ungelesene Nachricht.\n");
						$body .= "Bitte schauen Sie mal wieder in Ihr Postfach:\n\n";
						$body .= $mailboxurl;
						$body = nl2br($body);

						if (isset($settings['mailbox_email_unread_message_body']) && trim($settings['mailbox_email_unread_message_body']) !== "" && isset($settings['mailbox_email_unread_messages_body']) && trim($settings['mailbox_email_unread_messages_body']) !== "") {
							if ($user->count > 1) {
								$body = $settings['mailbox_email_unread_messages_body'];
								$body = nl2br(str_replace(array("[link]", "[anzahl]"), array("<a href=\"" . $mailboxurl . "\">" . $mailboxurl . "</a>", $user->count), $body));
							} else {
								$body = $settings['mailbox_email_unread_message_body'];
								$body = nl2br(str_replace("[link]", "<a href=\"" . $mailboxurl . "\">" . $mailboxurl . "</a>", $body));
							}
						}

						$headers = array('Content-Type: text/html; charset=UTF-8');
						wp_mail($to, $subject, $body, $headers);
						update_user_meta($user->id, 'notification-send-for-unread-messages', date("Y-m-d H:i:s"));
					}
				}
			}
		}
	}

	/**
	 * neue nachricht / nachricht-post anlegen 
	 */

	private function send_message()
	{

		$response = array();
		$response['post_id'] = $this->create_message('message');
		echo json_encode($response);
	}



	private function send_feedback()
	{

		$posted_data =  isset($_POST) ? $_POST : array();
		$post_id  = $this->create_message('feedback');


		global $wpdb;
		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_TRAINING_USER;
		$sql = $wpdb->prepare("UPDATE $tn SET  feedback = '%s', feedback_date ='%s' WHERE lektion_id='%d' AND user_id='%d';", $post_id, current_time('mysql'), $posted_data["lektionid"], $posted_data["recipient"]);
		$mysql_results = $wpdb->get_results($sql);

		$response = array();
		$response['post_id'] = $post_id;
		$response['lektionid'] =  $posted_data["lektionid"];
		$response['recipient'] =  $posted_data["recipient"];
		echo json_encode($response);
	}




	private function create_message($type)
	{

		global $wpdb;

		$posted_data =  isset($_POST) ? $_POST : array();
		$current_user = wp_get_current_user();
		$message = $posted_data["message"];
		$response = array();
		$post_id = wp_insert_post(array(
			'post_title' => $posted_data["subject"],
			'post_type' => 'nachrichten',
			'post_author' => $current_user->ID,
			'post_content' => $message,
			'post_status' => 'publish',
		), true);

		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$user_id = $current_user->ID;
		$to_id = $posted_data["recipient"];
		$lektion_id = isset($posted_data["lektionid"]) ? $posted_data["lektionid"] : NULL;

		$sql = $wpdb->prepare("INSERT INTO $tn ( post_id, from_id, to_id ,type_flag,lektion_id ) VALUES ('%d','%d','%d','%s','%d')", $post_id, $user_id, $to_id, $type, $lektion_id);
		$mysql_results = $wpdb->get_results($sql);

		$this->send_notification_to($to_id);

		return $post_id;
	}

	/**
	 * info per email über neue nachricht im postfach
	 */
	public function send_notification_to($to_id, $is_feedback = false)
	{
		$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
		$mailboxurl = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"]);
		$args = array(
			"include" => $to_id
		);
		$users = get_users($args);
		if (count($users) == 1 && isset($users[0])) {
			$user = $users[0];
			$notification_setting = get_user_meta($user->ID, 'mailbox_notifications', true);
			if ($notification_setting == "" || $notification_setting == "1") {
				$to = $user->user_email;

				if ($is_feedback) {

					$subject = get_bloginfo('name') . ' - Postfach';
					if (isset($settings['mailbox_feedback_from_coach_email_subject']) && trim($settings['mailbox_feedback_from_coach_email_subject']) !== "") {
						$subject = $settings['mailbox_feedback_from_coach_email_subject'];
					}
					$body = "Ein Trainingsteilnehmer wartet auf Feedback.\n";
					$body .= "Bitte schauen Sie in Ihr Postfach:\n\n";
					$body .= $mailboxurl;
					$body = nl2br($body);
					if (isset($settings['mailbox_feedback_from_coach_email_body']) && trim($settings['mailbox_feedback_from_coach_email_body']) !== "") {
						$body = $settings['mailbox_feedback_from_coach_email_body'];
						$body = nl2br(str_replace("[link]", "<a href=\"" . $mailboxurl . "\">" . $mailboxurl . "</a>", $body));
					}
				} else {
					$subject = get_bloginfo('name') . ' - Postfach';
					$body =  "Sie haben eine neue Nachricht.\n";
					$body .= "Bitte schauen Sie in Ihr Postfach:\n\n";
					$body .= $mailboxurl;
					$body = nl2br($body);

					//recipient is a coach
					if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole('pCoach', $user->id)) {
						if (isset($settings['mailbox_coachee_2_coach_email_subject']) && trim($settings['mailbox_coachee_2_coach_email_subject']) !== "") {
							$subject = $settings['mailbox_coachee_2_coach_email_subject'];
						}
						if (isset($settings['mailbox_coachee_2_coach_email_body']) && trim($settings['mailbox_coachee_2_coach_email_body']) !== "") {
							$body = $settings['mailbox_coachee_2_coach_email_body'];
							$body = nl2br(str_replace("[link]", "<a href=\"" . $mailboxurl . "\">" . $mailboxurl . "</a>", $body));
						}
					} else {
						if (isset($settings['mailbox_coach_2_coachee_email_subject']) && trim($settings['mailbox_coach_2_coachee_email_subject']) !== "") {
							$subject = $settings['mailbox_coach_2_coachee_email_subject'];
						}
						if (isset($settings['mailbox_coach_2_coachee_email_body']) && trim($settings['mailbox_coach_2_coachee_email_body']) !== "") {
							$body = $settings['mailbox_coach_2_coachee_email_body'];
							$body = nl2br(str_replace("[link]", "<a href=\"" . $mailboxurl . "\">" . $mailboxurl . "</a>", $body));
						}
					}
				}

				$headers = array('Content-Type: text/html; charset=UTF-8');
				wp_mail($to, $subject, $body, $headers);
			}
		}
	}

	/**
	 * Anzahl ungelesener Nachrichten
	 */
	private function get_unread_count()
	{
		global $wpdb;
		$current_user = wp_get_current_user();
		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$sql = $wpdb->prepare(
			"SELECT COUNT(*) FROM $tn  WHERE $tn.to_id='%d' AND $tn.read_at IS NULL;",
			$current_user->ID
		);
		$mysql_results = $wpdb->get_var($sql);
		return $mysql_results;
	}

	/**
	 * postfach abrufen 
	 */
	private function get_inbox()
	{

		global $wpdb, $post;
		$posted_data =  isset($_POST) ? $_POST : array();
		$current_user = wp_get_current_user();
		$usermodus = false;
		$uid = get_current_user_id();
		$selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
		if ($selectui != '') {
			$uid = $selectui;
			$usermodus = true;
		}
		if (isset($posted_data["offset"])) {
			$offset = $posted_data["offset"];
		} else {
			$offset = 0;
		}

		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$tu = $wpdb->users; //"wp_users";
		$tp = $wpdb->posts; //"wp_posts";



		if ($posted_data['userid'] !== 'null') {
			$sql = $wpdb->prepare(
				"SELECT message_id as id , send_at as date ,from_id,read_at, display_name as sender, post_title as title ,  type_flag , lektion_id FROM $tn LEFT JOIN $tu ON $tn.from_id=$tu.ID LEFT JOIN $tp ON $tn.post_id=$tp.ID WHERE $tn.to_id='%d' AND $tn.from_id='%d'  ORDER BY message_id DESC;",
				$uid,
				$posted_data['userid']
			);
		} else {
			$sql = $wpdb->prepare(
				"SELECT message_id as id , send_at as date ,from_id,read_at, display_name as sender, post_title as title , type_flag , lektion_id FROM $tn LEFT JOIN $tu ON $tn.from_id=$tu.ID LEFT JOIN $tp ON $tn.post_id=$tp.ID WHERE $tn.to_id='%d' ORDER BY message_id DESC;",
				$uid
			);
		}


		$mysql_results = $wpdb->get_results($sql);
		$data = new stdClass();
		$data->found_posts = count($mysql_results);
		$data->result = $mysql_results;
		echo json_encode($data);
	}

	private function get_outbox()
	{

		global $wpdb, $post;
		$posted_data =  isset($_POST) ? $_POST : array();
		$current_user = wp_get_current_user();
		$usermodus = false;
		$uid = get_current_user_id();
		$selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
		if ($selectui != '') {
			$uid = $selectui;
			$usermodus = true;
		}
		if (isset($posted_data["offset"])) {
			$offset = $posted_data["offset"];
		} else {
			$offset = 0;
		}

		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$tu = $wpdb->users; //"wp_users";
		$tp = $wpdb->posts; //"wp_posts";

		if ($posted_data['userid'] !== 'null') {
			$sql = $wpdb->prepare(
				"SELECT message_id as id, send_at as date,read_at, display_name as sender, post_title as title FROM $tn LEFT JOIN $tu ON $tn.to_id=$tu.ID LEFT JOIN $tp ON $tn.post_id=$tp.ID WHERE $tn.from_id='%d' AND $tn.to_id='%d' AND ($tn.type_flag='message' OR $tn.type_flag='feedback')  ORDER BY message_id DESC;",
				$uid,
				$posted_data['userid']
			);
		} else {
			$sql = $wpdb->prepare(
				"SELECT message_id as id, send_at as date,read_at, display_name as sender, post_title as title FROM $tn LEFT JOIN $tu ON $tn.to_id=$tu.ID LEFT JOIN $tp ON $tn.post_id=$tp.ID WHERE $tn.from_id='%d' AND ($tn.type_flag='message' OR $tn.type_flag='feedback')  ORDER BY message_id DESC;",
				$uid
			);
		}

		$mysql_results = $wpdb->get_results($sql);
		$data = new stdClass();
		$data->found_posts = count($mysql_results);
		$data->result = $mysql_results;
		echo json_encode($data);
	}

	private function get_history()
	{

		global $wpdb, $post;
		$posted_data =  isset($_POST) ? $_POST : array();
		$current_user = wp_get_current_user();
		$usermodus = false;
		$uid = get_current_user_id();
		$selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
		if ($selectui != '') {
			$uid = $selectui;
			$usermodus = true;
		}
		if (isset($posted_data["offset"])) {
			$offset = $posted_data["offset"];
		} else {
			$offset = 0;
		}

		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$tu = $wpdb->users; //"wp_users";
		$tp = $wpdb->posts; //"wp_posts";



		if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole('pCoach', $current_user->ID)) {
			if ($posted_data['userid'] !== 'null') {
				$to_id = $posted_data['userid'];
			} else {
				$data = new stdClass();
				$data->found_posts = 0;
				$data->result = [];
				echo json_encode($data);
				return;
			}
		} else {
			$to_id = intval(get_user_meta($current_user->ID, 'coachid', true));
		}


		$sql = $wpdb->prepare(
			"SELECT message_id as id, from_id , to_id ,  send_at as date,read_at, display_name as sender, post_title as title , post_content as content FROM $tn LEFT JOIN $tu ON $tn.to_id=$tu.ID LEFT JOIN $tp ON $tn.post_id=$tp.ID WHERE (($tn.from_id='%d' AND $tn.to_id='%d') OR ($tn.to_id='%d' AND $tn.from_id='%d'))   ORDER BY message_id DESC;",
			$uid,
			$to_id,
			$uid,
			$to_id
		);


		$mysql_results = $wpdb->get_results($sql);
		$data = new stdClass();
		$data->found_posts = count($mysql_results);
		$data->result = $mysql_results;
		echo json_encode($data);
	}

	private function get_message()
	{
		global $wpdb;
		$posted_data =  isset($_POST) ? $_POST : array();
		$userModusRequest = Trainingssystem_Plugin_Public::isUserModusRequest();
		if (isset($posted_data["message-id"])) {
			$message_id = $posted_data["message-id"];
			$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
			$tu = $wpdb->users; //"wp_users";
			$tp = $wpdb->posts; //"wp_posts";
			$sql = $wpdb->prepare("SELECT ID as id ,from_id , to_id, post_title as title , post_content as content  FROM $tp,$tn WHERE $tp.id=$tn.post_id AND message_id=%d AND post_type='nachrichten'", $message_id);
			$mysql_results = $wpdb->get_row($sql);
			if ($mysql_results->to_id == Trainingssystem_Plugin_Public::getTrainingUser()) {
				if(!$userModusRequest){
					$this->mark_as_read($message_id);
				}
				echo json_encode($mysql_results);
			} else if ($mysql_results->from_id == Trainingssystem_Plugin_Public::getTrainingUser()) {
				echo json_encode($mysql_results);
			} else {
				exit();
			}
		}
	}
	private function mark_as_read($message_id)
	{
		global $wpdb;
		$tn = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_PREFIX . "tranings_nachrichten";
		$mysql_date_now = current_time('mysql');
		$sql = $wpdb->prepare("UPDATE $tn SET read_at = '$mysql_date_now' WHERE message_id='%d'", $message_id);
		$mysql_results = $wpdb->get_row($sql);
	}
	/**
	 * mögliche nachrichten-empfänger
	 * bei trainern, alle ihm zugehörigen user
	 * bei usern nur der trainer
	 */
	private function get_users()
	{
		// user with meta pAdminId == 1 -> Admin/Trainer
		// meta coachid = id des trainers;
		$current_user = wp_get_current_user();
		if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole('pCoach', $current_user->ID)) {
			$args = array(
				'meta_key'     => 'coachid',
				'meta_value'   => $current_user->ID,
				'meta_compare' => '=',
				"exclude" => $current_user->ID
			);
		} else if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole('supervisor', $current_user->ID)) {
			$args = ['orderby' => 'display_name', 'order' => 'ASC'];
		} else if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole('pAdmin', $current_user->ID)) {
			$args = array(
				"include" => array(0)
			);
		} else {
			$myTrainer = get_user_meta($current_user->ID, 'coachid', true);
			if(!empty($myTrainer)){
				$args = array(
					"include" => $myTrainer
				);
			}
			else{
				$args = array(
					"include" => array(0)
				);
			}
			
		}

		$posted_data =  isset($_POST) ? $_POST : array();
		if ($posted_data['userid'] !== 'null') {
			$args = array(
				"include" => $posted_data['userid']
			);
		}

		$blogusers = get_users($args);
		$result = array();
		foreach ($blogusers as $user) {
			$item = new stdClass();
			$item->name = $user->display_name;
			$item->id = $user->ID;
			$result[] = $item;
		}

		echo json_encode($result);
	}
}
