<?php

namespace PaymentPage;

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

class SiteHealth {

	/**
	 * @var null|SiteHealth;
	 */
	protected static $_instance = null;

	/**
	 * @return SiteHealth
	 */
	public static function instance(): SiteHealth {
		if ( self::$_instance === null ) {
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	public function tests( $tests ) {
		$tests['direct'][ PAYMENT_PAGE_ALIAS . '_test_database_integrity' ] = [
			/* translators: %s: plugin name */
			'label' => __( '%s - Database Integrity', "payment-page" ),
			'test'  => [ $this, 'database_integrity' ],
		];

		return $tests;
	}

	public function database_integrity(): array {
		$default = [
			/* translators: %s: plugin name */
			'description' => '<p>' . sprintf( __( "%s uses custom tables to store data efficiently.", "payment-page" ), PAYMENT_PAGE_NAME ) . '</p>',
			'test'        => PAYMENT_PAGE_ALIAS . '_test_cron_requirement',
		];

		if ( Migration::instance()->is_valid_table_structure() ) {
			return [
				       /* translators: %s: plugin name */
				       'label'  => sprintf( __( "%s - Valid DB Table Structure.", "payment-page" ), PAYMENT_PAGE_NAME ),
				       'status' => 'good',
				       'badge'  => [
					       'label' => __( 'Critical', "payment-page" ),
					       'color' => 'green',
				       ],
			       ] + $default;
		}

		return [
			       /* translators: %s: plugin name */
			       'label'   => sprintf( __( "%s - Invalid DB Table Structure.", "payment-page" ), PAYMENT_PAGE_NAME ),
			       'status'  => 'critical',
			       'badge'   => [
				       'label' => __( 'Critical', "payment-page" ),
				       'color' => 'red',
			       ],
			       'actions' => sprintf(
				       '<p><a href="%s">%s</a></p>',
				       // (Audit F011) Nonce-protect the force-db-table-integrity trigger.
				       esc_url( wp_nonce_url(
					       admin_url( '?' . PAYMENT_PAGE_PREFIX . '-action=force-db-table-integrity' ),
					       'payment_page_force_db_table_integrity'
				       ) ),
				       __( "Fix Table Integrity", "payment-page" )
			       ),
		       ] + $default;
	}

}