<?php
class WPAS_Tickets_Submission {

	public function __construct() {

		if( isset( $_POST['ticket_issue'] ) )
			add_action( 'wp_loaded', array( $this, 'submitNewTicket' ) );

		if( isset( $_POST['ticket'] ) )
			add_action( 'wp_loaded', array( $this, 'submitClientReply' ) );

		if( is_admin() ) {

			add_action( 'save_post', array( $this, 'saveAgentReply' ) );
			add_action( 'init', array( $this, 'addNote' ) );

		}

		add_action( 'wpas_before_ticket_submit', array( $this, 'notificationMessages' ) ); 	// Hook the notification messages
		add_action( 'wpas_before_ticket_submit', array( $this, 'freeNotice' ) );			// Add free notice before ticket submission form
		add_action( 'wpas_before_registration_form', array( $this, 'addCaptchaScript' ) );
		add_action( 'wpas_after_registration_fields', array( $this, 'addCaptcha' ) );

	}
	
	/**
	 * Submit a new ticket
	 *
	 * @return (mixed) Ticket ID
	 */
	public function submitNewTicket() {

		global $wpas;

		/* We get the current user information */
		if( is_user_logged_in() ) {
			global $current_user;
			$user 		= $current_user->ID;
			$username 	= $current_user->data->user_nicename;
		}

		/* If anonymous posting is allowed then set user to null */
		elseif( wpas_get_option( 'allow_ticket_without_registering' ) == 'yes' ) {
			$user = 0;
			$username = 0;
		}

		/* If user isn't lodden-in and anonymous posting isn't enabled we cancel */
		else {
			return;
		}

		/* We check the nonce for security purpose */
		if( !isset($_POST['submit_ticket']) || !wp_verify_nonce( $_POST['submit_ticket'], 'submit' ) ) {

			/* Save all the fields values for later use in the form */
			$this->saveValues( false, __( 'It seems that your submission is invalid (nonce couldn\'t be validated)', 'wpas' ) );

			/* Abort */
			return;
		}

		/* Prepare an array with the incorrect fields */
		$incorrect = array();

		/* Get allowed HTML tags */
		$allowed_tags = wp_kses_allowed_html( 'post' );

		/**
		* The description field can be either ticket_issue or ticket_issue_simple.
		* Thus, we check which one has been submitted and make sure something has actually
		* been submitted
		*/
		if( '' != $_POST['ticket_issue'] ) {

			/* If content comes from the WYSIWYG */
			$content = wp_kses( $_POST['ticket_issue'], wp_kses_allowed_html( 'post' ) );

		} elseif( '' != $_POST['ticket_issue_simple'] ) {

			/* If content comes from the textarea */
			$content = wp_kses( $_POST['ticket_issue_simple'], wp_kses_allowed_html( 'post' ) );

		} else {

			/* Save all the fields values for later use in the form */
			$this->saveValues( false, __( 'You did not provide a description for your issue.', 'wpas' ) );

			/* We register the missing fields */
			array_push( $incorrect, 'ticket_issue' );
			array_push( $incorrect, 'ticket_issue_simple' );

		}

		/* List fields to check */
		$validate = array(
			'ticket_priority',
			'ticket_type',
			'ticket_subject'
		);

		/**
		* We check if all the mandatory fields are correctly filled-in.
		*/
		foreach( $validate as $field ) {

			if( '' == $_POST[$field] ) {

				/* We register the missing field */
				array_push( $incorrect, $field );

				$label = explode( '_', $field );

				/* Save all the fields values for later use in the form */
				$this->saveValues( false, sprintf( __( 'Please fill in the %s field', 'wpas' ), $label[1] ) );
			}
		}

		/* If there are incorrect fields, we break the function */
		if( !empty( $incorrect ) ) {

			/* Save the incorrect fields in session */
			$_SESSION['formtmp']['incorrect'] = $incorrect;

			/* Exit the function */
			return;
		}

		/**
		 * License validation
		 */
		if( 'yes' == wpas_get_option( 'envato_purchase_mandatory' ) ) {

			/* Licence number */
			$license = sanitize_key( $_POST['envato_purchase'] );

			/* Validate the item licence if needed */
			$validated = $this->AuthorizeLicence( $license );

			/* Cancel ticket submission if license is not valid */
			if( !$validated ) {

				/* Save all the fields values for later use in the form */
				$this->saveValues( $content, apply_filters( 'wpas_incorrect_envato_licence', __( 'The license number is incorrect.', 'wpas' ) ) );

				/* Exit the function */
				return;

			}

		}

		$state = wpas_get_option( 'default_state' );

		/* Check if tags are submitted */
		if( isset( $_POST['tags'] ) && $_POST['tags'] != '' )
			$tags = $_POST['tags'];

		/* All the other info is mendatory */
		$subject  = esc_html( $_POST['ticket_subject'] );
		$content  = wpautop( $content );
		$priority = $_POST['ticket_priority'];
		$type 	  = $_POST['ticket_type'];

		$post = array(
			'post_author'	=> $user,
			'post_content' 	=> $content,
			'post_status' 	=> 'publish',
			'post_type' 	=> 'tickets',
			'post_title' 	=> $subject,
			'comment_status' => 'closed'
		);

		$ticket = wp_insert_post( $post, false );

		if( !is_wp_error($ticket) ) {

			/* Add the ticket tags */
			if( isset($tags) )
				wp_set_post_tags( $ticket, $tags, true );

			/* Get the assignee for this ticket*/
			$assignee = $this->getAssignee( $type );

			/* Assign ticket to an agent */
			update_post_meta( $ticket, WPAS_PREFIX.'assignee', $assignee );
			
			/* And notify by email */
			$email = new WPAS_Email_Notification();
			$email->sendNotification( $ticket, 'new_assignment' );
			$email->sendNotification( $ticket, 'submission_confirmation' );

			/* Add Envato purchase license */
			if( isset($license) )
				update_post_meta( $ticket, WPAS_PREFIX.'envato_purchase_license', $license );

			if( $validated )
				update_post_meta( $ticket, WPAS_PREFIX . 'envato_purchased_item', $validated );

			/* Save Envato purchase status */
			if( isset($validated) )
				update_post_meta( $ticket, WPAS_PREFIX.'envato_purchased', 'yes' );

			/* Define the status as open */
			wp_set_object_terms( $ticket, 'wpas-open', 'status', false );

			/* Define the status as open */
			if( $state )
				wp_set_object_terms( $ticket, $state, 'state', false );

			/**
			 * Now let's deal with ticket properties and custom tax
			 */
			$taxonomies = $this->getFrontEndTaxonomies();

			foreach( $taxonomies as $taxonomy => $data ) {

				/* If the current taxonomy hasn't been submitted we continue */
				if( !isset( $_POST["ticket_$taxonomy"] ) )
					continue;

				wp_set_object_terms( $ticket, $_POST["ticket_$taxonomy"], $taxonomy, false );
			}

			/**
			 * Deal with custom text fields
			 */
			$cf = $wpas->getCustomFields();

			foreach( $cf as $fid => $field ) {

				$name = $field['name'];

				if( isset( $_POST[$name] ) && '' != $_POST[$name] ) {

					update_post_meta( $ticket, 'wpas_' . $field['name'], $_POST[$name] );

				}

			}

			/* Log the ticket creation */
			$this->LogTicketHistory($ticket, 'open', 'inherit', 'ticket_status', array('wpautop' => false));

			/* Save attachments */
			$this->saveAttachments( $ticket );

			if( !headers_sent() ) {
				wp_redirect( add_query_arg( 'message', '1', get_permalink($ticket) ), 302 );
				exit;
			} else {
				$_SESSION['formtmp']['success'] = sprintf(__('Your ticket has been submitted. <a href="%s">Click here to view</a>.', 'wpas'), get_permalink( $ticket ));
				return $ticket;
			}
		} else {
			return;
		}
	}

