<?php
/**
 * Quick Replies Class
 *
 * This class adds canned responses to ticket reply metabox.
 * Canned responses can be added through a custom post type
 * and will then be available as buttons under the WYSIWYG
 * editor in the ticket edit screen.
 *
 * @package WP Awesome Support
 * @since 1.2.0
 * @author Julien Liabeuf <julien.liabeuf@n2clic.com>
 */
class WPAS_Quick_Replies {

	public function __construct( $init = array() ) {

		$this->defaults = array(
			'title' 		=> __( 'Available Quick Replies:', 'wpas' ),
			'title_tag' 	=> 'h4',
			'container' 	=> 'div',
			'container_id' 	=> 'wpas-predefinedmsg'
		);

		$this->settings = array_merge( $this->defaults, $init );
		$this->replies 	= array(); // We will save all the replies data in this array
		$this->craft 	= array(); // Here will be saved the replies with the appropriate markup
		$this->tags 	= array();

		add_action( 'init', array( $this, 'listReplies' ) );
		add_action( 'init', array( $this, 'setDefaultTags' ) );
		add_action( 'init', array( $this, 'registerPostType' ), 0 );
		add_action( 'admin_menu', array( $this, 'registerMenuItem' ) );
		add_action( 'wpas_admin_after_wysiwyg', array( $this, 'echoMarkup' ) );
		add_filter( 'post_updated_messages', array( $this, 'customizeUpdateMessages' ) );
		add_filter( 'contextual_help', array( $this, 'helpTab' ), 10, 3);

	}

	public function registerPostType() {

		// Labels
		$labels = array(
			'name' 					=> _x( 'Replies', 'post type general name', 'wpas' ),
			'singular_name' 		=> _x( 'Reply', 'post type singular name', 'wpas' ),
			'add_new' 				=> __( 'Add New Reply', 'wpas' ),
			'add_new_item' 			=> __( 'Add A Reply', 'wpas' ),
			'edit_item' 			=> __( 'Edit Reply', 'wpas' ),
			'new_item' 				=> __( 'New Reply', 'wpas' ),
			'all_items' 			=> __( 'All Replies', 'wpas' ),
			'view_item' 			=> __( 'View Reply', 'wpas' ),
			'search_items' 			=> __( 'Find A Reply', 'wpas' ),
			'not_found' 			=> __( 'No Reply Found', 'wpas' ),
			'not_found_in_trash' 	=> __( 'No Reply In The Trash', 'wpas' ), 
			'parent_item_colon' 	=> '',
			'menu_name' 			=> __( 'Quick Replies', 'wpas' )
		);
	  
		$args = array(
			'labels' 				=> $labels,
			'public' 				=> true,
			'exclude_from_search' 	=> true,
			'publicly_queryable' 	=> true,
			'show_ui' 				=> true, 
			'show_in_menu' 			=> false, 
			'query_var' 			=> true,
			'rewrite' 				=> array(
				'slug' 					=> 'quick-messages',
				'with_front'			=> false
			),
			'capability_type' 		=> 'view_ticket',
			'capabilities' 			=> array(
				'read'					 => 'view_ticket',
				'read_post'				 => 'view_ticket',
				'read_private_posts' 	 => 'view_ticket',
				'edit_post'				 => 'edit_ticket',
				'edit_posts'			 => 'edit_ticket',
				'edit_others_posts' 	 => 'edit_ticket',
				'edit_private_posts' 	 => 'edit_ticket',
				'edit_published_posts' 	 => 'edit_ticket',
				'publish_posts'			 => 'create_ticket',
				'delete_post'			 => 'delete_ticket',
				'delete_posts'			 => 'delete_ticket',
				'delete_private_posts' 	 => 'delete_ticket',
				'delete_published_posts' => 'delete_ticket',
				'delete_others_posts' 	 => 'delete_ticket' ,
			),
			'has_archive' 			=> false, 
			'hierarchical' 			=> false,
			// 'menu_position' 		=> 100,
			'supports' 				=> array( 'title', 'editor' ),
			'menu_icon' 			=> WPAS_URL . 'images/icon-tickets.png'
		);

		register_post_type( 'quick-reply', $args );
	}

	public function registerMenuItem() {

		if( class_exists( 'WP_Awesome_Support' ) )
			add_submenu_page( 'edit.php?post_type=tickets', __( 'Quick Replies', 'wpas' ), __( 'Quick Replies', 'wpas' ), 'settings_tickets', 'edit.php?post_type=quick-reply' );

	}

