<?php
/**
 * Server environment collector.
 *
 * @package MonitorCat\Modules\Diagnostics\Collector
 */

declare(strict_types=1);

namespace MonitorCat\Modules\Diagnostics\Collector;

defined( 'ABSPATH' ) || exit;

/**
 * Collects server environment information including web server, OS, and disk usage.
 */
final class ServerCollector {

	/**
	 * Collect server environment data.
	 *
	 * @return array{label: string, icon: string, items: array<int, array{label: string, value: string, status?: string}>}
	 */
	public function collect(): array {
		return array(
			'label' => __( 'Server', 'monitor-cat' ),
			'icon'  => 'fa-server',
			'items' => array(
				array(
					'label' => __( 'Web Server', 'monitor-cat' ),
					'value' => isset( $_SERVER['SERVER_SOFTWARE'] )
						? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) )
						: __( 'Unknown', 'monitor-cat' ),
				),
				array(
					'label' => __( 'Architecture', 'monitor-cat' ),
					'value' => php_uname( 'm' ),
				),
				array(
					'label' => __( 'Operating System', 'monitor-cat' ),
					'value' => php_uname( 's' ) . ' ' . php_uname( 'r' ),
				),
				array(
					'label' => __( 'Hostname', 'monitor-cat' ),
					'value' => gethostname() ? gethostname() : php_uname( 'n' ),
				),
				array(
					'label' => __( 'Document Root', 'monitor-cat' ),
					'value' => isset( $_SERVER['DOCUMENT_ROOT'] )
						? sanitize_text_field( wp_unslash( $_SERVER['DOCUMENT_ROOT'] ) )
						: __( 'Unknown', 'monitor-cat' ),
				),
				array(
					'label' => __( 'Available Disk Space', 'monitor-cat' ),
					'value' => $this->get_disk_free_space(),
				),
				array(
					'label' => __( 'Total Disk Space', 'monitor-cat' ),
					'value' => $this->get_disk_total_space(),
				),
				array(
					'label' => __( 'Server Protocol', 'monitor-cat' ),
					'value' => isset( $_SERVER['SERVER_PROTOCOL'] )
						? sanitize_text_field( wp_unslash( $_SERVER['SERVER_PROTOCOL'] ) )
						: __( 'Unknown', 'monitor-cat' ),
				),
				array(
					'label'  => __( 'TLS/SSL', 'monitor-cat' ),
					'value'  => is_ssl()
						? __( 'Yes', 'monitor-cat' )
						: __( 'No', 'monitor-cat' ),
					'status' => is_ssl() ? 'good' : 'warning',
				),
			),
		);
	}

	/**
	 * Get the available disk space formatted as a human-readable string.
	 *
	 * @return string
	 */
	private function get_disk_free_space(): string {
		$free_space = disk_free_space( ABSPATH );

		if ( false === $free_space ) {
			return __( 'Unable to determine', 'monitor-cat' );
		}

		return size_format( (int) $free_space );
	}

	/**
	 * Get the total disk space formatted as a human-readable string.
	 *
	 * @return string
	 */
	private function get_disk_total_space(): string {
		$total_space = disk_total_space( ABSPATH );

		if ( false === $total_space ) {
			return __( 'Unable to determine', 'monitor-cat' );
		}

		return size_format( (int) $total_space );
	}
}