	/**
	 * Check the licence validity
	 *
	 * The function will check licence validity
	 * based on the system defined in the settings.
	 * Currently supported:
	 * - Envato
	 *
	 * @param (string) 	Licence to check
	 * @return (string) Licence validity
	 */
	private function AuthorizeLicence( $license = false ) {

		/* Set the purchase to false */
		$purchase = false;

		/**
		 * We base the default state on the fact that
		 * the licence number is mendatory or not.
		 */
		if( 'yes' == wpas_get_option( 'envato_purchase_mandatory', 'no' ) ) {

			$validated = apply_filters( 'wpas_set_default_validation_status', 'no' );

		} else {

			$validated = apply_filters( 'wpas_set_default_validation_status', 'yes' );

		}

		/* Call Envato API to verify license */
		if( $license && '' != $license ) {

			do_action( 'wpas_before_envato_licence_check', $license );
			
			$purchase = wpas_verify_envato_purchase( false, $license );

		}

		return $purchase;

	}

	/**
	 * We check if a client reply has been submitted
	 * and save it if so.
	 */
	function submitClientReply() {

		if( !isset( $_POST['ticket'] ) )
			return;

		if( is_user_logged_in() )
			global $current_user;

		$post   = get_post( $_POST['ticket'] );
		$author = get_userdata( $post->post_author );
		$verify = md5($author->data->user_email);

		if( !isset( $_POST['client_reply'] ) || !wp_verify_nonce( $_POST['client_reply'], 'send_reply' ) )
			return;

		if( !is_user_logged_in() && wpas_get_option( 'ticket_reading' ) == 'token' && $verify != $_POST['token'] )
			return;

		/**
		 * If the user wanna close the ticket
		 */
		if( isset( $_POST['close_ticket'] ) && 'true' == $_POST['close_ticket'] ) {

			/* Define the status as open */
			wp_set_object_terms( $post->ID, 'wpas-close', 'status', false );

			/* We save the new ticket status */
			$this->LogTicketHistory( $post->ID, 'close', 'inherit', 'ticket_status', array( 'wpautop' => false ) );

		}

		/**
		 * Here we define which field contains the user reply
		 */
		if( isset( $_POST['user_reply'] ) && $_POST['user_reply'] != '' ) {

			$user_reply = $_POST['user_reply'];

		} elseif( isset( $_POST['user_reply_mobile'] ) && $_POST['user_reply_mobile'] != '' ) {

			$user_reply = $_POST['user_reply_mobile'];

		} else {

			/* Don't go any further */
			wp_redirect( get_permalink( $post->ID ) );
			exit;

		}

		$reply = $this->LogTicketHistory( $_POST['ticket'], $user_reply, 'inherit', 'ticket_reply' );

		if( !is_wp_error( $reply ) ) {

			/* Save attachments */
			$this->saveAttachments( $reply );

			$email = new WPAS_Email_Notification();
			$email->sendNotification( $post->ID, 'new_reply_from_client', array( 'reply_id' => $reply ) );

			/**
			 * wpas_after_client_post_reply hook
			 *
			 * @since 2.0.3
			 */
			do_action( 'wpas_after_client_post_reply', $reply );

			if( !headers_sent() ) {

				wp_redirect( add_query_arg( 'message', '2', get_permalink($_POST['ticket']) ), 302 );
				exit;
				
			}


		} else {

			/* Don't go any further */
			wp_redirect( get_permalink( $post->ID ) );
			exit;

		}
	}

