<?php
namespace WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors;

/**
 * Media Library Information Collector
 *
 * Collects media library statistics
 */
class MediaCollector extends AbstractCollector
{
	/**
	 * Collect media information
	 *
	 * @return array
	 */
	public function collect(): array
	{
		$upload_dir = wp_upload_dir();
		$counts = wp_count_posts('attachment');

		return [
			$this->item(__('Total Attachments', 'ultimate-security'), $this->getTotalAttachments()),
			$this->item(__('Images', 'ultimate-security'), $this->getImageCount()),
			$this->item(__('Videos', 'ultimate-security'), $this->getVideoCount()),
			$this->item(__('Audio', 'ultimate-security'), $this->getAudioCount()),
			$this->item(__('Documents', 'ultimate-security'), $this->getDocumentCount()),
			$this->item(__('Upload Directory', 'ultimate-security'), $upload_dir['basedir']),
			$this->item(__('Upload URL', 'ultimate-security'), $upload_dir['baseurl']),
			$this->item(__('Upload Path Writable', 'ultimate-security'), is_writable($upload_dir['basedir'])),
			$this->item(__('Max Upload Size', 'ultimate-security'), size_format(wp_max_upload_size())),
		];
	}

	/**
	 * Get total attachments
	 *
	 * @return int
	 */
	private function getTotalAttachments(): int
	{
		$counts = wp_count_posts('attachment');
		return isset($counts->inherit) ? (int) $counts->inherit : 0;
	}

	/**
	 * Get image count
	 *
	 * @return int
	 */
	private function getImageCount(): int
	{
		global $wpdb;
		return (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->posts}
			WHERE post_type = 'attachment'
			AND post_mime_type LIKE 'image/%'"
		);
	}

	/**
	 * Get video count
	 *
	 * @return int
	 */
	private function getVideoCount(): int
	{
		global $wpdb;
		return (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->posts}
			WHERE post_type = 'attachment'
			AND post_mime_type LIKE 'video/%'"
		);
	}

	/**
	 * Get audio count
	 *
	 * @return int
	 */
	private function getAudioCount(): int
	{
		global $wpdb;
		return (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->posts}
			WHERE post_type = 'attachment'
			AND post_mime_type LIKE 'audio/%'"
		);
	}

	/**
	 * Get document count
	 *
	 * @return int
	 */
	private function getDocumentCount(): int
	{
		global $wpdb;
		return (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->posts}
			WHERE post_type = 'attachment'
			AND post_mime_type IN ('application/pdf', 'application/msword', 'application/vnd.ms-excel')"
		);
	}

	/**
	 * Get collector name
	 *
	 * @return string
	 */
	public function getName(): string
	{
		return 'media';
	}

	/**
	 * Get collector label
	 *
	 * @return string
	 */
	public function getLabel(): string
	{
		return __('Media', 'ultimate-security');
	}
}
