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

use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\AbstractCollector;

/**
 * Health Check Service
 *
 * Orchestrates all health check collectors
 */
class HealthCheckService
{
	/**
	 * Registered collectors
	 *
	 * @var AbstractCollector[]
	 */
	private $collectors = [];

	/**
	 * Add a collector
	 *
	 * @param AbstractCollector $collector Collector instance
	 * @return self
	 */
	public function addCollector(AbstractCollector $collector): self
	{
		$this->collectors[$collector->getName()] = $collector;
		return $this;
	}

	/**
	 * Get all collectors
	 *
	 * @return AbstractCollector[]
	 */
	public function getCollectors(): array
	{
		return $this->collectors;
	}

	/**
	 * Collect data from all collectors
	 *
	 * @return array Collected data indexed by collector name
	 */
	public function collectAll(): array
	{
		$data = [];

		foreach ($this->collectors as $name => $collector) {
			try {
				$data[$name] = $collector->collect();
			} catch (\Exception $e) {
				// Log error but continue with other collectors
				error_log(sprintf(
					'Health Check Error (%s): %s',
					$name,
					$e->getMessage()
				));
				$data[$name] = [
					[
						'label' => __('Error', 'ultimate-security'),
						'value' => __('Failed to collect data', 'ultimate-security'),
					]
				];
			}
		}

		return $data;
	}

	/**
	 * Collect data from a specific collector
	 *
	 * @param string $collector_name Collector name
	 * @return array|null Collected data or null if collector not found
	 */
	public function collect(string $collector_name): ?array
	{
		if (!isset($this->collectors[$collector_name])) {
			return null;
		}

		try {
			return $this->collectors[$collector_name]->collect();
		} catch (\Exception $e) {
			error_log(sprintf(
				'Health Check Error (%s): %s',
				$collector_name,
				$e->getMessage()
			));
			return null;
		}
	}

	/**
	 * Get collector by name
	 *
	 * @param string $name Collector name
	 * @return AbstractCollector|null
	 */
	public function getCollector(string $name): ?AbstractCollector
	{
		return $this->collectors[$name] ?? null;
	}

	/**
	 * Check if collector exists
	 *
	 * @param string $name Collector name
	 * @return bool
	 */
	public function hasCollector(string $name): bool
	{
		return isset($this->collectors[$name]);
	}

	/**
	 * Get collector count
	 *
	 * @return int
	 */
	public function count(): int
	{
		return count($this->collectors);
	}
}