	/**
	 * While ticket submission, if a field is incorrect, we save the
	 * values of all fields so that the user doesn't have to re-type
	 * everything.
	 */
	function saveValues( $content = false, $error = false ) {

		/* Default error message */
		if( !$error ) { $error = __( 'Your ticket couldn\'t be submitted. Please make sure you filled all the required fields.', 'wpas' );  }

		foreach( $_POST as $key => $value )
			$_SESSION['formtmp'][$key] = $value;

		/*if( isset($_POST['ticket_priority']) && !isset($_SESSION['formtmp']['ticket_priority']) )
			$_SESSION['formtmp']['ticket_priority'] = $_POST['ticket_priority'];

		if( isset($_POST['ticket_type']) && !isset($_SESSION['formtmp']['ticket_type']) )
			$_SESSION['formtmp']['ticket_type'] = $_POST['ticket_type'];

		if( isset($_POST['ticket_product']) && !isset($_SESSION['formtmp']['ticket_product']) )
			$_SESSION['formtmp']['ticket_product'] = $_POST['ticket_product'];

		if( isset($_POST['ticket_subject']) && !isset($_SESSION['formtmp']['ticket_subject']) )
			$_SESSION['formtmp']['ticket_subject'] = $_POST['ticket_subject'];

		if( isset( $content ) && !isset($_SESSION['formtmp']['ticket_issue']) )
			$_SESSION['formtmp']['ticket_issue'] = $content;

		if( isset($_POST['envato_purchase']) && !isset($_SESSION['formtmp']['envato_purchase']) )
			$_SESSION['formtmp']['envato_purchase'] = $_POST['envato_purchase'];

		if( isset($_POST['hidden-tags']) && !isset($_SESSION['formtmp']['tags']) )
			$_SESSION['formtmp']['tags'] = $_POST['tags'];*/

		$_SESSION['formtmp']['error'] = $error;
	}

