<?php
/**
 * The class that handles debug functionality for the page cache.
 *
 * @since 0.1.0
 *
 * @package SolidWP\Performance
 */

declare( strict_types=1 );

namespace SolidWP\Performance\Page_Cache;

use DateTimeImmutable;
use SolidWP\Performance\Config\Config;
use SolidWP\Performance\Http\Request;
use SolidWP\Performance\Page_Cache\Compression\Contracts\Compressible;
use SolidWP\Performance\Page_Cache\Request_Context\Device\Resolver\Contracts\Device_Resolver;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles the debug functionality for the page cache.
 *
 * @since 0.1.0
 *
 * @package SolidWP\Performance
 */
class Debug {

	/**
	 * The padding to insert between definition labels and values.
	 *
	 * @since 0.1.0
	 *
	 * @var int
	 */
	private int $pad = 23;

	/**
	 * @var Config
	 */
	private Config $config;

	/**
	 * @var Device_Resolver
	 */
	private Device_Resolver $device_resolver;

	/**
	 * @param  Config          $config  The config object.
	 * @param  Device_Resolver $device_resolver The device resolver.
	 */
	public function __construct(
		Config $config,
		Device_Resolver $device_resolver
	) {
		$this->config          = $config;
		$this->device_resolver = $device_resolver;
	}

	/**
	 * Get the content for the page cache debug comment.
	 *
	 * @since 0.1.0
	 *
	 * @param Request      $request The current request to output information about.
	 * @param Compressible $compressor The compressor used to save the cache file.
	 *
	 * @return string
	 */
	public function get_debug_comment( Request $request, Compressible $compressor ): string {
		if ( $this->config->get( 'page_cache.debug' ) !== true ) {
			return '';
		}

		$is_mobile       = $this->device_resolver->is_mobile() ? 'yes' : 'no';
		$date_time       = $this->get_timestamp();
		$engine          = str_pad( 'Engine:', $this->pad ) . 'Disk';
		$creation_time   = str_pad( 'Creation Time:', $this->pad ) . $request->start . 's';
		$is_mobile_cache = str_pad( 'Is Mobile Cache:', $this->pad ) . $is_mobile;
		$host            = filter_var( $request->server['HTTP_HOST'], FILTER_SANITIZE_SPECIAL_CHARS );

		$encoding    = $compressor->encoding() ?: 'None';
		$compression = str_pad( 'Compression Algorithm:', $this->pad ) . $encoding;

		$header_content = $this->get_headers(
			$request,
			[
				'X-Powered-By'  => 'HTTP_X_POWERED_BY',
				'Expires'       => '',
				'Cache Control' => 'HTTP_CACHE_CONTROL',
				'Content-Type'  => 'HTTP_CONTENT_TYPE',
			]
		);
		return "
<!--
Solid Performance page optimization. Learn more: https://solidwp.com/performance

Page cache debug info:

$engine
$creation_time
$compression
$is_mobile_cache

Header Info:

$header_content

Served from: $host @ $date_time by Solid Performance
-->";
	}

	/**
	 * Gets a list of headers to output in a list of labels and values.
	 *
	 * @since 0.1.0
	 *
	 * @param Request              $request The request in which to get headers.
	 * @param array<string,string> $headers The labels and headers to output.
	 *
	 * @return string
	 */
	public function get_headers( Request $request, array $headers = [] ): string {

		$header_content = '';

		foreach ( $headers as $label => $header ) {
			if ( isset( $request->server[ $header ] ) ) {
				$label           = sprintf(
					'%s:',
					$label
				);
				$header_content .= str_pad( $label, $this->pad ) . $request->server[ $header ];
			}
		}

		if ( strlen( $header_content ) > 0 ) {
			return $header_content;
		}

		return '';
	}

	/**
	 * Get the generated comment, shown on cached pages when debugging is DISABLED.
	 *
	 * @return string
	 */
	public function get_generated_by_comment(): string {
		if ( $this->config->get( 'page_cache.debug' ) ) {
			return '';
		}

		return sprintf(
			'
<!-- Cached page generated by Solid Performance on %s -->',
			esc_html( $this->get_timestamp() )
		);
	}

	/**
	 * Get a timestamp using the configured timezone from the WP dashboard.
	 *
	 * @return string
	 */
	private function get_timestamp(): string {
		return ( new DateTimeImmutable( 'now', wp_timezone() ) )->format( 'Y-m-d H:i:s T' );
	}
}
