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

/**
 * File System Information Collector
 *
 * Collects file system and directory information
 */
class FileSystemCollector extends AbstractCollector
{
	/**
	 * Collect file system information
	 *
	 * @return array
	 */
	public function collect(): array
	{
		return [
			$this->item(__('WordPress Directory', 'ultimate-security'), ABSPATH),
			$this->item(__('WordPress Writable', 'ultimate-security'), is_writable(ABSPATH)),
			$this->item(__('Content Directory', 'ultimate-security'), WP_CONTENT_DIR),
			$this->item(__('Content Directory Writable', 'ultimate-security'), is_writable(WP_CONTENT_DIR)),
			$this->item(__('Plugins Directory', 'ultimate-security'), WP_PLUGIN_DIR),
			$this->item(__('Plugins Directory Writable', 'ultimate-security'), is_writable(WP_PLUGIN_DIR)),
			$this->item(__('Themes Directory', 'ultimate-security'), get_theme_root()),
			$this->item(__('Themes Directory Writable', 'ultimate-security'), is_writable(get_theme_root())),
			$this->item(__('wp-config.php Location', 'ultimate-security'), $this->getWpConfigLocation()),
			$this->item(__('wp-config.php Writable', 'ultimate-security'), $this->isWpConfigWritable()),
		];
	}

	/**
	 * Get wp-config.php location
	 *
	 * @return string
	 */
	private function getWpConfigLocation(): string
	{
		if (file_exists(ABSPATH . 'wp-config.php')) {
			return ABSPATH . 'wp-config.php';
		} elseif (file_exists(dirname(ABSPATH) . '/wp-config.php')) {
			return dirname(ABSPATH) . '/wp-config.php';
		}
		return __('Not found', 'ultimate-security');
	}

	/**
	 * Check if wp-config.php is writable
	 *
	 * @return bool
	 */
	private function isWpConfigWritable(): bool
	{
		$config_file = $this->getWpConfigLocation();
		if ($config_file !== __('Not found', 'ultimate-security')) {
			return is_writable($config_file);
		}
		return false;
	}

	/**
	 * Get file permissions
	 *
	 * @param string $path File path
	 * @return string
	 */
	public function getPermissions(string $path): string
	{
		if (!file_exists($path)) {
			return __('Not found', 'ultimate-security');
		}

		$perms = fileperms($path);
		return substr(sprintf('%o', $perms), -4);
	}

	/**
	 * Get directory size
	 *
	 * @param string $path Directory path
	 * @return string
	 */
	public function getDirectorySize(string $path): string
	{
		if (!is_dir($path)) {
			return __('Not found', 'ultimate-security');
		}

		$size = 0;
		$files = new \RecursiveIteratorIterator(
			new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS)
		);

		foreach ($files as $file) {
			$size += $file->getSize();
		}

		return size_format($size);
	}

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

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