	public function get_field_value( $id ) {

		if( isset( $_SESSION['formtmp'][$id] ) )
			return $_SESSION['formtmp'][$id];
		else
			return false;

	}

	public function populate_fields_values( $id ) {

		$value = $this->get_field_value( $id );

		if( isset( $_SESSION['formtmp'][$id] ) )
			echo "value='$value'";

	}

	/**
	 * Saves agents replies in the backend
	 * 
	 * @param  (numeric) Current post ID
	 */
	public function saveAgentReply( $post_id ) {

		global $current_user, $wpas;

		// verify if this is an auto save routine. 
		// If it is our form has not been submitted, so we dont want to do anything
		if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || wp_is_post_revision($post_id) )
			return;

		// verify this came from the our screen and with proper authorization,
		// because save_post can be triggered at other times
		if ( !isset($_POST['ticket_details']) || isset($_POST['ticket_details']) && !wp_verify_nonce( $_POST['ticket_details'], 'update_ticket') )
			return;

		// Check permissions
		if( !isset($_POST['post_type']) || isset($_POST['post_type']) && 'tickets' != $_POST['post_type'] )
			return;

		if( !current_user_can( 'edit_post', $post_id ) )
			return;

		// OK, we're authenticated: we need to find and save the data
		$options = array(
			'assignee',
			'ccs',
		);

		$taxo 	 = $wpas->getTaxonomies();
		$actions = array();
		$email 	 = new WPAS_Email_Notification();

		/* Prevent the infinite loop due to $this->LogTicketHistory() */
		remove_action('save_post', 'wpas_save_ticket_details');

		/* We save the "regular" options here */
		foreach( $options as $option ) {
			/* Reset $msg */
			$msg = '';

			if( !isset($_POST[$option]) )
				continue;

			$opt = WPAS_PREFIX . $option;
			$prev = get_post_meta( $post_id, $opt, true );

			/**
			 * We suppose the option is the assignee as it is the only
			 * numeric value. We'll try to improve this in future versions
			 */
			$value = $_POST[$option];
			if( is_numeric($_POST[$option]) ) {
				$usr_data = get_userdata( $_POST[$option] );
				if( $usr_data ) {
					$value = $usr_data->data->display_name;
					if( $usr_data->data->ID != $current_user->data->ID )
						$msg = sprintf(__('<strong>%s</strong> assigned the ticket to <strong>%s</strong>.', 'wpas'), $current_user->display_name, $value);
				}
			} else {
				if( empty($actions) ) {
					$msg = sprintf(__('<strong>%s</strong> changed <strong>%s</strong> to <strong>%s</strong>.', 'wpas'), $current_user->display_name, $option, $value);
				} elseif( count($actions) >= 1 ) {
					$msg = sprintf(__(' <strong>%s</strong> changed to <strong>%s</strong>.', 'wpas'), ucwords($option), $value);
				}
			}

			/* If meta didn't previously exist */
			if( '' == $prev ) {
				/* And if posted data is not empty */
				if( '' != $_POST[$option] ) {

					update_post_meta( $post_id, $opt, $_POST[$option] );

					if( $msg != '' )
						array_push($actions, $msg);
				}

				/* Let's also send a mail to the agent the ticket has been assigned to */
				if( 'assignee' == $option )
					$email->sendNotification( $post_id, 'new_assignment' );
			}
			/* If the meta exists already */
			else {
				/* If new value is empty we delete the meta */
				if( '' == $_POST[$option] ) {
					delete_post_meta( $post_id, $opt, $prev );
					if( empty($actions) ) {
						$msg = sprintf(__('<strong>%s</strong> deleted <strong>%s</strong>.', 'wpas'), $current_user->display_name, $option);
					} elseif( count($actions) >= 1 ) {
						$msg = sprintf(__(' <strong>%s</strong> deleted.', 'wpas'), ucwords($option));
					}
					if( $msg != '' )
						array_push($actions, $msg);
				}
				/* If not we update it */
				elseif( $prev != $_POST[$option] ) {
					update_post_meta( $post_id, $opt, $_POST[$option], $prev );
					/* Send the notification to new agent */
					if( 'assignee' == $option )
						$email->sendNotification( $post_id, 'new_assignment' );

					if( $msg != '' )
						array_push($actions, $msg);
				}
			}
		}

