<?php
class WPAS_Email_Notification {

	public function getTemplatesTags( $content = false, $post_id = false, $reply_id = false ) {

		$assignee 	= false;
		$user 		= false;
		$post 		= false;

		if( $post_id ) {
			$post 		= get_post($post_id);
			$assignee 	= get_post_meta( $post_id, WPAS_PREFIX.'assignee', true );
			$assignee 	= get_userdata( $assignee );
			$client 	= $post->post_author;
			$user 		= get_userdata( $client );
		}

		/* Get the latest reply */
		if( $reply_id ) {
			$reply = ( $reply_id ) ? get_post( $reply_id ) : '';
		}

		$tags = array(
			array(
				'tag' 	=> '{ticket_id}',
				'value' => $post_id ? $post_id : '',
				'desc' 	=> __('Convert into ticket ID', 'wpas')
			),
			array(
				'tag' 	=> '{site_name}',
				'value' => get_bloginfo('name'),
				'desc' 	=> __('Convert into website name', 'wpas')
			),
			array(
				'tag' 	=> '{agent_name}',
				'value' => $assignee ? $assignee->data->display_name : '',
				'desc' 	=> __('Convert into agent name', 'wpas')
			),
			array(
				'tag' 	=> '{agent_email}',
				'value' => $assignee ? $assignee->data->user_email : '',
				'desc' 	=> __('Convert into agent e-mail address', 'wpas')
			),
			array(
				'tag' 	=> '{client_name}',
				'value' => $user ? $user->data->display_name : '',
				'desc' 	=> __('Convert into client name', 'wpas')
			),
			array(
				'tag' 	=> '{client_email}',
				'value' => $user ? $user->data->user_email : '',
				'desc' 	=> __('Convert into client e-mail address', 'wpas')
			),
			array(
				'tag' 	=> '{ticket_title}',
				'value' => $post ? $post->post_title : '',
				'desc' 	=> __('Convert into current ticket title', 'wpas')
			),
			array(
				'tag' 	=> '{ticket_link}',
				'value' => $post ? '<a href="'.home_url().'/?p='.$post->ID.'">'.home_url().'/?p='.$post->ID.'</a>' : '',
				'desc' 	=> __('Displays a link to public ticket', 'wpas')
			),
			array(
				'tag' 	=> '{ticket_url}',
				'value' => $post ? home_url().'/?p='.$post->ID : '',
				'desc' 	=> __('Displays the URL <strong>only</strong> (not a link link) to public ticket', 'wpas')
			),
			array(
				'tag' 	=> '{ticket_admin_link}',
				'value' => $post ? '<a href="'.home_url().'/wp-admin/post.php?post='.$post->ID.'&action=edit#wpas_ticket_replies">'.home_url().'/wp-admin/post.php?post='.$post->ID.'&action=edit</a>' : '',
				'desc' 	=> __('Displays a link to ticket details in admin (for agents)', 'wpas')
			),
			array(
				'tag' 	=> '{ticket_admin_url}',
				'value' => $post ? home_url().'/wp-admin/post.php?post='.$post->ID.'&action=edit#wpas_ticket_replies' : '',
				'desc' 	=> __('Displays the URL <strong>only</strong> (not a link link) to ticket details in admin (for agents)', 'wpas')
			),
			array(
				'tag' 	=> '{date}',
				'value' => date( get_option('date_format') ),
				'desc' 	=> __('Convert into current date', 'wpas')
			),
			array(
				'tag' 	=> '{admin_email}',
				'value' => get_bloginfo('admin_email'),
				'desc' 	=> sprintf(__('Convert into WordPress admin e-mail (<em>currently: %s</em>)', 'wpas'), get_bloginfo('admin_email'))
			),
			array(
				'tag' 	=> '{message}',
				'value' => isset( $reply ) ? $reply->post_content : '',
				'desc' 	=> __('Convert into ticket reply', 'wpas')
			)
		);

		return apply_filters( 'wpas_edit_template_tags', $tags );
	}

	/**
	 * This function converts any registered template
	 * tag into its corresponding data
	 */
	private function convertTemplatesTags( $content, $id = false, $reply_id = false ) {
		$tags = $this->getTemplatesTags( $content, $id, $reply_id );

		foreach( $tags as $tag => $data ) {
			$content = str_replace($data['tag'], $data['value'], $content);
		}

		return $content;
	}

	/**
	 * Get e-mail templates individually
	 * 
	 * @param  [type]  $option  [description]
	 * @param  boolean $default [description]
	 * @return [type]           [description]
	 */
	public function getOption( $option, $default = false) {
		if( isset($_SESSION['wpas_options']['email']) && !empty($_SESSION['wpas_options']['email']) ) {
			$options = $_SESSION['wpas_options']['email'];
		} else {
			$options = get_option(WPAS_PREFIX.'email_options', $default);
			$options = maybe_unserialize( $options );
			$_SESSION['wpas_options']['email'] = $options;
		}

		if( isset($options[$option]) ) {
			return $options[$option];
		} else {
			return $default;
		}
	}

