<?php
namespace Fabrica\Dashboard;

if (!defined('WPINC')) { die(); }

require_once('base.php');

class CommentsActivity {
	private static $comments;
	private static $filters;
	private static $columns = 5;
	private static $count = 10;

	public static function init() {
		add_action('wp_dashboard_setup', array(__CLASS__, 'register'));
		add_action('wp_ajax_fd-comments-activity-switch', array(__CLASS__, 'displayAjaxSwitch'));
		add_action('wp_ajax_fd-comments-activity-more', array(__CLASS__, 'displayAjaxMore'));
	}

	// Register
	public static function register() {

		// Only proceed if user has relevant privileges, and if there's at least one comment in the database
		if (!Base::$isModerator || !Base::$hasComments) {
			return;
		}
		add_meta_box('fd_comments_activity', __("Comments Activity", Base::$textDomain), array(__CLASS__, 'displayWrapper'), 'dashboard', 'side', 'high');
	}

	// Update table with extra results when requested via AJAX
	public static function displayAjaxSwitch() {
		header('Content-Type: text/html');

		// Check + set user filter
		$hasFilter = isset($_POST['data']['filter']) && $_POST['data']['filter'] === 'true';
		update_user_meta(Base::$currentUser->ID, 'fd-comments-activity-user-filter', $hasFilter);

		// Retrieve the data and sanitized filters
		self::cacheResults();

		// Output the requested results
		self::displayTable();
		exit;
	}

	// Update table with extra results when requested via AJAX
	public static function displayAjaxMore() {
		header('Content-Type: text/html');

		// Retrieve the data and sanitized filters
		self::cacheResults();

		// Output the requested results
		self::displayResults();
		exit;
	}

	// Perform query (on load) and cache for use by either normal display or AJAX display
	private static function cacheResults() {

		// Default filters
		$filters = array(
			'offset' => 0
		);

		// Override defaults with any chosen filters, sanitizing
		if (isset($_POST['data'])) {

			$params = $_POST['data'];

			// Query offset
			if (isset($params['fd-comments-activity-offset']) && is_numeric($params['fd-comments-activity-offset'])) {
				$filters['offset'] = $params['fd-comments-activity-offset'];
			}
		}

		// Build query
		global $wpdb;
		$query = 'SELECT ' . Base::$dbPrefix . 'comments.comment_ID, ' . Base::$dbPrefix . 'comments.comment_post_ID, ' . Base::$dbPrefix . 'comments.comment_content, ' . Base::$dbPrefix . 'comments.comment_author, ' . Base::$dbPrefix . 'comments.comment_date, ' . Base::$dbPrefix . 'comments.comment_approved, ' . Base::$dbPrefix . 'comments.user_ID';
		$query .= ' FROM ' . Base::$dbPrefix . 'comments';

		// Joins required for responses to own posts / comments
		if (get_user_meta(Base::$currentUser->ID, 'fd-comments-activity-user-filter', true) === '1') {
			$query .= ' LEFT JOIN ' . Base::$dbPrefix . 'posts ON (' . Base::$dbPrefix . 'comments.comment_post_ID = ' . Base::$dbPrefix . 'posts.ID)';
			$query .= ' LEFT JOIN ' . Base::$dbPrefix . 'comments AS comment_parents ON (' . Base::$dbPrefix . 'comments.comment_ID = comment_parents.comment_parent)';
		}

		// Exclude pingbacks / trackbacks / other special comment types
		$query .= ' WHERE ' . Base::$dbPrefix . 'comments.comment_type = \'comment\'';

		// Conditions for responses to own posts / comments
		if (get_user_meta(Base::$currentUser->ID, 'fd-comments-activity-user-filter', true) === '1') {
			$query .= $wpdb->prepare(' AND (comment_parents.user_ID = %s OR ' . Base::$dbPrefix . 'posts.post_author = %s)', Base::$currentUser->ID, Base::$currentUser->ID);
		}

		// Order
		$query .= $wpdb->prepare(' ORDER BY comment_date DESC LIMIT %d, %d', $filters['offset'], self::$count + 1);

		// Cache the filters and results for use by other functions
		self::$filters = $filters;
		self::$comments = $wpdb->get_results($query);
	}

