<?php
namespace ActiriseAdmin\Includes;

use Actirise\Includes\Options;
use Actirise\Includes\Helpers;
use Actirise\Includes\Logger;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

/**
 * The admin-specific functionality of the plugin.
 *
 * This class is a site health data collector for wp-admin
 *
 * @link       https://actirise.com
 * @since      2.6.8
 * @package    actirise
 * @subpackage actirise/admin/includes
 * @author     actirise <wordpress@actirise.com>
 */
final class SiteHealth {
	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    2.6.8
	 * @access   protected
	 * @var      string    $plugin_name    The string used to uniquely identify this plugin.
	 */
	protected $plugin_name;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    2.6.8
	 * @param    string $plugin_name                            The name of this plugin.
	 */
	public function __construct( $plugin_name ) {
		$this->plugin_name = $plugin_name;
	}

	/**
	 * Add the site health info to the site health page.
	 *
	 * @since 2.6.8
	 *
	 * @param array<mixed> $args The site health info arguments.
	 *
	 * @return array<mixed> The modified site health info arguments.
	 */
	public function site_health_info( $args ) {
		$debug_infos = array(
			'version'            => ACTIRISE_VERSION,
			'version_lastupdate' => Options::get( 'version-lastupdate', '-1' ),
			'uuid'               => Options::get( 'settings-uuid' ),
			'type'               => Options::get( 'settings-uuid-type', 'boot' ),
			'cron'               => defined( 'ACTIRISE_CRON' ) && ACTIRISE_CRON === 'true' ? 'true' : 'false',
			'noPub'              => Options::get( 'nopub', array() ),
			'customVar'          => array(
				'custom1' => Options::get( 'custom1', 'author_ID' ),
				'custom2' => Options::get( 'custom2', 'category_0_slug' ),
				'custom3' => Options::get( 'custom3', 'post_ID' ),
				'custom4' => Options::get( 'custom4', '' ),
				'custom5' => Options::get( 'custom5', '' ),
			),
			'adstxt'             => array(
				'actirise'    => Options::get( 'adstxt-actirise', '' ),
				'custom'      => Options::get( 'adstxt-custom', array() ),
				'enabled'     => Options::get( 'adstxt-active', false ) ? 'true' : 'false',
				'update'      => Options::get( 'adstxt-update', false ) ? 'true' : 'false',
				'file'        => Options::get( 'adstxt-file', false ) ? 'true' : 'false',
				'last_update' => Options::get( 'adstxt-lastupdate', '-1' ),
			),
			'presizedDiv'        => array(
				'actirise'    => Options::get( 'presizeddiv-actirise', array() ),
				'selected'    => Options::get( 'presizeddiv-selected', array() ),
				'enabled'     => Options::get( 'presizeddiv-active', false ) ? 'true' : 'false',
				'last_update' => Options::get( 'presizeddiv-lastupdate', '-1' ),
			),
			'cache'              => array(
				'wprocket'  => defined( 'WP_ROCKET_VERSION' ) ? 'true' : 'false',
				'wpmeteor'  => defined( 'WPMETEOR_VERSION' ) ? 'true' : 'false',
				'litespeed' => defined( 'LSCWP_V' ) ? 'true' : 'false',
			),
			'fastcmp'            => Helpers::get_fastcmp_options( false ),
			'api'                => array(
				'api_url_data' => ACTIRISE_URL_API_DATA,
				'api_url_v2'   => ACTIRISE_URL_API_V2,
				'api_token'    => ! empty( Options::get( 'settings-analytics-token', '' ) ) ? 'true' : 'false',
				'api_userid'   => Options::get( 'settings-analytics-userid', '' ),
				'currency'     => Options::get( 'currency', 'USD' ),
			),
			'autoUpdate'         => Options::get( 'auto-update', false ) ? 'true' : 'false',
			'logs'               => Logger::get_logs(),
			'logs_actions'       => Logger::get_logs_action(),
		);

		$fields = array();

		foreach ( $debug_infos as $key => $value ) {
			$debug = $value;

			if ( $key === 'noPub' ) {
				$value = array_map(
					function ( $item ) {
						return $item->url; // @phpstan-ignore property.nonObject
					},
					$value // @phpstan-ignore argument.type
				);

				$debug = $value;
			}

			if ( $key === 'logs' || $key === 'logs_actions' ) {
				$debug = array_map(
					function ( $item ) {
						return gettype( $item ) === 'array' ? wp_json_encode( $item ) : $item;
					},
					$value // @phpstan-ignore argument.type
				);
				$value = count( $value ); // @phpstan-ignore argument.type
			}

			if ( is_array( $value ) ) {
				$value = array_map(
					function ( $item ) {
						return gettype( $item ) === 'array' ? count( $item ) : $item;
					},
					$value
				);
			}

			if ( is_array( $debug ) ) {
				$debug = array_map(
					function ( $item ) {
						return gettype( $item ) === 'array' ? wp_json_encode( $item ) : $item;
					},
					$debug
				);
			}

			if ( $key === 'adstxt' ) {
				$value['actirise'] = gettype( $value['actirise'] ) === 'array' ? count( $value['actirise'] ) : strlen( $value['actirise'] ); // @phpstan-ignore argument.type
				$value['custom']   = gettype( $value['custom'] ) === 'array' ? count( $value['custom'] ) : strlen( $value['custom'] ); // @phpstan-ignore argument.type
			}

			if ( $key === 'fastcmp' ) {
				$value['stubLight']   = strlen( $value['stubLight'] ); // @phpstan-ignore argument.type
				$value['customStyle'] = strlen( $value['customStyle'] ); // @phpstan-ignore argument.type
			}

			$fields[$key] = array(
				'label'   => $key,
				'value'   => $value,
				'debug'   => $debug,
				'private' => false,
			);
		}

		$args[$this->plugin_name] = array(
			'label'       => esc_html__( 'Actirise', 'actirise' ),
			'description' => esc_html__( 'Actirise plugin settings', 'actirise' ),
			'fields'      => $fields,
		);

		return $args;
	}

