<?php
/**
 * Plugin health-check evaluator.
 *
 * Each check returns one of: 'ok', 'warn', 'fail'. The collection
 * answers "is the plugin in a healthy state?" without any UI coupling.
 *
 * @package KaizenCoders\MagicLink\AuditLog
 */

namespace KaizenCoders\MagicLink\AuditLog;

use KaizenCoders\MagicLink\Helper;
use KaizenCoders\MagicLink\IntentConfirmation;

class HealthCheck {

	const STATUS_OK   = 'ok';
	const STATUS_WARN = 'warn';
	const STATUS_FAIL = 'fail';

	/**
	 * Run every check and return a summary.
	 *
	 * @return array  array of array{id,status,message}
	 */
	public static function run() {
		$results = array();
		$results[] = self::check_mail();
		$results[] = self::check_tables();
		$results[] = self::check_intent_confirmation();
		$results[] = self::check_token_lifespan();

		return $results;
	}

	/**
	 * Roll up to a single status: fail if any fail, warn if any warn, else ok.
	 *
	 * @param  array $results Result rows.
	 *
	 * @return string
	 */
	public static function rollup( $results ) {
		$status = self::STATUS_OK;
		foreach ( (array) $results as $r ) {
			if ( self::STATUS_FAIL === ( isset( $r['status'] ) ? $r['status'] : '' ) ) {
				return self::STATUS_FAIL;
			}
			if ( self::STATUS_WARN === ( isset( $r['status'] ) ? $r['status'] : '' ) ) {
				$status = self::STATUS_WARN;
			}
		}
		return $status;
	}

	/**
	 * wp_mail should exist and be callable.
	 *
	 * @return array
	 */
	public static function check_mail() {
		$ok = function_exists( 'wp_mail' );
		return array(
			'id'      => 'mail',
			'status'  => $ok ? self::STATUS_OK : self::STATUS_FAIL,
			'message' => $ok
				? __( 'wp_mail is available.', 'magic-link' )
				: __( 'wp_mail is missing; magic-link emails cannot be sent.', 'magic-link' ),
		);
	}

	/**
	 * Audit-log and magic-link tables should exist.
	 *
	 * @return array
	 */
	public static function check_tables() {
		if ( ! isset( $GLOBALS['wpdb'] ) || ! is_object( $GLOBALS['wpdb'] ) ) {
			return array(
				'id'      => 'tables',
				'status'  => self::STATUS_FAIL,
				'message' => __( 'WPDB is not available.', 'magic-link' ),
			);
		}
		global $wpdb;
		$audit = Logger::table();
		$links = $wpdb->prefix . 'kc_ml_magic_links';

		$audit_ok = method_exists( $wpdb, 'get_var' ) && $wpdb->get_var( "SHOW TABLES LIKE '" . $audit . "'" );
		$links_ok = method_exists( $wpdb, 'get_var' ) && $wpdb->get_var( "SHOW TABLES LIKE '" . $links . "'" );

		if ( $audit_ok && $links_ok ) {
			return array(
				'id'      => 'tables',
				'status'  => self::STATUS_OK,
				'message' => __( 'Required tables are present.', 'magic-link' ),
			);
		}
		return array(
			'id'      => 'tables',
			'status'  => self::STATUS_FAIL,
			'message' => __( 'One or more required tables are missing. Re-run installation.', 'magic-link' ),
		);
	}

	/**
	 * Scanner protection should be enabled — warn if user has turned it off.
	 *
	 * @return array
	 */
	public static function check_intent_confirmation() {
		$enabled = IntentConfirmation::is_enabled();
		return array(
			'id'      => 'intent_confirmation',
			'status'  => $enabled ? self::STATUS_OK : self::STATUS_WARN,
			'message' => $enabled
				? __( 'Email-scanner protection is enabled.', 'magic-link' )
				: __( 'Email-scanner protection is OFF. Single-use links may be silently consumed by Outlook Safe Links / Mimecast / Proofpoint.', 'magic-link' ),
		);
	}

	/**
	 * Token lifespan should be a sensible value.
	 *
	 * @return array
	 */
	public static function check_token_lifespan() {
		$settings = function_exists( 'get_option' ) ? get_option( 'kc_ml_settings', array() ) : array();
		$value    = Helper::get_data( $settings, 'general|settings|token_lifespan', 5 );
		$unit     = Helper::get_data( $settings, 'general|settings|token_lifespan_unit', 'minutes' );

		$minutes = (int) $value;
		if ( 'hours' === $unit ) {
			$minutes *= 60;
		} elseif ( 'days' === $unit ) {
			$minutes *= 1440;
		}

		if ( $minutes <= 0 ) {
			return array(
				'id'      => 'token_lifespan',
				'status'  => self::STATUS_FAIL,
				'message' => __( 'Token lifespan is 0 or negative.', 'magic-link' ),
			);
		}
		if ( $minutes > 7 * 1440 ) {
			return array(
				'id'      => 'token_lifespan',
				'status'  => self::STATUS_WARN,
				'message' => __( 'Token lifespan is longer than 7 days. Consider shortening it.', 'magic-link' ),
			);
		}
		return array(
			'id'      => 'token_lifespan',
			'status'  => self::STATUS_OK,
			'message' => __( 'Token lifespan is within recommended bounds.', 'magic-link' ),
		);
	}
}