		/**
		 * Update / Save the custom taxonomies
		 */
		foreach( $taxo as $taxonomy ) {

			$tax = sanitize_title( $taxonomy['id'] );

			/* Check if the current taxonomy has been submitted */
			if( !isset( $_POST[$tax] ) )
				continue;

			/**
			 * As this function is called for tickets updates too,
			 * we check if the current taxonomy has been modified.
			 * If not, we continue the loop.
			 */
			$term 	= false;
			$terms  = get_the_terms( $post_id, $tax );

			/* We extract the current term */
			if( is_array($terms) ) {
				foreach($terms as $t) {
					$term = $t->slug;
				}
			}

			/* Here we break the loop if the taxo hasn't changed */
			if( $term == $_POST[$tax] )
				continue;

			// Let's log the ticket history for the other taxonomies
			if( $terms ) {
				if( empty($actions) ) {
					$msg = sprintf(__('<strong>%s</strong> changed <strong>%s</strong> to %s.', 'wpas'), $current_user->display_name, $tax, $_POST[$tax]);
				} elseif( count($actions) >= 1 ) {
					$msg = sprintf(__(' <strong>%s</strong> changed to %s.', 'wpas'), $tax, $_POST[$tax]);
				}

				array_push($actions, $msg);
			}

			wp_set_object_terms( $post_id, $_POST[$tax], $tax, false );
		}

		/* If current taxo is a status we need to isolate the action */
		if( isset( $_POST['status'] ) ) {

			$terms  = get_the_terms( $post_id, 'status' );

			/* Avoid updating the status if there is no change */
			if( $_POST['status'] != $terms[0]->slug ) {

				/* We remove the term prefix */
				$lib = explode( '-', $_POST['status'] );

				/* We save the new ticket status */
				$this->LogTicketHistory( $post_id, $lib[1], 'inherit', 'ticket_status', array('wpautop' => false) );

				/* If ticket has been closed we notify the client */
				if( $_POST['status'] == 'wpas-close' ) {

					$email->sendNotification( $post_id, 'ticket_was_closed' );
					$do_close = true;
				}

				/* Update the ticket status */
				wp_set_object_terms( $post_id, $_POST['status'], 'status', false );

			}
		}

		/* We save the ticket reply */
		if( isset($_POST['ticket_reply']) && '' != $_POST['ticket_reply'] && current_user_can( 'reply_ticket', $post_id ) ) {

			$reply = $this->LogTicketHistory( $post_id, $_POST['ticket_reply'], 'inherit', 'ticket_reply' );

			if( !is_wp_error($reply) ) {

				/* Save attachments */
				$this->saveAttachments( $reply );

				/* Send an email to the client */
				$email->sendNotification( $post_id, 'new_reply_from_agent', array( 'reply_id' => $reply ) );

				/* Add an action hook here for additional processing */
				do_action( 'wpas_after_save_reply', $reply );
			}
		}

		/* If the agent modified a reply */
		$reply_redirect = false;

		if( isset( $_POST['wpas_edit_reply'] ) ) {

			foreach( $_POST['wpas_edit_reply'] as $rid => $edit ) {

				if( '' != $edit ) {

					wp_update_post( array( 'ID' => $rid, 'post_content' => wp_kses_post( $edit ) ) );
					$reply_redirect = $rid;

				}

			}

		}

		/* Finally, we check if the user wanted to close the ticket with his reply */
		if( isset($_POST['do']) && $_POST['do'] == 'reply_close' ) {
			wp_set_object_terms( $post_id, 'wpas-close', 'status', false );
			$this->LogTicketHistory($post_id, 'close', 'inherit', 'ticket_status', array('wpautop' => false));
			$email->sendNotification( $post_id, 'ticket_was_closed' );
		}

		/* We log all the actions that has been performed */
		if( !empty($actions) ) {
			$actions = implode('', $actions);
			$this->LogTicketHistory( $post_id, $actions, 'inherit', 'ticket_history', array('wpautop' => false) );
		}