	/**
	 * Add the site health status to the site health page.
	 *
	 * @since 2.6.8
	 *
	 * @param array<mixed> $args The site health status arguments.
	 *
	 * @return array<mixed> The modified site health status arguments.
	 */
	public function site_health_status( $args ) {
		$new_args = array(
			'actirise_cron' => array(
				'label' => esc_html__( 'Actirise', 'actirise' ),
				'test'  => array( $this, 'site_health_status_cron' ),
			),
			'actirise_tidy' => array(
				'label' => esc_html__( 'Actirise', 'actirise' ),
				'test'  => array( $this, 'site_health_status_tidy' ),
			),
		);

		$args['direct'] = $new_args + $args['direct'];

		return $args;
	}

	/**
	 * Check if WP Cron is enabled.
	 *
	 * @since 2.6.8
	 *
	 * @return array<mixed> The status block for WP Cron.
	 */
	public function site_health_status_cron() {
		$result = $this->define_status_bloc(
			__( 'Cron is enabled', 'actirise' ),
			__( 'Activating Cron allows you to keep your ads.txt file, pre-sized divs, and FastCMP updated automatically, ensuring optimal performance and seamless integration.', 'actirise' ),
			'cron'
		);

		if ( ACTIRISE_CRON !== 'true' ) {
			$result['status']         = 'recommended';
			$result['label']          = __( 'Cron is not enabled', 'actirise' );
			$result['actions']        = sprintf(
				'<p><a href="%s" target="_blank">%s</a></p>',
				esc_url( 'https://draftpress.com/docs/how-to-enable-wp-cron/' ),
				__( 'Enable WP Cron', 'actirise' )
			);
			$result['badge']['color'] = 'red';
		}

		return $result;
	}

	/**
	 * Check if PHP Tidy is enabled.
	 *
	 * @since 2.6.8
	 *
	 * @return array<mixed> The status block for PHP Tidy.
	 */
	public function site_health_status_tidy() {
		$result = $this->define_status_bloc(
			__( 'PHP Tidy is enabled', 'actirise' ),
			__( 'Enabling PHP Tidy improves the injection of pre-sized divs, reducing compatibility issues with certain WordPress themes and ensuring smoother ad placement.', 'actirise' ),
			'tidy'
		);

		if ( ! extension_loaded( 'tidy' ) ) {
			$result['label']          = __( 'PHP Tidy is not enabled', 'actirise' );
			$result['actions']        = sprintf(
				'<p><a href="%s" target="_blank">%s</a></p>',
				esc_url( 'https://www.php.net/manual/fr/book.tidy.php' ),
				__( 'Enable PHP Tidy', 'actirise' )
			);
			$result['status']         = 'recommended';
			$result['badge']['color'] = 'red';
		}

		return $result;
	}

	/**
	 * Define the status block for the site health.
	 *
	 * @since 2.6.8
	 *
	 * @param string $label       The label for the status block.
	 * @param string $description The description for the status block.
	 * @param string $test        The test to be performed.
	 *
	 * @return array<mixed> The status block definition.
	 */
	private function define_status_bloc( $label, $description, $test ) {
		$result = array(
			'label'       => $label,
			'status'      => 'good',
			'badge'       => array(
				'label' => __( 'Monetization', 'actirise' ),
				'color' => 'green',
			),
			'description' => sprintf(
				'<p>%s</p>',
				$description
			),
			'actions'     => '',
			'test'        => $test,
		);

		return $result;
	}
}