	// Display wrapper which in turn calls displayTable() to populate the table (which can also be called to load more by AJAX)
	public static function displayWrapper() {

		// Retrieve the data and sanitized filters
		self::$count = 5; // Only show 5 on first view
		self::cacheResults();

		// Render wrapper
		if (Base::$isEditor && Base::$totalUsers > 1) {
			?><div class="fd-util-center fd-util-margin-bottom">
				<?php esc_html_e("Show", Base::$textDomain); ?>: <strong><?php esc_html_e("all comments", Base::$textDomain); ?>&nbsp;</strong>
				<input type="checkbox" class="fd-toggle fd-ajaxSwitch" data-ajax-action="fd-comments-activity-switch" id="fd-comments-activity-user-filter" name="fd-comments-activity-user-filter" value="1" <?php if (get_user_meta(Base::$currentUser->ID, 'fd-comments-activity-user-filter', true) === '1') echo 'checked'; ?>>
				<label class="fd-toggleButton" for="fd-comments-activity-user-filter"></label>
				<strong>&nbsp;<?php esc_html_e("just replies to your posts / comments", Base::$textDomain); ?></strong>
			</div><?php
		}
		self::displayTable();
	}

	// Display table frame
	public static function displayTable() {
		?><table class="wp-list-table widefat striped fd-util-normal-table fd-comments-activity-table" id="fd-comments-activity-table" data-ajax-replace="fd-comments-activity-table">
			<thead>
				<th class="fd-comments-activity-status-header"></th>
				<th class="fd-comments-activity-comment-header"><?php esc_html_e("Comment", Base::$textDomain); ?></th>
				<th class="fd-comments-activity-user-header"><?php esc_html_e("User", Base::$textDomain); ?></th>
				<th class="fd-comments-activity-when-header"><?php esc_html_e("When", Base::$textDomain); ?></th>
			</thead>
			<tbody><?php
				self::displayResults();
			?></tbody>
		</table><?php
	}

	// Display results
	private static function displayResults() {

		// Start a counter - first and last rows will have some special markup relevant to AJAX requests
		$c = 0;
		if (count(self::$comments) == 0) {
			?><tr id="fd-comments-activity">
				<td colspan="<?php echo esc_attr(self::$columns); ?>"><?php esc_html_e("There is no activity that fits the chosen criteria.", Base::$textDomain); ?></td>
			</tr><?php
		} else {
			foreach (self::$comments as $comment) {
				if ($c == self::$count) { // If there's an additional item, show 'show more' button

					// Encode the filters to be sent with the AJAX request
					$params = json_encode(array(
						'fd-comments-activity-offset' => self::$filters['offset'] + count(self::$comments) - 1
					));
					?><tr id="fd-comments-activity">
						<td colspan="<?php echo esc_attr(self::$columns); ?>" class="fd-util-center">
							<button class="button fd-ajaxButton" data-ajax-action="fd-comments-activity-more" data-ajax-params='<?php echo esc_attr($params); ?>'><?php esc_html_e("Show more", Base::$textDomain); ?></button>
						</td>
					</tr><?php
				} else {
					?><tr<?php if ($c == 0) { echo ' data-ajax-replace="fd-comments-activity"'; } ?>>
						<td><?php $colour = ''; // `` suffix tells WP the variable doesn't need to be escaped
							if ($comment->comment_approved == '1') {
								$colour = 'green';
							} else if ($comment->comment_approved == '0') {
								$colour = 'orange';
							} else if ($comment->comment_approved == 'spam') {
								$colour = 'red';
							}
							?><span class="fd-trafficlight fd-trafficlight--<?php echo esc_attr($colour); ?>"></span>
						</td>
						<td class="fd-comments-activity-comment">
							<a href="<?php echo esc_url(admin_url('comment.php?action=editcomment&c=' . $comment->comment_ID)); ?>"><?php echo esc_html(substr($comment->comment_content, 0, 200)); ?></a>
						</td>
						<td><?php echo esc_html($comment->comment_author); ?></td>
						<td class="fd-util-right"><?php echo wp_kses_post(Base::ago(strtotime($comment->comment_date))); ?></td>
					</tr><?php
				}
				$c++;
			}
		}
	}
}
CommentsActivity::init();
