<?php
/**
 * Content Report Widget Module
 *
 * @package ContentReportWidget
 * @since 1.0.0
 */

namespace ContentReportWidget;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'content-report-widget';
	private const MODULE_VERSION = '1.2.0';
	private const CACHE_KEY = 'wpps_content_report_stats';
	private const CACHE_EXPIRY = 300; // 5 minutes

	private ?array $settings_cache = null;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Content Report Widget', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Dashboard widget with content and user counts, including drafts, published items, and custom types.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return 'admin';
	}

	public function getDependencies(): array {
		return [];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		if ( is_admin() ) {
			add_action( 'wp_dashboard_setup', [ $this, 'addDashboardWidget' ] );
			add_action( 'admin_enqueue_scripts', [ $this, 'enqueueAssets' ] );
			add_action( 'wp_powersuite_module_settings_saved', [ $this, 'onSettingsSaved' ], 10, 2 );
		}

		add_action( 'save_post', [ __CLASS__, 'clearCache' ] );
		add_action( 'delete_post', [ __CLASS__, 'clearCache' ] );
		add_action( 'wp_trash_post', [ __CLASS__, 'clearCache' ] );
		add_action( 'untrash_post', [ __CLASS__, 'clearCache' ] );
		add_action( 'deleted_comment', [ __CLASS__, 'clearCache' ] );
		add_action( 'comment_post', [ __CLASS__, 'clearCache' ] );
		add_action( 'wp_set_comment_status', [ __CLASS__, 'clearCache' ] );
		add_action( 'edit_comment', [ __CLASS__, 'clearCache' ] );
		add_action( 'profile_update', [ __CLASS__, 'clearCache' ] );
		add_action( 'user_register', [ __CLASS__, 'clearCache' ] );
		add_action( 'deleted_user', [ __CLASS__, 'clearCache' ] );
		add_action( 'add_attachment', [ __CLASS__, 'clearCache' ] );
		add_action( 'delete_attachment', [ __CLASS__, 'clearCache' ] );
		add_action( 'created_term', [ __CLASS__, 'clearCache' ] );
		add_action( 'edited_term', [ __CLASS__, 'clearCache' ] );
		add_action( 'delete_term', [ __CLASS__, 'clearCache' ] );
	}

	public function addDashboardWidget(): void {
		if ( ! $this->canViewWidget() ) {
			return;
		}

		wp_add_dashboard_widget(
			'wpps_content_report',
			__( 'Content Report', 'wp-powersuite' ),
			[ $this, 'renderDashboardWidget' ]
		);
	}

	public function enqueueAssets( string $hook ): void {
		if ( $hook !== 'index.php' || ! $this->canViewWidget() ) {
			return;
		}

		$base = defined( 'WP_POWERSUITE_PLUGIN_URL' ) ? WP_POWERSUITE_PLUGIN_URL : '';
		$url  = $base . 'modules/' . self::MODULE_ID . '/assets/content-report-widget.css';

		wp_enqueue_style( 'wpps-content-report-widget', $url, [], self::MODULE_VERSION );
	}

	public function renderDashboardWidget(): void {
		if ( ! $this->canViewWidget() ) {
			return;
		}

		$data = $this->getCachedStats();
		$stats = $data['main'];
		$post_statuses = $data['post_statuses'];
		$custom_post_types = $data['custom_post_types'];
		$comment_statuses = $data['comment_statuses'];

		$post_status_labels = [
			'published' => __( 'Published', 'wp-powersuite' ),
			'draft'     => __( 'Draft', 'wp-powersuite' ),
			'scheduled' => __( 'Scheduled', 'wp-powersuite' ),
			'pending'   => __( 'Pending Review', 'wp-powersuite' ),
		];

		$comment_status_labels = [
			'approved' => __( 'Approved', 'wp-powersuite' ),
			'pending'  => __( 'Pending', 'wp-powersuite' ),
			'spam'     => __( 'Spam', 'wp-powersuite' ),
		];

		$links = [
			'posts'      => current_user_can( 'edit_posts' ) ? admin_url( 'edit.php' ) : '',
			'pages'      => current_user_can( 'edit_pages' ) ? admin_url( 'edit.php?post_type=page' ) : '',
			'media'      => current_user_can( 'upload_files' ) ? admin_url( 'upload.php' ) : '',
			'comments'   => current_user_can( 'moderate_comments' ) ? admin_url( 'edit-comments.php' ) : '',
			'users'      => current_user_can( 'list_users' ) ? admin_url( 'users.php' ) : '',
			'categories' => current_user_can( 'manage_categories' ) ? admin_url( 'edit-tags.php?taxonomy=category' ) : '',
			'tags'       => current_user_can( 'manage_categories' ) ? admin_url( 'edit-tags.php?taxonomy=post_tag' ) : '',
		];

		?>
		<div class="wpps-content-report">
			<div class="wpps-content-report-grid">
				<?php $this->renderStatCard( 'posts', $stats['posts'], __( 'Posts', 'wp-powersuite' ), $links['posts'] ); ?>
				<?php $this->renderStatCard( 'pages', $stats['pages'], __( 'Pages', 'wp-powersuite' ), $links['pages'] ); ?>
				<?php $this->renderStatCard( 'media', $stats['media'], __( 'Media', 'wp-powersuite' ), $links['media'] ); ?>
				<?php $this->renderStatCard( 'comments', $stats['comments'], __( 'Comments', 'wp-powersuite' ), $links['comments'] ); ?>
				<?php $this->renderStatCard( 'users', $stats['users'], __( 'Users', 'wp-powersuite' ), $links['users'] ); ?>
				<?php $this->renderStatCard( 'categories', $stats['categories'], __( 'Categories', 'wp-powersuite' ), $links['categories'] ); ?>
				<?php $this->renderStatCard( 'tags', $stats['tags'], __( 'Tags', 'wp-powersuite' ), $links['tags'] ); ?>
			</div>

			<?php
			$has_post_statuses = array_sum( $post_statuses ) > 0;
			if ( $has_post_statuses ) :
				?>
				<div class="wpps-content-report-section">
					<h4 class="wpps-section-title">
						<span class="dashicons dashicons-admin-post"></span>
						<?php esc_html_e( 'Post Status Breakdown', 'wp-powersuite' ); ?>
					</h4>
					<div class="wpps-status-list">
						<?php foreach ( $post_statuses as $status => $count ) : ?>
							<?php if ( $count > 0 ) : ?>
								<div class="wpps-status-item">
									<span class="wpps-status-label"><?php echo esc_html( $post_status_labels[ $status ] ?? ucfirst( $status ) ); ?></span>
									<span class="wpps-status-count"><?php echo esc_html( number_format_i18n( $count ) ); ?></span>
								</div>
							<?php endif; ?>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( $custom_post_types ) ) : ?>
				<div class="wpps-content-report-section">
					<h4 class="wpps-section-title">
						<span class="dashicons dashicons-admin-post"></span>
						<?php esc_html_e( 'Custom Post Types', 'wp-powersuite' ); ?>
					</h4>
					<div class="wpps-cpt-list">
						<?php foreach ( $custom_post_types as $post_type => $data ) : ?>
							<?php $cpt_url = $this->getCptEditUrl( $post_type ); ?>
							<div class="wpps-cpt-item">
								<?php if ( $cpt_url !== '' ) : ?>
									<a href="<?php echo esc_url( $cpt_url ); ?>">
										<span class="wpps-cpt-label"><?php echo esc_html( $data['label'] ); ?></span>
										<span class="wpps-cpt-count"><?php echo esc_html( number_format_i18n( $data['count'] ) ); ?></span>
									</a>
								<?php else : ?>
									<span class="wpps-cpt-label"><?php echo esc_html( $data['label'] ); ?></span>
									<span class="wpps-cpt-count"><?php echo esc_html( number_format_i18n( $data['count'] ) ); ?></span>
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>

			<?php
			$has_comment_statuses = array_sum( $comment_statuses ) > 0;
			if ( $has_comment_statuses ) :
				?>
				<div class="wpps-content-report-section">
					<h4 class="wpps-section-title">
						<span class="dashicons dashicons-admin-comments"></span>
						<?php esc_html_e( 'Comment Status', 'wp-powersuite' ); ?>
					</h4>
					<div class="wpps-status-list">
						<?php foreach ( $comment_statuses as $status => $count ) : ?>
							<?php if ( $count > 0 ) : ?>
								<div class="wpps-status-item">
									<span class="wpps-status-label"><?php echo esc_html( $comment_status_labels[ $status ] ?? ucfirst( $status ) ); ?></span>
									<span class="wpps-status-count"><?php echo esc_html( number_format_i18n( $count ) ); ?></span>
								</div>
							<?php endif; ?>
						<?php endforeach; ?>
					</div>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	private function renderStatCard( string $type, int $count, string $label, string $url ): void {
		$icons = [
			'posts'      => 'dashicons-admin-post',
			'pages'      => 'dashicons-admin-page',
			'media'      => 'dashicons-admin-media',
			'comments'   => 'dashicons-admin-comments',
			'users'      => 'dashicons-admin-users',
			'categories' => 'dashicons-category',
			'tags'       => 'dashicons-tag',
		];
		$icon = $icons[ $type ] ?? 'dashicons-admin-post';
		?>
		<div class="wpps-content-stat-card wpps-stat-<?php echo esc_attr( $type ); ?>">
			<?php if ( $url !== '' ) : ?>
				<a href="<?php echo esc_url( $url ); ?>">
			<?php endif; ?>
			<div class="wpps-stat-icon">
				<span class="dashicons <?php echo esc_attr( $icon ); ?>"></span>
			</div>
			<div class="wpps-stat-content">
				<div class="wpps-stat-number"><?php echo esc_html( number_format_i18n( $count ) ); ?></div>
				<div class="wpps-stat-label"><?php echo esc_html( $label ); ?></div>
			</div>
			<?php if ( $url !== '' ) : ?>
				</a>
			<?php endif; ?>
		</div>
		<?php
	}

	private function getCachedStats(): array {
		$settings = $this->getSettings();
		$show_empty = ! empty( $settings['show_empty_cpts'] );
		$cache_key = self::CACHE_KEY . '_' . get_current_blog_id() . '_' . ( $show_empty ? '1' : '0' );
		$cached = get_transient( $cache_key );

		if ( $cached !== false && is_array( $cached ) ) {
			return $cached;
		}

		$stats = $this->computeAllStats();
		set_transient( $cache_key, $stats, self::CACHE_EXPIRY );

		return $stats;
	}

	private function computeAllStats(): array {
		$posts_count = wp_count_posts( 'post' );
		$posts_total = (int) $posts_count->publish + (int) $posts_count->draft + (int) $posts_count->pending + (int) $posts_count->future;

		$pages_count = wp_count_posts( 'page' );
		$pages_total = (int) $pages_count->publish + (int) $pages_count->draft + (int) $pages_count->pending + (int) $pages_count->future;

		$media_count = wp_count_posts( 'attachment' );
		$media_total = (int) $media_count->inherit;

		$comments_count = wp_count_comments();
		$comments_total = (int) $comments_count->approved + (int) $comments_count->moderated + (int) $comments_count->spam;

		$users_count = count_users();
		$users_total = (int) $users_count['total_users'];

		$categories = get_terms(
			[
				'taxonomy'   => 'category',
				'hide_empty' => false,
				'fields'     => 'count',
			]
		);
		$categories_total = is_wp_error( $categories ) ? 0 : (int) $categories;

		$tags = get_terms(
			[
				'taxonomy'   => 'post_tag',
				'hide_empty' => false,
				'fields'     => 'count',
			]
		);
		$tags_total = is_wp_error( $tags ) ? 0 : (int) $tags;

		$post_statuses = [
			'published' => (int) $posts_count->publish,
			'draft'     => (int) $posts_count->draft,
			'scheduled' => (int) $posts_count->future,
			'pending'   => (int) $posts_count->pending,
		];

		$comment_statuses = [
			'approved' => (int) $comments_count->approved,
			'pending'  => (int) $comments_count->moderated,
			'spam'     => (int) $comments_count->spam,
		];

		$custom_post_types = $this->getCustomPostTypes();

		return [
			'main' => [
				'posts'      => $posts_total,
				'pages'      => $pages_total,
				'media'      => $media_total,
				'comments'   => $comments_total,
				'users'      => $users_total,
				'categories' => $categories_total,
				'tags'       => $tags_total,
			],
			'post_statuses'     => $post_statuses,
			'comment_statuses'  => $comment_statuses,
			'custom_post_types' => $custom_post_types,
		];
	}

	private function getCustomPostTypes(): array {
		$settings = $this->getSettings();
		$show_empty = ! empty( $settings['show_empty_cpts'] );

		$post_types = get_post_types(
			[
				'_builtin' => false,
			],
			'objects'
		);

		$custom_post_types = [];

		foreach ( $post_types as $post_type => $post_type_object ) {
			$count = wp_count_posts( $post_type );
			$total = (int) $count->publish + (int) $count->draft + (int) $count->pending + (int) $count->future;

			if ( $total > 0 || $show_empty ) {
				$custom_post_types[ $post_type ] = [
					'label' => $post_type_object->label,
					'count' => $total,
				];
			}
		}

		return $custom_post_types;
	}

	private function getCptEditUrl( string $post_type ): string {
		$obj = get_post_type_object( $post_type );
		if ( ! $obj || ! isset( $obj->cap->edit_posts ) || ! current_user_can( $obj->cap->edit_posts ) ) {
			return '';
		}
		return admin_url( 'edit.php?post_type=' . $post_type );
	}

	private function canViewWidget(): bool {
		return current_user_can( 'edit_posts' );
	}

	public function onSettingsSaved( string $module_id, array $settings ): void {
		if ( $module_id !== self::MODULE_ID ) {
			return;
		}

		$this->settings_cache = null;
		self::clearCache();
	}

	public static function clearCache(): void {
		$blog_id = get_current_blog_id();
		delete_transient( self::CACHE_KEY . '_' . $blog_id . '_0' );
		delete_transient( self::CACHE_KEY . '_' . $blog_id . '_1' );
	}

	public function getDefaultSettings(): array {
		return [
			'show_empty_cpts' => false,
		];
	}

	private function getSettings(): array {
		if ( $this->settings_cache !== null ) {
			return $this->settings_cache;
		}
		$saved = $this->moduleSettings()->all( [] );
		$this->settings_cache = array_merge( $this->getDefaultSettings(), is_array( $saved ) ? $saved : [] );
		return $this->settings_cache;
	}

}
