<?php
add_action( 'add_meta_boxes', 'wpas_add_replies_widget' );
/**
 * Register the metabox
 */
function wpas_add_replies_widget() {
	add_meta_box( 'wpas_ticket_replies', __('Solve This Issue', 'wpas'), 'wpas_ticket_replies', wpas_get_slug(), 'normal', 'default' );
}

function wpas_ticket_replies() {

	global $post; ?>

	<table class="form-table">
		<tbody>
			<?php
			$global_options = get_option( 'wpas_plugin_options', array() );

			/* Get ticket status */
			$status  = get_the_terms( $post->ID, 'status' );
			if( $status ) {
				foreach($status as $s) {
					$status = $s->slug;
					$lib = explode('-', $status);
				}
			}

			/* If the post hasn't been saved yet we do not display the metabox's content */
			if( !$status ): ?>

				<div class="updated below-h2" style="margin-top: 2em;">
					<h2 style="margin: 0.5em 0; padding: 0; line-height: 100%;"><?php _e('Create Ticket', 'wpas'); ?></h2>
					<p><?php _e('Please save this ticket to reveal all options.', 'wpas'); ?></p>
				</div>

			<?php else:
			
			/* We check if Envato purchase verification is enabled */
			if( wpas_get_option('envato_check', 'no') == 'yes' ) {

				if( wpas_verify_envato_purchase( $post->ID ) ) {
					echo '<div class="envato-verif envato-verif-yes">&#10003; '.__('Verified purchase', 'wpas').'</div>';
				} else {
					echo '<div class="envato-verif envato-verif-no">&#10007; '.__('Purchase not verified', 'wpas').'</div>';
				}

			}

			$main_query_args = array(
				'posts_per_page'	=>	-1,
				'orderby'			=>	'post_date',
				'order'				=>	wpas_get_option( 'replies_order', 'ASC' ),
				'post_type'			=>	array( 'ticket_history', 'ticket_reply', 'ticket_status', 'ticket_note' ),
				'post_parent'		=>	$post->ID,
				'post_status'		=>	array( 'inherit', 'private', 'trash' )
			);

			$history = new WP_Query( $main_query_args );


			if( !empty( $history->posts ) ) {

				foreach( $history->posts as $row ) {

					/**
					 * Reply posted by registered member
					 */
					if( $row->post_author != 0 ) {

						$user_data 		= get_userdata( $row->post_author );
						$user_id 		= $user_data->data->ID;
						$user_name 		= $user_data->data->display_name;

					}

					/**
					 * Reply posted anonymously
					 */
					else {

						$user_name 		= __('Anonymous', 'wpas');
						$user_id 		= 0;

					}


					if( $row->post_type == 'ticket_reply' && 'inherit' == $row->post_status ) {
						$reply = true;
					} else {
						$reply = false;
					}

					$reply ? $user_avatar = get_avatar( $user_id, '64', 'mm' ) : $user_avatar = get_avatar( $user_id, '32', 'mm' );
					$date 			= human_time_diff( get_the_time( 'U', $row->ID ), current_time( 'timestamp' ) );
					$post_type 		= $row->post_type;

					/**
					 * Layout for replies
					 */
					if( ( 'ticket_reply' == $row->post_type || 'ticket_note' == $row->post_type ) && 'trash' != $row->post_status ):

						if( 'ticket_note' == $row->post_type ): ?>
							<tr class="wpas-note-notice">
								<td colspan="3">
									<div class="dashicons dashicons-lock"></div> <?php _e( 'This is a private note.', 'wpas' ); ?>
								</td>
							</tr>
						<?php endif; ?>

						<tr valign="top" class="<?php echo $post_type; ?><?php if( $user_id == 0 ) echo ' anonymous'; ?> wpas-origin-<?php echo $row->ID; ?> wpas-<?php echo $row->post_status; ?>" id="wpas-post-<?php echo $row->ID; ?>">
							<td class="col1">

								<?php
								/* Display avatar only for replies */
								if( 'ticket_reply' == $row->post_type ) {
									echo $user_avatar;
									echo '<br>';
								}
								?>

								<strong><?php echo $user_name; ?></strong><br>
								<?php
								if( $user_id != 0 )
									echo ucwords( $user_data->roles[0] );

								if( isset( $_GET['post'] ) && is_numeric( $_GET['post'] ) && get_current_user_id() == $row->post_author ) {

									$delete = wp_nonce_url( add_query_arg( array( 'post' => $_GET['post'], 'rid' => $row->ID, 'action' => 'delete_reply' ), admin_url( 'post.php' ) ), 'delete_reply_' . $row->ID );
									$edit = wp_nonce_url( add_query_arg( array( 'post' => $_GET['post'], 'rid' => $row->ID, 'action' => 'edit_reply' ), admin_url( 'post.php' ) ), 'delete_reply_' . $row->ID );

									echo '<br><a href="' . $delete . '" class="wpas-icon wpas-delete" title="' . __( 'Delete', 'wpas' ) . '">' . __( 'Delete', 'wpas' ) . '</a>';
									echo '<a href="#" class="wpas-icon wpas-edit" data-origin="wpas-origin-' . $row->ID . '" data-replyid="' . $row->ID . '" data-reply="wpas-editwrap-' . $row->ID . '" data-wysiwygid="wpas-editreply-' . $row->ID . '" title="' . __( 'Edit', 'wpas' ) . '">' . __( 'Edit', 'wpas' ) . '</a>';

								}
								?>
								
							</td>
							<td class="col2">
								<?php
								/* Safe HTML tags to display as reply content */
								$tags = array(
									'a' => array(
										'href' => array (),
										'title' => array ()),
									'abbr' => array(
										'title' => array ()),
									'acronym' => array(
										'title' => array ()),
									'b' => array(),
									'blockquote' => array(
										'cite' => array ()),
									'cite' => array (),
									'code' => array(),
									'pre' => array(),
									'del' => array(
										'datetime' => array ()),
									'em' => array (), 'i' => array (),
									'q' => array(
										'cite' => array ()),
									'strike' => array(),
									'strong' => array(),
									'h1' => array(),
									'h2' => array(),
									'h3' => array(),
									'h4' => array(),
									'h5' => array(),
									'h6' => array(),
									'p' => array(),
								);

								$content = ( 'ticket_note' == $row->post_type ) ? wpautop( htmlentities( $row->post_content, ENT_COMPAT, 'UTF-8' ) ) : wpautop( wp_kses_post( $row->post_content, $tags ) );

								/* The content displayed to agents */
								echo '<div id="wpas-origin-' . $row->ID . '">' . $content . '</div>';

								if( ( $attachments = get_post_meta( $row->ID, WPAS_PREFIX.'attachments', true ) ) != '' && is_array($attachments) ) {

									echo '<div class="wpas_attachements"><span>'.__('Attached files', 'wpas').':</span><ul>';

									wpas_get_uploaded_files( $row->ID );

									echo '</ul></div>';
								}
								?>
							</td>
							<td class="col3">
								<?php printf(__('%s ago', 'wpas'), $date); ?>
							</td>
						</tr>
						<tr class="wpas-editmeta wpas-editwrap-<?php echo $row->ID; ?>" style="display:none;">
							<td colspan="3">
								<?php printf( __( 'You\'re currently editing the reply posted by %s <time>%s ago</time>.', 'wpas' ), "<strong>$user_name</strong>", $date ); ?> 
							</td>
						</tr>
						<tr class="wpas-editor wpas-editwrap-<?php echo $row->ID; ?>" style="display:none;">
							<td colspan="3">

							<div class="wpas-editwrap" id="wpas-editwrap-<?php echo $row->ID; ?>">

								<?php
								/* The edition textarea */
								wp_editor( '', 'wpas-editreply-' . $row->ID, array(
									'media_buttons' => false,
									'teeny' 		=> true,
									'quicktags' 	=> false,
									'editor_class' 	=> 'wpas-edittextarea',
									'textarea_name' => 'wpas_edit_reply[' . $row->ID . ']',
									'textarea_rows' => 20
									)
								);
								?>

								<br>
								<input id="wpas-edited-reply-<?php echo $row->ID; ?>" type="hidden" name="edited_replies[]">
								<input type="submit" class="button-primary" value="<?php _e( 'Save changes', 'wpas' ); ?>"> 
								<input type="button" class="wpas-editcancel button-secondary" data-origin="wpas-origin-<?php echo $row->ID; ?>" data-replyid="<?php echo $row->ID; ?>" data-reply="wpas-editwrap-<?php echo $row->ID; ?>" data-wysiwygid="wpas-editreply-<?php echo $row->ID; ?>" value="<?php _e( 'Cancel', 'wpas' ); ?>">
							</div>

							</td>
						</tr>

					<?php
					/**
					 * Layout for history and statuses
					 */
					else: ?>

						<tr scope="row" class="<?php echo $post_type; ?> wpas-<?php echo $row->post_status; ?>" id="wpas-post-<?php echo $row->ID; ?>">
							<td colspan="3">

								<?php
								/* Status change */
								if( $row->post_type == 'ticket_status' ) {

									$content = explode( '-', $row->post_content );

									$label = ucwords( $content[0] );

									$lib = explode('-', $row->post_content);

									$status_color = wpas_get_option( "status_$content[0]_color" );

									echo '<span class="label" style="background-color:'.$status_color.';">' . $label . '</span> ';
									echo $user_avatar;

									if( isset( $content[1] ) && 'auto' == $content[1] )
										printf( __( ' Ticket automatically closed <em>%s ago.</em>', 'wpas' ), $date );

									elseif( 'close' == $content[0] )
										printf( __(' <strong>%s</strong> closed the ticket <em>%s ago.</em>', 'wpas'), $user_name, $date );

									elseif( 'open' == $content[0] )
										printf( __(' <strong>%s</strong> opened the ticket <em>%s ago.</em>', 'wpas'), $user_name, $date );

								}

								/* Action history */
								elseif( $row->post_type == 'ticket_history' ) {

									echo $user_avatar;
									echo wp_kses_post( $row->post_content );
									printf( __( ' <em>%s ago</em>', 'wpas' ), $date );

								}

								/* Deleted reply */
								elseif( ( 'ticket_reply' || 'ticket_note' == $row->post_type ) && 'trash' == $row->post_status ) {

									$status_color = wpas_get_option( 'status_' . $row->post_content . '_color' );
									echo $user_avatar;
									printf( __(' This reply has been deleted <em>%s ago.</em>', 'wpas'), $date );

								} else {

									echo $user_avatar;
									printf(__('%s <em>%s ago</em>', 'wpas'), $lib[1], $date);

								}
								?>
							</td>
						</tr>
					<?php endif; ?>
				<?php }
			}
			endif; ?>
		</tbody>
	</table>
	<?php
	wp_nonce_field( 'update_ticket', 'ticket_details', false, true );
	if( $status == 'wpas-open' ):
		if( current_user_can('reply_ticket') ): ?>
			<h2><?php printf(__('Write a reply to &laquo;%s&raquo;', 'wpas'), get_the_title( $post->ID )); ?></h2>
			<div>
				<?php
				/**
				 * Load the WordPress WYSIWYG with minimal options
				 */
				/* The edition textarea */
				wp_editor( '', 'ticket_reply', array(
					'media_buttons' => false,
					'teeny' 		=> true,
					'quicktags' 	=> true,
					)
				);
				?>
			</div>
			<?php
			/**
			 * Add a hook after the WYSIWYG editor
			 * for tickets reply.
			 *
			 * @WPAS_Quick_Replies::echoMarkup()
			 */
			do_action( 'wpas_admin_after_wysiwyg' );
			?>
			<?php if( wpas_can_attach_files() ): ?>

				<div class="wpas-attachments-admin">
					<h2><?php _e( 'Upload a File', 'wpas'); ?></h2>
					<?php wpas_file_uploader(); ?>
				</div>

			<?php endif; ?>
			<div>
				<button type="submit" name="do" class="button-primary" value="reply"><?php _e('Reply', 'wpas'); ?></button>
				<?php if( current_user_can('close_ticket') ): ?><button type="submit" name="do" class="button-secondary" value="reply_close"><?php _e('Reply & Close', 'wpas'); ?></button><?php endif; ?>
			</div>
		<?php else: ?>
			<p><?php _e('Sorry, you don\'t have sufficient permissions to reply to tickets.', 'wpas'); ?></p>
		<?php endif; ?>
	<?php elseif( $status == 'wpas-close' ): ?>
		<div class="updated below-h2" style="margin-top: 2em;">
			<h2 style="margin: 0.5em 0; padding: 0; line-height: 100%;"><?php _e('Ticket is closed', 'wpas'); ?></h2>
			<p><?php _e('This ticket has been closed. If you want to write a new reply to this ticket, you need to re-open it first.', 'wpas'); ?></p>
		</div>
	<?php endif; ?>
<?php }