	/**
	 * Sends the e-mail notification
	 *
	 * @param (integer) $ticket_id  The current ticket ID
	 * @param (string)  $case 		The type of notification to send
	 * @param (array)   $args 		Additional arguments
	 */
	function sendNotification( $ticket_id, $case = 'def', $args = array() ) {

		/* Defaults arguments */
		$def = array(
			'link' 		=> null,
			'ccs' 		=> null,
			'reply_id' 	=> false
		);

		/* Let's merge the arguments with default ones */
		$args 		 = array_merge( $def, $args );
		$ticket 	 = get_post( $ticket_id );
		$client_id   = $ticket->post_author;
		$agent_id    = get_post_meta( $ticket_id, WPAS_PREFIX . 'assignee', true );
		$client 	 = get_userdata( $client_id );
		$agent 		 = get_userdata( $agent_id );
		$client_mail = $client->data->user_email;
		$client_name = $client->data->user_nicename;
		$agent_mail  = $agent->data->user_email;
		$agent_name  = $agent->data->user_nicename;
		$ccs 		 = get_post_meta( $ticket_id, WPAS_PREFIX . 'ccs', true );
		$new 		 = array();
		$mail 		 = '';
		$to_agent 	 = $agent_name.' <'.$agent_mail.'>';
		$to_client 	 = $client_name.' &lt;'.$client_mail.'&gt;';

		/* Setting up the e-mail default values for fallback */
		$def = array(
			'from' 	    => $this->getOption('email_from_name', get_bloginfo('name')),
			'from_mail' => $this->getOption('email_from_mail', get_bloginfo('admin_email')),
			'to' 		=> '',
			'subject'   => '',
			'content'   => ''
		);

		$tpl = get_option( WPAS_PREFIX.'email_options', false );

		if( !$tpl )
			return;

		/* Now let's prepare the e-mail */
		switch( $case ):
			case 'submission_confirmation':
				/* We make sure the notification is enabled */
				if( $tpl['confirm_submission_to_client'] != 'yes' )
					return false;

				$new = array(
					'subject'   => $tpl['ticket_confirm_subject'],
					'content'   => $tpl['ticket_confirm_content'],
					'to' 		=> $client_mail
				);

				// $headers[] = 'To: '.$client_name.' &lt;'.$client_mail.'&gt;';
			break;
			case 'new_assignment':
				/* We make sure the notification is enabled */
				if( $tpl['email_agent_on_assignation'] != 'yes' )
					return false;

				$new = array(
					'subject'   => $tpl['new_assignment_subject'],
					'content'   => $tpl['new_assignment_content'],
					'to' 		=> $agent_mail
				);

				// $headers[] = 'To: '.$agent_name.' &lt;'.$agent_mail.'&gt;';
			break;
			case 'new_reply_from_client':
				/* We make sure the notification is enabled */
				if( $tpl['email_agent_client_reply'] != 'yes' )
					return false;

				$new = array(
					'subject'   => $tpl['client_new_reply_subject'],
					'content'   => $tpl['client_new_reply_content'],
					'to' 		=> $agent_mail
				);

				// $headers[] = 'To: '.$to_agent;

				/* Add the CCs */
				if( '' != $ccs )
					$new['ccs'] = $ccs;
			break;
			case 'new_reply_from_agent':
				/* We make sure the notification is enabled */
				if( $tpl['email_client_new_reply'] != 'yes' )
					return false;

				$new = array(
					'subject'   => $tpl['agent_new_reply_subject'],
					'content'   => $tpl['agent_new_reply_content'],
					'to' 		=> $client_mail
				);

				// $headers[] = 'To: '.$client_name.' &lt;'.$client_mail.'&gt;';

				/* Add the CCs */
				if( '' != $ccs )
					$new['ccs'] = $ccs;
			break;
			case 'ticket_was_closed':
				/* We make sure the notification is enabled */
				if( $tpl['email_client_when_closed'] != 'yes' )
					return false;

				$new = array(
					'subject'   => $tpl['closed_ticket_subject'],
					'content'   => $tpl['closed_ticket_content'],
					'to' 		=> $client_mail
				);

				// $headers[] = 'To: '.$client_name.' &lt;'.$client_mail.'&gt;';

				/* Add the CCs */
				if( '' != $ccs )
					$new['ccs'] = $ccs;
			break;

			case 'ticket_will_close':
			
				/* We make sure the notification is enabled */
				if( $tpl['wpas_ticket_will_close'] != 'yes' )
					return false;

				$new = array(
					'subject'   => $tpl['will_be_closed_ticket_subject'],
					'content'   => $tpl['will_be_closed_ticket_content'],
					'to' 		=> $client_mail
				);

				// $headers[] = 'To: '.$client_name.' &lt;'.$client_mail.'&gt;';

				/* Add the CCs */
				if( '' != $ccs )
					$new['ccs'] = $ccs;
			break;

		endswitch;

		// Convert all template tags into the right data
		foreach( $new as $key => $value ) {
			$new[$key] = $this->convertTemplatesTags( $value, $ticket_id, $args['reply_id'] );
		}

		$cfg = array_merge($def, $new);
		$cfg['content'] = wpautop( $cfg['content'] );

		$from_header = 'From: '.$cfg['from'].' <'.$cfg['from_mail'].'>';

		/* Send an HTML email */
		$headers[] = 'MIME-Version: 1.0' . "\r\n";
		$headers[] = 'Content-type: text/html; charset=UTF-8' . "\r\n";
		$headers[] = $from_header;

		if( isset($cfg['ccs']) )
			$headers[] = 'Cc: '.$cfg['ccs']; // note you can just use a simple email address

		// print_r($cfg); print_r($headers); exit;

		/* We use the wp_mail function to make it
		* easy for user to use an SMTP plugin which
		* is more reliable */
		if( wp_mail( $cfg['to'], $cfg['subject'], $cfg['content'], $headers ) ) {
			return true;
		} else {
			return false;
		}
	}
}
?>