		/**
		 * Last thing, if the agent closed the ticket, we redirect him to the tickets list
		 */
		if( isset($_POST['do']) && $_POST['do'] == 'reply_close' || isset( $do_close ) && $do_close ) {

			/* Does the user want to see all states? */
			$show = wpas_get_option( 'only_list_open', 'no' );

			/* Get CPT slug */
			$slug = $wpas->getPostTypeSlug();

			if( 'yes' == $show ) {

				/* Get the open term ID */
				$term = get_term_by( 'slug', 'wpas-open', 'status' );

				/* Open term ID */
				$term_id = $term->term_id;

				/* Prepare URL */
				$url = add_query_arg( array( 'status' => $term_id ), admin_url( 'edit.php?post_type=' . $slug ) );

			} else {
				$url = admin_url( 'edit.php?post_type=' . $slug );
			}

			wp_redirect( $url );
			exit;

		}

		if( $reply_redirect ) {

			$redirect = add_query_arg( array( 'post' => $post_id, 'action' => 'edit', 'message' => 1 ), 'post.php') . '#wpas-post-' . $reply_redirect;

		} else {

			$back = wpas_get_option( 'reply_and_back', 'yes' );

			/* Does the agent want to be redirected to tickets list? */
			if( 'yes' == $back ) {

				/* Does the user want to see all states? */
				$show = wpas_get_option( 'only_list_open', 'no' );

				/* Get CPT slug */
				$slug = WP_Awesome_Support::getPostTypeSlug();

				if( 'yes' == $show ) {

					/* Get the open term ID */
					$term = get_term_by( 'slug', 'wpas-open', 'status' );

					/* Open term ID */
					$term_id = $term->term_id;

					/* Prepare URL */
					$redirect = add_query_arg( array( 'status' => $term_id ), admin_url( 'edit.php?post_type=' . $slug ) );

				} else {
					$redirect = admin_url( 'edit.php?post_type=' . $slug );
				}

			} else {

				$redirect = add_query_arg( array( 'post' => $post_id, 'action' => 'edit', 'message' => 1 ), 'post.php') . '#wpas-post-' . $reply;

			}

		}

