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

/**
 * Database Information Collector
 *
 * Collects database configuration and statistics
 */
class DatabaseCollector extends AbstractCollector
{
	/**
	 * Collect database information
	 *
	 * @return array
	 */
	public function collect(): array
	{
		global $wpdb;

		return [
			$this->item(__('Database Name', 'ultimate-security'), DB_NAME),
			$this->item(__('Database Host', 'ultimate-security'), DB_HOST),
			$this->item(__('Database User', 'ultimate-security'), DB_USER),
			$this->item(__('Database Charset', 'ultimate-security'), DB_CHARSET),
			$this->item(__('Database Collation', 'ultimate-security'), DB_COLLATE ?: __('Default', 'ultimate-security')),
			$this->item(__('Table Prefix', 'ultimate-security'), $wpdb->prefix),
			$this->item(__('Database Size', 'ultimate-security'), $this->getDatabaseSize()),
			$this->item(__('Total Tables', 'ultimate-security'), $this->getTableCount()),
		];
	}

	/**
	 * Get database size
	 *
	 * @return string
	 */
	private function getDatabaseSize(): string
	{
		global $wpdb;

		$size = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2)
				FROM information_schema.TABLES
				WHERE table_schema = %s",
				DB_NAME
			)
		);

		return $size ? $size . ' MB' : __('Unknown', 'ultimate-security');
	}

	/**
	 * Get table count
	 *
	 * @return int
	 */
	private function getTableCount(): int
	{
		global $wpdb;

		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*)
				FROM information_schema.TABLES
				WHERE table_schema = %s",
				DB_NAME
			)
		);
	}

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

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