<?php
namespace Fabrica\Dashboard;

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

require_once('base.php');

class ContentBreakdown {
	public static function init() {
		add_action('wp_dashboard_setup', array(__CLASS__, 'register'));
		add_action('wp_ajax_fd-content-breakdown', array(__CLASS__, 'displayAjax'));
	}

	// Register
	public static function register() {
		add_meta_box('fd_content_breakdown', 'Content Breakdown', array(__CLASS__, 'displayWrapper'), 'dashboard', 'normal', 'high');
	}

	// Update parameters supplied by AJAX and return new output
	public static function displayAjax() {
		header('Content-Type: text/html');

		// Check + set user filter
		if (isset($_POST['data']['filter']) && $_POST['data']['filter'] === 'true') {
			update_user_meta(Base::$currentUser->ID, 'fd-content-breakdown-user-filter', true);
		} else {
			update_user_meta(Base::$currentUser->ID, 'fd-content-breakdown-user-filter', false);
		}

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

	// Display wrapper with filter switch
	public static function displayWrapper() {
		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 content", Base::$textDomain); ?>&nbsp;</strong>
				<input type="checkbox" class="fd-toggle fd-ajaxSwitch" data-ajax-action="fd-content-breakdown" id="fd-content-breakdown-user-filter" name="fd-content-breakdown-user-filter" value="1" <?php if (get_user_meta(Base::$currentUser->ID, 'fd-content-breakdown-user-filter', true) === '1') echo 'checked'; ?>>
				<label class="fd-toggleButton" for="fd-content-breakdown-user-filter"></label>
				<strong>&nbsp;<?php esc_html_e("just yours", Base::$textDomain); ?></strong>
			</div><?php
		}
		self::displayContents();
	}

	// Display contents (called by displayWrapper() and displayAjax())
	private static function displayContents() {
		?><table id="fd-content-breakdown" data-ajax-replace="fd-content-breakdown" class="wp-list-table widefat striped fd-util-normal-table fd-util-margin-bottom">
			<thead>
				<th>Type</th>
				<th class="fd-util-right"><span class="fd-content-breakdown-col-icon dashicons dashicons-visibility" title="<?php echo esc_html(Base::$postStatuses['publish']); ?>"></span><span class="fd-content-breakdown-col-label"><?php echo esc_html(Base::$postStatuses['publish']); ?></span></th>
				<th class="fd-util-right"><span class="fd-content-breakdown-col-icon dashicons dashicons-calendar-alt" title="<?php echo esc_html(Base::$postStatuses['future']); ?>"></span><span class="fd-content-breakdown-col-label"><?php echo esc_html(Base::$postStatuses['future']); ?></span></th>
				<th class="fd-util-right"><span class="fd-content-breakdown-col-icon dashicons dashicons-welcome-write-blog" title="<?php echo esc_html(Base::$postStatuses['draft']); ?>"></span><span class="fd-content-breakdown-col-label"><?php echo esc_html(Base::$postStatuses['draft']); ?></span></th>
				<th class="fd-util-right"><span class="fd-content-breakdown-col-icon dashicons dashicons-trash" title="<?php echo esc_html(Base::$postStatuses['trash']); ?>"></span><span class="fd-content-breakdown-col-label"><?php echo esc_html(Base::$postStatuses['trash']); ?></span></th>
				<th class="fd-util-right"><span class="fd-content-breakdown-col-icon dashicons dashicons-clock" title="<?php esc_html_e("Updated", Base::$textDomain); ?>"></span><span class="fd-content-breakdown-col-label"><?php esc_html_e("Updated", Base::$textDomain); ?></span></th>
			</thead>
			<tbody><?php

				// If below editor, only show user's posts; if editor or admin, show all unless toggled manually
				$authorID = false;
				if (!Base::$isEditor || (Base::$isEditor && get_user_meta(Base::$currentUser->ID, 'fd-content-breakdown-user-filter', true) === '1')) {
					$authorID = Base::$currentUser->ID;
				}
				global $wpdb;
				$resultCount = 0;

				foreach (Base::$postTypes as $type => $labels) {

					// Don't include Media here
					if ($type == 'attachment') {
						continue;
					}

					// Counts for each post status
					$query = $wpdb->prepare('SELECT post_status, COUNT(post_status) as count FROM ' . Base::$dbPrefix . 'posts WHERE post_type = %s AND post_status IN (\'publish\', \'future\', \'draft\', \'trash\')', $type);
					if ($authorID) {
						$query .= $wpdb->prepare(' AND post_author = %s', $authorID);
					}
					$query .= ' GROUP BY post_status';
					$counts = $wpdb->get_results($query, OBJECT_K);
					if (count($counts) == 0) {
						continue;
					}

					// Increment counter so we know at the end if we need to display a 'no results' message
					$resultCount++;

					// Most recent modification
					$mostRecent = false;
					$query = $wpdb->prepare('SELECT ID, post_modified, post_author FROM ' . Base::$dbPrefix . 'posts WHERE post_type = %s AND post_status IN (\'publish\', \'future\', \'draft\', \'trash\')', $type);
					if ($authorID) {
						$query .= $wpdb->prepare(' AND post_author = %s', $authorID);
					}
					$query .= ' ORDER BY post_modified DESC LIMIT 1';
					$mostRecents = $wpdb->get_results($query, OBJECT_K);
					if ($mostRecents) {
						$mostRecent = current($mostRecents);
					}

					// Parameters for URLs
					$authorString = '';
					if ($authorID) {
						$authorString = '&author=' . $authorID;
					}

					// Render
					?><tr>
						<td><a href="<?php echo esc_url(admin_url('edit.php?post_type=' . $type . $authorString)); ?>"><?php echo esc_html($labels['plural']); ?></a></td><?php
						foreach (['publish', 'future', 'draft', 'trash'] as $status) { ?>
							<td class="fd-util-right"><?php if (isset($counts[$status]->count)) { ?><a href="<?php echo esc_url(admin_url('edit.php?post_status=' . $status . '&post_type=' . $type . $authorString)); ?>"><?php echo esc_html($counts[$status]->count); ?></a><?php } else { echo ' &ndash; '; } ?></td><?php
						} ?>
						<td class="fd-util-right"><?php if ($mostRecent) { ?><a href="<?php echo esc_url(get_edit_post_link($mostRecent->ID)); ?>"><?php echo wp_kses_post(Base::ago(strtotime($mostRecent->post_modified))); ?></a><?php } ?></td>
					</tr><?php
				}

				if ($resultCount == 0) {
					?><tr><td colspan="6"><?php
						if ($authorID) {
							esc_html_e("You currently have no Posts, Pages or Custom Post Types.", Base::$textDomain);
						} else {
							esc_html_e("There are currently no Posts, Pages or Custom Post Types.", Base::$textDomain);
						}
					?></td></tr><?php
				}
			?></tbody>
		</table><?php
	}
}
ContentBreakdown::init();