		/* Redirect to the new reply */
		wp_redirect( $redirect );
		exit;
	}

	/**
	 * Add private note
	 *
	 * @since 2.0.0
	 */
	public function addNote() {

		if( isset( $_POST['wpas_note'] ) && '' != $_POST['wpas_note'] && isset( $_POST['post_id'] ) ) {

			if( isset( $_POST['_wpas_note_nonce'] ) && wp_verify_nonce( $_POST['_wpas_note_nonce'], 'add_note' ) ) {

				$note = wp_kses_post( $_POST['wpas_note'] );
				$id   = intval( $_POST['post_id'] );

				$new  = wp_insert_post( array( 'post_content' => $_POST['wpas_note'], 'post_parent' => $id, 'post_status' => 'private', 'post_type' => 'ticket_note' ) );

				/* Transfer the ticket */
				if( isset( $_POST['add_transfer'] ) && isset( $_POST['wpas_agent'] ) ) {

					$agent = intval( $_POST['wpas_agent'] );
					update_post_meta( $id, 'wpas_ticket_assignee', $agent );

					/* Does the user want to see all states? */
					$show = wpas_get_option( 'only_list_open', 'no' );

					/* Get CPT slug */
					$slug = WP_Awesome_Support::getPostTypeSlug();

					if( 'yes' == $show ) {

						/* Get the open term ID */
						$term = get_term_by( 'slug', 'wpas-open', 'status' );

						/* Open term ID */
						$term_id = $term->term_id;

						/* Prepare URL */
						$url = add_query_arg( array( 'post_type' => 'tickets', 'status' => $term_id ), admin_url( 'edit.php' ) );

					} else {
						$url = add_query_arg( array( 'post_type' => 'tickets' ), admin_url( 'edit.php' ) );
					}

					wp_redirect( $url );
					exit;

				}

				wp_redirect( add_query_arg( array( 'post' => $id, 'action' => 'edit' ), admin_url( 'post.php' ) ) . '#wpas-post-' . $new );
				exit;

			}

		}

	}

	/**
	 * Log Ticket Actions History
	 *
	 * This function saves every action done by
	 * an agent or admin to the ticket. It is saved
	 * in the posts table using the ticket_history
	 * post type.
	 * 
	 * @param (integer) $post_id Post ID
	 * @param (string) $action  Action to save
	 * @param (string) $status  Status of the post
	 * @param (string) $type    Post type to use while saving
	 * @param (array)  $args    Additional arguments
	 * @return (integer)		New post ID
	 */
	public function LogTicketHistory( $post_id, $action, $status = 'inherit', $type = 'ticket_history', $args = array() ) {
		/* Defaults */
		$def = array(
			'wpautop' => true,
			'user' => ''
		);

		$args = array_merge( $def, $args );

		if( $args['user'] == '' || !is_numeric($args['user']) ) {
			if( is_user_logged_in() ) {
				$user = wp_get_current_user();
				$user = $user->data->ID;
			} else {
				$user  = 0;
			}
		} else {
			$user = $args['user'];
		}

		if( $args['wpautop'] )
			$action = wpautop( $action );

		$post = array(
			'post_author'	=> $user,
			'post_content' 	=> $action,
			'post_parent' 	=> $post_id,
			'post_status' 	=> $status,
			'post_type' 	=> $type
		);

		$reply = wp_insert_post( $post, true );

		return $reply;
	}

	/**
	 * Get agent to assign the ticket to
	 * 
	 * This function will determine who to assign
	 * a new ticket to. If auto-assignment is
	 * enabled, the ticket will be assigned
	 * to the most available agent. It can be
	 * based on the agent's group or not depending
	 * on the plugin settings.
	 *
	 * @param (string) The desired group the agent should belong to
	 * @return (mixed) Agent ID or false
	 */
	public function getAssignee( $type = false ) {

		$auto 	 = wpas_get_option( 'ticket_auto_assignment', 'no' );
		$default = wpas_get_option( 'default_assignee', false );
		$mode 	 = wpas_get_option( 'assignment_mode', 'standard' );
		$usr 	 = array();
		$agent 	 = false;

		if( $auto == 'yes' ) {
			switch( $mode ):
				case 'standard':
					$usr = array();
				break;
				case 'group':
					if( $type ) {
						$usr['meta_key'] 	= 'wpas_user_group';
						$usr['meta_value']  = $type;
					}
				break;
			endswitch;

			$users = get_users( $usr );
			$best  = array();

			if( empty($users) )
				return apply_filters( 'wpas_assignee_id', $default );

			foreach( $users as $user ) {

				if( !array_key_exists('create_ticket', $user->allcaps) )
					continue;

				$args = array(
					'meta_key' 	 => WPAS_PREFIX.'assignee',
					'meta_value' => $user->ID,
					'post_type'  => 'tickets',
					'post_status'=> 'publish',
					'status' 	 => 'wpas-open'
				);

				$agent_tickets = get_posts( $args );
				$nb 		   = count($agent_tickets);

				if( !empty($best) ) {
					if( $nb < $best['count'] ) {
						$best = array('agent' => $user->ID, 'count' => $nb);
					}
				} else {
					$best = array('agent' => $user->ID, 'count' => $nb);
				}
			}

			$agent = !empty($best) ? $best['agent'] : $default;

		} elseif( $default ) {
			$agent = $default;
		}

		return apply_filters( 'wpas_assignee_id', $agent );
	}

	/**
	 * Get taxonomies for use in front-end
	 *
	 * We get all the taxonomies (default+custom) and filter the ones that have to be displayed on the front-end
	 * 
	 * @return (array) List of taxonomies to show
	 * @since 2.0.0
	 * @package WP Awesome Support
	 * @subpackage WPAS_Tickets_Submission
	 */
	public function getFrontEndTaxonomies() {

		global $wpas;

		/* All taxonomies */
		$taxonomies = $wpas->getTaxonomies();

		/* The list to use in front-end */
		$new = array();

		foreach( $taxonomies as $tax ) {

			/* We don't wanna show the states */
			if( 'state' == $tax['id'] )
				continue;

			$new[sanitize_title( $tax['id'] )] = array( 'label' => $tax['singular'], 'required' => $tax['required'] );

		}

		$new = array_reverse( $new );

		return apply_filters( 'wpas_ticket_properties', $new );

	}

	function notificationMessages() {

		global $wpas_notification;

		/**
		 * Check if success notification is available
		 */
		if( isset($_SESSION['register']['succes']) ) {

			/* Remove the notification trigger */
			unset($_SESSION['register']['succes']);

			/* Display notification */
			$wpas_notification->notification( 'success', sprintf( __( 'Your account has been successfully created. You can now post support tickets. If you are not redirected to the ticket submission, <a href="%s">please click here</a>.', 'wpas' ), get_permalink($post->ID) ) );

		}

		/**
		 * Check for other notifications
		 */
		if( isset( $_GET['message'] ) ) {

			/* Display notification */
			$wpas_notification->notification( $_GET['message'] );
		}

		/**
		 * This message is just a fallback in case
		 * headers messed up with the redirect
		 */
		if( isset($_SESSION['formtmp']['success']) ) {

			$wpas_notification->notification( 'success', $_SESSION['formtmp']['success'] ); ?>

			<script type="text/javascript">window.location.replace("<?php echo add_query_arg( 'message', '1', get_permalink( wpas_get_option('ticket_list') ) ); ?>");</script>

		<?php }

		if( isset($_SESSION['formtmp']['error']) ) {

			$wpas_notification->notification( 'failure', $_SESSION['formtmp']['error'] );

		}

	}

	public function freeNotice() {

		global $wpas_notification;

		$notice = wpas_get_option( 'pre_submission_notice', '' );

		if( '' == $notice )
			return;

		$wpas_notification->notification( 'info', $notice );

	}

	public function addCaptcha() {

		echo wpas_get_captcha();

	}

	public function addCaptchaScript() {

		$equiv = array(
			'en_US' => 'en',
			'en_AU' => 'en',
			'en_GB' => 'en',
			'en_CA' => 'en',
			'nl_NL' => 'nl',
			'fr_FR' => 'fr',
			'de_DE' => 'de',
			'pt_PT' => 'pt',
			'pt_BR' => 'pt',
			'ru_RU' => 'ru',
			'es_ES' => 'es',
			'es_PE' => 'es',
			'tr_TR' => 'tr'
		);

		$lang = isset( $equiv[WPLANG] ) ? $equiv[WPLANG] : 'en';

		if( 'disable' == wpas_get_option( 'plugin_style' ) ) {

			?>
			<script type="text/javascript">
			var RecaptchaOptions = {
				theme : 'clean',
				lang : '<?php echo $lang; ?>'
			};
			</script>
			<?php

		} else {

			?>
			<script type="text/javascript">
			var RecaptchaOptions = {
				lang : '<?php echo $lang; ?>',
				theme : 'custom',
	    		custom_theme_widget: 'wpas-recaptcha'
			};
			</script>
			<?php

		}

	}

	/**
	 * Get posted attachments
	 * 
	 * @return (boolean) List of attached files
	 * @since 2.0.3
	 */
	public function get_posted_attachments() {

		$uploader = wpas_get_option( 'upload_script', 'fineuploader' );

		/* Set the result to false */
		$files = false;

		if( !isset( $_POST['attachments'] ) || empty( $_POST['attachments'] ) )
			return false;

		switch( $uploader ):

			case 'fineuploader':

				if( !empty( $_POST['attachments'] ) && !empty( $_POST['filenames'] ) ) {

					/* We make sure we have the same number of files and filenames */
					if( count( $_POST['attachments'] ) == count( $_POST['filenames'] ) ) {
						$files = array();

						/* Associate file with its name */
						foreach( $_POST['attachments'] as $key => $attch ) {
							$files[] = array( 'file' => $attch, 'filename' => sanitize_file_name( $_POST['filenames'][$key] ), 'uploader' => 'fineuploader' );
						}
					}
				}

			break;

			case 'filepicker':

				$attachments = json_decode( urldecode( $_POST['attachments'] ) );

				if( !empty( $attachments ) ) {

					/* We'll save all attachments in this array */
					$files = array();

					foreach( $attachments as $key => $attachment ) {

						$files[] = array( 'file' => $attachment->url, 'filename' => sanitize_file_name( $attachment->filename ), 'mime' => $attachment->mimetype, 'size' => $attachment->size, 'uploader' => 'filepicker' );

					}

				}

			break;

		endswitch;

		return $files;

	}

	/**
	 * Save attachments
	 * 
	 * @param  (integer) $post_id ID of the submitted post
	 */
	public function saveAttachments( $post_id ) {

		$files = $this->get_posted_attachments();

		if( $files ) {

			/* Save the post meta */
			update_post_meta( $post_id, WPAS_PREFIX . 'attachments', $files );

		}

	}

}

$wpas_submit = new WPAS_Tickets_Submission();