<?php

class HappyForms_Form_Admin_Upgrade {

	private static $instance;

	public static function instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		self::$instance->hook();

		return self::$instance;
	}

	public function hook() {
		$post_type = happyforms_get_form_controller()->post_type;

		add_filter( "views_edit-{$post_type}", array( $this, 'order_views' ) );
		add_filter( 'happyforms_manage_form_column_headers', array( $this, 'column_headers' ) );
		add_action( "manage_{$post_type}_posts_custom_column", array( $this, 'column_content' ), 10, 2 );
		add_filter( "bulk_actions-edit-{$post_type}", array( $this, 'bulk_actions' ) );
		add_filter( "handle_bulk_actions-edit-{$post_type}", array( $this, 'handle_bulk_actions' ), 10, 3 );
		add_filter( 'post_row_actions', array( $this, 'row_actions' ), 10, 2 );
		add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ) );
		add_action( 'admin_notices', array( $this, 'print_notices' ) );
	}

	public function column_headers( $headers ) {
		$messages_header = '<span class="dashicons dashicons-admin-comments"></span>';
		$messages_header .= '<span class="happyforms-responses-column-label">';
		$messages_header .= __( 'Activity', 'happyforms' );
		$messages_header .= '</span>';
		$messages_header = array( 'messages' => $messages_header );

		$before = array_slice( $headers, 0, -1, true );
		$after = array_slice( $headers, -1, 1, true );
		$headers = $before + $messages_header + $after;

		return $headers;
	}

	public function column_content( $column, $id ) {
		switch ( $column ) {
			case 'messages':
				$messages_url = admin_url( "/edit.php?post_type=happyforms-message&form_id={$id}" );
				$message_counter = happyforms_get_message_controller()->get_counters( $id );
				$message_html = '—';

				if ( 0 < $message_counter['total'] ) {
					$message_html = '<div class="happyforms-responses-count-wrapper">';
					$bubble_html = sprintf(
						'<span class="responses-count-read">%d</span>
						<span class="screen-reader-text">%d %s</span>',
						$message_counter['total'],
						$message_counter['total'],
						__( 'read responses', 'happyforms' )
					);
					$bubble = sprintf(
						'<span class="happyforms-responses-count happyforms-responses-count-read">%s</span>',
						$bubble_html
					);

					if ( current_user_can( 'happyforms_manage_activity' ) ) {
						$bubble = sprintf(
							'<a href="%s" class="happyforms-responses-count happyforms-responses-count-read">%s</a>',
							$messages_url, $bubble_html
						);
					}

					$message_html .= $bubble;
					
					if ( 0 < $message_counter['unread'] ) {
						$messages_url_unread = add_query_arg( 'read', 'unread', $messages_url );
						$bubble_html = sprintf(
							'<span class="responses-count-unread">%d</span>
							<span class="screen-reader-text">%d %s</span>',
							$message_counter['unread'],
							$message_counter['unread'],
							__( 'unread responses', 'happyforms' )
						);
						$bubble = sprintf(
							'<span class="happyforms-responses-count happyforms-responses-count-unread">%s</span>',
							$bubble_html
						);

						if ( current_user_can( 'happyforms_manage_activity' ) ) {
							$bubble = sprintf(
								'<a href="%s" class="happyforms-responses-count happyforms-responses-count-unread">%s</a>',
								$messages_url_unread, $bubble_html
							);
						}

						$message_html .= $bubble;
					}

					$message_html .= '</div>';
				}

				echo $message_html;
				break;
		}
	}

	public function row_actions( $actions, $post ) {
		$post_type = happyforms_get_form_controller()->post_type;

		if ( $post->post_type === $post_type ) {
			$link_template = '<a href="%s">%s</a>';
			$links = array();

			switch ( $post->post_status ) {
				case 'archive':
					$links['restore'] = sprintf(
						$link_template,
						add_query_arg( 'status', 'publish', happyforms_get_form_status_link( array( $post->ID ) ) ),
						__( 'Restore', 'happyforms' )
					);
					$links['delete'] = sprintf(
						$link_template,
						get_delete_post_link( $post->ID, '', true ),
						__( 'Delete Permanently', 'happyforms' )
					);

					break;
				case 'publish':
					$links['edit'] = $actions['edit'];
					$links['duplicate'] = $actions['duplicate'];
					$links['archive'] = sprintf(
						$link_template,
						add_query_arg( array(
							'status' => 'archive',
							'archived' => 1
						), happyforms_get_form_status_link( array( $post->ID ) ) ),
						__( 'Archive', 'happyforms' )
					);
					$links['trash'] = $actions['trash'];

					break;
				default:
					break;
			}

			if ( ! empty( $links ) ) {
				$actions = $links;
			}

			$activity_count = happyforms_get_message_controller()->count_by_form( $post->ID );

			if ( 0 < $activity_count ) {
				if ( isset( $actions['trash'] ) ) {
					unset( $actions['trash'] );
				}

				if ( isset( $actions['delete'] ) ) {
					unset( $actions['delete'] );
				}
			}
		}

		return $actions;
	}

	public function pre_get_posts( $query ) {
		if ( ! is_admin() ) {
			return;
		}

		$post_type = $query->get( 'post_type' );
		$controller = happyforms_get_form_controller();

		if ( $post_type !== $controller->post_type ) {
			return;
		}

		$query_vars = &$query->query_vars;

		if ( empty( $query_vars['post_status'] ) ) {
			$query_vars['post_status'] = 'publish';
		}
	}

	public function bulk_actions( $actions ) {
		$new_actions = array();

		$new_actions['archive'] = __( 'Move to Archive', 'happyforms' );
		$new_actions['trash'] = __( 'Move to Trash', 'happyforms' );

		if ( isset( $_GET['post_status'] ) && 'all' !== $_GET['post_status'] ) {
			$new_actions = array();

			if ( 'archive' === $_GET['post_status'] ) {
				unset( $actions['trash'] );
				unset( $actions['archive'] );

				$actions['restore_archive'] = __( 'Restore', 'happyforms' );
				$actions['delete'] = __( 'Delete Permanently', 'happyforms' );
			}

			if ( 'trash' === $_GET['post_status'] ) {
				unset( $actions['archive'] );
				unset( $actions['restore_archive'] );
			}
		}

		if ( ! empty( $new_actions ) ) {
			$actions = $new_actions;
		}

		return $actions;
	}

	public function handle_bulk_actions( $redirect_to, $action, $ids ) {
		$form_controller = happyforms_get_form_controller();

		switch ( $action ) {
			case 'archive':
				foreach ( $ids as $id ) {
					$form = $form_controller->get( $id );

					if ( ! $form ) {
						continue;
					}

					wp_update_post( array(
						'ID' => $id,
						'post_status' => 'archive'
					) );
				}

				$redirect_to = remove_query_arg( 'restored', $redirect_to );
				$redirect_to = add_query_arg( array(
					'archived' => count( $ids ),
					'form_ids' => join( ',', $ids )
				), $redirect_to );

				break;
			case 'restore_archive':
				foreach ( $ids as $id ) {
					$form = $form_controller->get( $id );

					if ( ! $form ) {
						continue;
					}

					wp_update_post( array(
						'ID' => $id,
						'post_status' => 'publish'
					) );
				}

				$redirect_to = remove_query_arg( 'archived', $redirect_to );
				$redirect_to = add_query_arg( array(
					'restored' => count( $ids ),
					'form_ids' => join( ',', $ids ),
				), $redirect_to );

				break;
		}

		return $redirect_to;
	}

	public function print_notices() {
		$messages = array();

		if ( isset( $_GET['archived'] ) && ! empty( $_GET['archived'] ) ) {
			$count = intval( $_GET['archived'] );
			$text = _n( 'form moved to the Archive.', 'forms moved to the Archive.', $count, 'happyforms' );

			if ( isset( $_GET['form_ids'] ) ) {
				$ids = explode( ',', $_GET['form_ids'] );

				$restore_link = add_query_arg( array(
					'status' => 'publish',
					'undo' => 1,
					'restored' => 1
				), happyforms_get_form_status_link( $ids ) );

				$text = $text . sprintf(
					" <a href=\"%s\">%s</a>",
					$restore_link,
					__( 'Undo', 'happyforms' )
				);
			}

			$message = "{$count} {$text}";
			$messages[] = $message;
		}

		if ( isset( $_GET['restored'] ) && ! empty( $_GET['restored'] ) ) {
			$count = intval( $_GET['restored'] );
			$message = _n( 'form restored from the Archive.', 'forms restored from the Archive.', $count, 'happyforms' );

			$message = "{$count} {$message}";
			$messages[] = $message;
		}

		if ( ! empty( $messages ) ) {
		?>
			<div id="message" class="updated notice is-dismissible"><p><?php echo join( ' ', $messages ); ?></p></div>
		<?php
		}
	}

	public function order_views( $views ) {
		/**
		 * Push Trash view always to the end.
		 */
		if ( ! isset( $views['trash'] ) ) {
			return $views;
		}

		$trash_view = $views['trash'];
		unset( $views['trash'] );

		$views['trash'] = $trash_view;

		return $views;
	}
}

HappyForms_Form_Admin_Upgrade::instance();
