<?php
namespace Fabrica\Dashboard;

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

require_once('base.php');

class EditorialOverview {
	public static function init() {
		add_action('wp_dashboard_setup', array(__CLASS__, 'register'));
	}

	// Register
	public static function register() {

		// Only proceed if user has relevant privileges
		if (!Base::$isEditor) {
			return;
		}
		add_meta_box('fd_editorial_overview', 'Editorial Overview', array(__CLASS__, 'display'), 'dashboard', 'normal', 'high');
	}

	// Display
	public static function display() {

		global $wpdb;
		$counts = array();
		$postTypesString = '\'' . join('\', \'', array_keys(Base::$postTypes)) . '\'';

		$selectClause = 'SELECT COUNT(*) FROM ' . Base::$dbPrefix . 'posts';
		$postTypesWhereClause = ' WHERE post_type in (' . $postTypesString . ')';

		// Total published posts
		$postsCount = 0;
		$query = $selectClause . $postTypesWhereClause . ' AND post_status = \'publish\'';
		$results = $wpdb->get_results($query, OBJECT_K);
		if ($results && key($results)) {
			$postsCount = key($results);
		}

		// All users who publish
		$writersCount = 0;
		$query = $selectClause . $postTypesWhereClause .' AND post_status = \'publish\' AND post_author != 0 GROUP BY post_author';
		$results = $wpdb->get_results($query, ARRAY_N);
		if ($results) {
			$writersCount = count($results);
		}

		// If timestamps saved, show recent activity by other users between user's last and current logins
		if (Base::$lastLogin && Base::$currentLogin) {

			$editedByJoinClause = ' LEFT JOIN ' . Base::$dbPrefix . 'postmeta AS editedby ON (' . Base::$dbPrefix . 'posts.ID = editedby.post_id AND editedby.meta_key = \'_edit_last\')';
			$editedByWhereClause = ' AND editedby.meta_value != ' . Base::$currentUser->ID;

			// Newly published
			$query = $wpdb->prepare($selectClause . $editedByJoinClause . $postTypesWhereClause . $editedByWhereClause . ' AND post_status = \'publish\' AND post_date_gmt > %s AND post_date_gmt < %s', date('Y-m-d H:i:s', Base::$lastLogin), date('Y-m-d H:i:s', Base::$currentLogin));
			$results = $wpdb->get_results($query, OBJECT_K);
			if ($results && key($results)) {
				$counts[] = array(
					'label' => __("New published items", Base::$textDomain),
					'number' => key($results),
				);
			}

			// Edited
			$query = $wpdb->prepare($selectClause . $editedByJoinClause . $postTypesWhereClause . $editedByWhereClause . ' AND post_modified_gmt > %s AND post_modified_gmt < %s AND post_modified_gmt != post_date_gmt', date('Y-m-d H:i:s', Base::$lastLogin), date('Y-m-d H:i:s', Base::$currentLogin));
			$results = $wpdb->get_results($query, OBJECT_K);
			if ($results && key($results)) {
				$counts[] = array(
					'label' => __("Edited items", Base::$textDomain),
					'number' => key($results),
				);
			}

			// Drafts
			$query = $wpdb->prepare($selectClause . $editedByJoinClause . $postTypesWhereClause . $editedByWhereClause . ' AND post_status = \'draft\' AND post_modified_gmt > %s AND post_modified_gmt < %s AND post_date_gmt =\'0000-00-00 00:00:00\'', date('Y-m-d H:i:s', Base::$lastLogin), date('Y-m-d H:i:s', Base::$currentLogin));
			$results = $wpdb->get_results($query, OBJECT_K);
			if ($results && key($results)) {
				$counts[] = array(
					'label' => __("New drafts", Base::$textDomain),
					'number' => key($results),
				);
			}

			// Scheduled
			$query = $wpdb->prepare($selectClause . $editedByJoinClause . $postTypesWhereClause . $editedByWhereClause . ' AND post_status = \'future\' AND post_modified_gmt > %s AND post_modified_gmt < %s AND post_date_gmt > NOW()', date('Y-m-d H:i:s', Base::$lastLogin), date('Y-m-d H:i:s', Base::$currentLogin));
			$results = $wpdb->get_results($query, OBJECT_K);
			if ($results && key($results)) {
				$counts[] = array(
					'label' => __("Scheduled items", Base::$textDomain),
					'number' => key($results),
				);
			}

			// Trashed
			$query = $wpdb->prepare($selectClause . $editedByJoinClause . ' LEFT JOIN ' . Base::$dbPrefix . 'postmeta AS deleted ON (' . Base::$dbPrefix . 'posts.ID = deleted.post_id AND deleted.meta_key = \'_wp_trash_meta_time\') ' . $postTypesWhereClause . $editedByWhereClause . ' AND post_status = \'trash\' AND deleted.meta_value > %d AND deleted.meta_value < %d', Base::$lastLogin, Base::$currentLogin);
			$results = $wpdb->get_results($query, OBJECT_K);
			if ($results && key($results)) {
				$counts[] = array(
					'label' => __("Trashed items", Base::$textDomain),
					'number' => key($results),
				);
			}

			// New users
			$userstable = Base::$dbBasePrefix . 'users';
			$usermetatable = Base::$dbBasePrefix . 'usermeta';
			$query = $wpdb->prepare("SELECT COUNT(*) FROM {$userstable} INNER JOIN {$usermetatable} ON ({$userstable}.ID = {$usermetatable}.user_id) WHERE {$usermetatable}.meta_key = %s AND {$userstable}.user_registered > %s AND {$userstable}.user_registered < %s", Base::$dbPrefix . 'capabilities', date('Y-m-d H:i:s', Base::$lastLogin), date('Y-m-d H:i:s', Base::$currentLogin));
			$results = $wpdb->get_results($query, OBJECT_K);
			if ($results && key($results)) {
				$counts[] = array(
					'label' => __("New users", Base::$textDomain),
					'number' => key($results),
				);
			}
		}

		// Render
		?><div class="fd-key-metrics">
			<div class="fd-key-metrics__metric">
				<div class="fd-key-metrics__head">
					<span class="fd-key-metrics__icon fd-util-grey dashicons dashicons-networking"></span>
					<span class="fd-util-large fd-util-light"><?php echo esc_html($postsCount); ?></span>
				</div>
				<span class="fd-util-medium"><?php esc_html_e("published items", Base::$textDomain); ?></span>
			</div>
			<div class="fd-key-metrics__metric">
				<div class="fd-key-metrics__head">
					<span class="fd-key-metrics__icon fd-util-grey dashicons dashicons-admin-users"></span>
					<span class="fd-util-large fd-util-light"><?php echo esc_html(Base::$totalUsers); ?></span>
				</div>
				<span class="fd-util-medium"><?php esc_html_e("registered users", Base::$textDomain); ?></span>
			</div><?php
			if (Base::$totalUsers > 1) {
				?><div class="fd-key-metrics__metric">
					<div class="fd-key-metrics__head">
						<span class="fd-key-metrics__icon fd-util-grey dashicons dashicons-id-alt"></span>
						<span class="fd-util-large fd-util-light"><?php echo esc_html($writersCount); ?></span>
					</div>
					<span class="fd-util-medium"><?php esc_html_e("users who publish", Base::$textDomain); ?></span>
				</div><?php
			}
		?></div><?php
		if ($counts) {
			?><table class="wp-list-table widefat striped fd-util-normal-table fd-util-margin-top">
				<thead>
					<th class="fd-util-center" colspan="4"><?php esc_html_e("Since your previous login", Base::$textDomain); ?></th>
				</thead>
				<tbody><?php echo esc_html(Base::renderStatsTable($counts)); ?></tbody>
			</table><?php
		}
	}
}
EditorialOverview::init();