	/**
	 * Customize the updates messages
	 */
	public function customizeUpdateMessages( $messages ) {
	  global $post, $post_ID;

	  $messages['quick-reply'] = array(
		0 => '', // Unused. Messages start at index 1.
		1 => sprintf( __('Reply updated. <a href="%s">View Reply</a>'), esc_url( get_permalink($post_ID) ) ),
		2 => __('Custom field updated.'),
		3 => __('Custom field deleted.'),
		4 => __('Reply updated.'),
		/* translators: %s: date and time of the revision */
		5 => isset($_GET['revision']) ? sprintf( __('Reply restored to version %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
		6 => sprintf( __('Reply published. <a href="%s">View Reply</a>'), esc_url( get_permalink($post_ID) ) ),
		7 => __('Reply saved.'),
		8 => sprintf( __('Reply saved. <a target="_blank" href="%s">View Reply</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
		9 => sprintf( __('Reply scheduled for : <strong>%1$s</strong>. <a target="_blank" href="%2$s">View Reply</a>'),
		  // translators: Publish box date format, see http://php.net/date
		  date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
		10 => sprintf( __('Reply draft updated. <a target="_blank" href="%s">Preview Reply</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
	  );

	  return $messages;
	}

	/**
	 * We simply get all the posts for 
	 * the "quick-reply" post type.
	 */
	public function listReplies() {

		$args = array(
			'posts_per_page' 			=> -1,
			'post_type' 				=> 'quick-reply',
			'update_post_meta_cache' 	=> false,
			'update_post_term_cache' 	=> false
		);

		$replies = new WP_Query( $args );

		if( isset( $replies->posts ) ) {

			foreach( $replies->posts as $key => $reply ) {

				$this->replies[$reply->post_name] = array(
					'title' => $reply->post_title,
					'reply' => $reply->post_content
				);

			}

		}

	}

	public function setDefaultTags() {

		/**
		 * TODO
		 *
		 * Remove product tag as it now is only dynamically registered
		 */

		global $post, $current_user, $wpas;

		/* Avoid errors for pages else than posts */
		if( !is_object( $post ) )
			return;

		$author 	= get_user_by( 'id', $post->post_author );
		$taxonomies = $wpas->getTaxonomies();

		$this->tags = array(
			'author' 			=> $author->user_nicename,
			'agent' 			=> $current_user->user_firstname,
		);

		foreach( $taxonomies as $key => $taxo ) {

			$tax 	= sanitize_title( $taxo['singular'] );
			$terms 	= get_the_terms( $post->ID, $tax );

			if( !is_wp_error( $terms ) ) {

				$term = isset( $terms[0]->name ) ? $terms[0]->name : '';
				$this->tags[$tax] = $term;

			}

		}

		return $this->tags;

	}

	public function removeTag( $tag ) {

		if( isset( $this->tags[$tag] ) )
			unset( $this->tags[$tag] );

	}

	private function convertTags( $content ) {

		$tags = $this->setDefaultTags();

		foreach( $tags as $tag => $value ) {

			$content = str_replace( '{' . $tag . '}', $value, $content );

		}

		return $content;

	}

	/**
	 * Prepare the markup to output under the
	 * WYSIWYG editor.
	 */
	public function constructMarkup() {

		/* Prevent errors due to no reply defined */
		if( !empty( $this->replies ) ) {

			$markup = '';

			foreach( $this->replies as $key => $data ) {

				/* First of all we convert the tags that might have been used */
				$reply = $this->convertTags( $data['reply'] );

				/* Then we convert the backslashes into <br> */
				$reply = str_replace( array("\r\n", "\r"), "<br>", $reply );

				$this->craft[] = '<a href="#" class="wpas-predefine" data-message="' . esc_html( $reply ) . '">' . $data['title'] . '</a>';

			}

			$this->craft = implode( ' ', $this->craft );

			/* Add the container */
			$markup = '<' . $this->settings['container'];

			/* Add the container ID */
			if( '' != $this->settings['container_id'] )
				$markup .= ' id="' . $this->settings['container_id'] . '"';

			/* Add the title */
			$markup .= '><' . $this->settings['title_tag'] . '>' . $this->settings['title'] . '</' . $this->settings['title_tag'] . '>';


			/* Add the content */
			$markup .= $this->craft;

			/* Close container */
			$markup .= '</' . $this->settings['container'] . '>';

			$this->craft = ( !empty( $this->craft ) ) ? $markup : '';

		} else {
			$this->craft = false;
		}

	}

	public function getMarkup() {

		$this->constructMarkup();

		return $this->craft;

	}

	public function echoMarkup() {

		echo $this->getMarkup();

	}

	function helpTab() {

		global $wpas;

		if( !isset( $_GET['post_type'] ) || $_GET['post_type'] != 'quick-reply' ) {
			return;
		}

		// $taxonomies = $wpas->getTaxonomies();
		$custom 	= array();
		$default 	= array( 'type', 'priority', 'state' );

		$ul = '<ul>
		<li><code>{author}</code>: the ticket author username</li>
		<li><code>{agent}</code>: the current agent name</li>
		<li><code>{type}</code>: ticket type</li>
		<li><code>{priority}</code>: ticket priority</li>
		<li><code>{state}</code>: current state of the ticket <em>(open or closed)</em></li>
		</ul>';

		if( isset( $taxonomies ) && !empty( $taxonomies ) ) {

			foreach( $taxonomies as $key => $taxo ) {

				$tax = sanitize_title( $taxo['singular'] );

				if( !in_array( $tax, $default ) )
					array_push( $custom, '<li><code>{' . $tax . '}</code></li>' );				

			}

			if( !empty( $custom ) ) {

				$custom = implode( '', $custom );
				$ul .= '<h2>Custom Taxonomies</h2><ul>' . $custom . '</ul>';

			}

		}
		
		$screen = get_current_screen();
		
		$screen->add_help_tab( array(
			'id'      => 'tags',
			'title'   => __( 'Template Tags', 'wpas' ),
			'content' => sprintf( __( '<h2>Quick Reply Template Tags</h2><p>Here is the list of all template tags you can use: %s', 'wpas' ), $ul )
		) );
	}
}

$quick_reply = new WPAS_Quick_Replies;