<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Health {

	private static $checks = array();

	public static function calculate_score() {
		self::run_all_checks();
		$total       = 0;
		$max_total   = 0;
		$results     = array();

		foreach ( self::$checks as $check ) {
			$max_total += $check['weight'];
			if ( $check['pass'] ) {
				$total += $check['weight'];
			}
			$results[] = $check;
		}

		$score = $max_total > 0 ? (int) round( ( $total / $max_total ) * 100 ) : 0;
		$score = max( 0, min( 100, $score ) );

		return array(
			'score'       => $score,
			'grade'       => self::get_grade( $score ),
			'total'       => $total,
			'max_total'   => $max_total,
			'checks'      => $results,
			'timestamp'   => current_time( 'mysql' ),
		);
	}

	private static function get_grade( $score ) {
		if ( $score >= 90 ) return 'excellent';
		if ( $score >= 75 ) return 'good';
		if ( $score >= 50 ) return 'fair';
		if ( $score >= 25 ) return 'poor';
		return 'critical';
	}

	private static function run_all_checks() {
		self::$checks = array();

		self::check_2fa_enabled();
		self::check_login_limits();
		self::check_custom_login_url();
		self::check_password_policy();
		self::check_block_wp_login();
		self::check_geoip();
		self::check_cloudflare();
		self::check_device_tracking();
		self::check_session_timeout();
		self::check_email_notifications();
		self::check_auto_block();
		self::check_lockdown_not_active();
		self::check_audit_trail();
		self::check_db_tables();
		self::check_plugin_version();
		self::check_ssl();
		self::check_file_integrity();
		self::check_vulnerability_scan();
		self::check_admin_username();
		self::check_xmlrpc();
		self::check_debug_mode();
		self::check_weak_passwords();
		self::check_backup_plugin();
	}

	public static function get_recommendations() {
		self::run_all_checks();
		$recommendations = array();

		foreach ( self::$checks as $check ) {
			if ( ! $check['pass'] && ! empty( $check['recommendation'] ) ) {
				$recommendations[] = array(
					'id'          => $check['id'],
					'title'       => $check['title'],
					'description' => $check['recommendation'],
					'severity'    => $check['weight'] >= 15 ? 'high' : ( $check['weight'] >= 10 ? 'medium' : 'low' ),
					'weight'      => $check['weight'],
					'tab'         => $check['tab'] ?? 'settings',
				);
			}
		}

		usort( $recommendations, function( $a, $b ) {
			return $b['weight'] - $a['weight'];
		} );

		return $recommendations;
	}

	public static function apply_recommended_settings() {
		$settings = array(
			'zacls_2fa_enabled'           => 'yes',
			'zacls_2fa_forced_roles'      => array( 'administrator' ),
			'zacls_login_limits'          => array(
				'max_attempts' => 5,
				'time_window'  => 15,
				'lockout_time' => 30,
			),
			'zacls_auto_block_threshold'  => 10,
			'zacls_auto_block_duration'   => 1440,
			'zacls_block_wp_login'        => 'yes',
			'zacls_password_policy'       => array(
				'min_length'      => 12,
				'require_upper'   => 'yes',
				'require_lower'   => 'yes',
				'require_number'  => 'yes',
				'require_special' => 'yes',
			),
			'zacls_session_timeout'       => 60,
			'zacls_device_tracking'       => 'yes',
			'zacls_geoip_enabled'         => 'yes',
			'zacls_email_notifications'   => array(
				'failed_login' => 'yes',
				'new_ip_login' => 'yes',
				'ip_blocked'   => 'yes',
			),
			'zacls_report_frequency'      => 'weekly',
		);

		foreach ( $settings as $key => $value ) {
			update_option( $key, $value );
		}

		update_option( 'zacls_wizard_applied', 'yes' );
		ZACLS_Audit_Trail::log( 'wizard_applied', esc_html__( 'Security Wizard: recommended settings applied', 'za-creative-login-shield' ) );

		return true;
	}

	private static function add_check( $id, $title, $pass, $weight, $recommendation = '', $tab = 'settings' ) {
		self::$checks[] = array(
			'id'            => $id,
			'title'         => $title,
			'pass'          => $pass,
			'weight'        => $weight,
			'recommendation'=> $recommendation,
			'tab'           => $tab,
		);
	}

	private static function check_2fa_enabled() {
		$enabled = 'yes' === get_option( 'zacls_2fa_enabled', 'no' );
		self::add_check(
			'twofa',
			esc_html__( 'Two-Factor Authentication', 'za-creative-login-shield' ),
			$enabled,
			20,
			$enabled ? '' : esc_html__( 'Enable two-factor authentication to add an extra layer of security to user accounts.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_login_limits() {
		$limits = get_option( 'zacls_login_limits', array() );
		$pass   = isset( $limits['max_attempts'] ) && (int) $limits['max_attempts'] > 0 && (int) $limits['max_attempts'] <= 10;
		self::add_check(
			'login_limits',
			esc_html__( 'Login Rate Limiting', 'za-creative-login-shield' ),
			$pass,
			15,
			$pass ? '' : esc_html__( 'Configure login attempt limits to prevent brute-force attacks. Set max attempts between 3 and 10.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_custom_login_url() {
		$slug = get_option( 'zacls_custom_login_slug', '' );
		$pass = ! empty( $slug );
		self::add_check(
			'custom_login_url',
			esc_html__( 'Custom Login URL', 'za-creative-login-shield' ),
			$pass,
			10,
			$pass ? '' : esc_html__( 'Change the default wp-login.php URL to a custom slug to reduce automated attacks.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_block_wp_login() {
		$pass = 'yes' === get_option( 'zacls_block_wp_login', 'no' );
		self::add_check(
			'block_wp_login',
			esc_html__( 'Default Login Blocked', 'za-creative-login-shield' ),
			$pass,
			10,
			$pass ? '' : esc_html__( 'Block direct access to wp-login.php alongside your custom login URL.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_password_policy() {
		$policy = get_option( 'zacls_password_policy', array() );
		$pass   = isset( $policy['min_length'] ) && (int) $policy['min_length'] >= 8;
		self::add_check(
			'password_policy',
			esc_html__( 'Password Strength Policy', 'za-creative-login-shield' ),
			$pass,
			10,
			$pass ? '' : esc_html__( 'Enforce strong password requirements including minimum length, uppercase, lowercase, numbers, and special characters.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_geoip() {
		$pass = 'yes' === get_option( 'zacls_geoip_enabled', 'no' );
		self::add_check(
			'geoip',
			esc_html__( 'GeoIP Tracking', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Enable GeoIP to track login origin countries and detect suspicious geographic activity.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_cloudflare() {
		$pass = 'yes' === get_option( 'zacls_cloudflare_enabled', 'no' );
		self::add_check(
			'cloudflare',
			esc_html__( 'Cloudflare Integration', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Enable Cloudflare integration if your site uses Cloudflare to restore real visitor IPs.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_device_tracking() {
		$pass = 'yes' === get_option( 'zacls_device_tracking', 'no' );
		self::add_check(
			'device_tracking',
			esc_html__( 'Device Tracking', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Enable device fingerprinting to recognize trusted devices and detect suspicious login origins.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_session_timeout() {
		$timeout = (int) get_option( 'zacls_session_timeout', 1440 );
		$pass    = $timeout <= 480;
		self::add_check(
			'session_timeout',
			esc_html__( 'Session Timeout', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Reduce the session timeout duration. Sessions should expire after 8 hours or less for better security.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_email_notifications() {
		$settings = get_option( 'zacls_email_notifications', array() );
		$pass     = ! empty( $settings['failed_login'] ) && 'yes' === $settings['failed_login'];
		self::add_check(
			'email_notifications',
			esc_html__( 'Email Notifications', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Enable email notifications to stay informed about failed login attempts and security events.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_auto_block() {
		$threshold = (int) get_option( 'zacls_auto_block_threshold', 10 );
		$pass      = $threshold > 0 && $threshold <= 20;
		self::add_check(
			'auto_block',
			esc_html__( 'Auto-Block Threshold', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Set an automatic IP blocking threshold to block IPs after excessive failed login attempts.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_lockdown_not_active() {
		$pass = ! ZACLS_Emergency::is_lockdown_active();
		self::add_check(
			'lockdown',
			esc_html__( 'No Active Lockdown', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'Emergency lockdown is currently active. Normal login will be blocked.', 'za-creative-login-shield' ),
			'lockdown'
		);
	}

	private static function check_audit_trail() {
		global $wpdb;
		$count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}zacls_audit_log" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		$pass  = $count > 0;
		self::add_check(
			'audit_trail',
			esc_html__( 'Audit Trail Activity', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'No audit log entries found. Enable security logging to track administrative actions.', 'za-creative-login-shield' ),
			'audit-trail'
		);
	}

	private static function check_db_tables() {
		$missing = ZACLS_Install::tables_missing();
		self::add_check(
			'db_tables',
			esc_html__( 'Database Tables', 'za-creative-login-shield' ),
			! $missing,
			5,
			$missing ? esc_html__( 'Some database tables are missing. Deactivate and reactivate the plugin to create them.', 'za-creative-login-shield' ) : '',
			'dashboard'
		);
	}

	private static function check_plugin_version() {
		$db_version = get_option( ZACLS_Install::DB_VERSION_OPTION, '0.0.0' );
		$pass       = version_compare( $db_version, ZACLS_DB_VERSION, '>=' );
		self::add_check(
			'plugin_version',
			esc_html__( 'Plugin Up-to-Date', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'The plugin database needs to be upgraded. Visit any admin page to trigger the upgrade.', 'za-creative-login-shield' ),
			'dashboard'
		);
	}

	private static function check_ssl() {
		$pass = is_ssl();
		self::add_check(
			'ssl',
			esc_html__( 'SSL/HTTPS Enabled', 'za-creative-login-shield' ),
			$pass,
			10,
			$pass ? '' : esc_html__( 'Your site should use HTTPS/SSL to encrypt login credentials and session data in transit.', 'za-creative-login-shield' ),
			'dashboard'
		);
	}

	private static function check_file_integrity() {
		$last_check = get_option( 'zacls_file_check_last', 0 );
		$pass       = $last_check > 0;
		self::add_check(
			'file_integrity',
			esc_html__( 'File Integrity Monitoring', 'za-creative-login-shield' ),
			$pass,
			10,
			$pass ? '' : esc_html__( 'Run a file integrity check to verify your WordPress core, theme, and plugin files.', 'za-creative-login-shield' ),
			'file-monitor'
		);
	}

	private static function check_vulnerability_scan() {
		$last_scan = get_option( 'zacls_vuln_scan_last', 0 );
		$pass      = $last_scan > 0;
		self::add_check(
			'vuln_scan',
			esc_html__( 'Vulnerability Scanning', 'za-creative-login-shield' ),
			$pass,
			10,
			$pass ? '' : esc_html__( 'Run a vulnerability scan to check your installed plugins and themes against known security vulnerabilities.', 'za-creative-login-shield' ),
			'vulnerability'
		);
	}

	private static function check_admin_username() {
		$admin_user = get_user_by( 'login', 'admin' );
		self::add_check(
			'admin_username',
			esc_html__( 'Admin Username Not "admin"', 'za-creative-login-shield' ),
			! $admin_user,
			10,
			$admin_user ? esc_html__( 'Your site uses the default "admin" username — a primary target for brute-force attacks. Create a new admin user and remove "admin".', 'za-creative-login-shield' ) : '',
			'users'
		);
	}

	private static function check_xmlrpc() {
		$pass = ! apply_filters( 'xmlrpc_enabled', true );
		self::add_check(
			'xmlrpc',
			esc_html__( 'XML-RPC Disabled', 'za-creative-login-shield' ),
			$pass,
			5,
			$pass ? '' : esc_html__( 'XML-RPC is enabled, which can be exploited for brute-force and DDoS attacks. Disable it if you don\'t need it.', 'za-creative-login-shield' ),
			'settings'
		);
	}

	private static function check_debug_mode() {
		$debug = defined( 'WP_DEBUG' ) && WP_DEBUG;
		self::add_check(
			'debug_mode',
			esc_html__( 'WP_DEBUG Disabled on Production', 'za-creative-login-shield' ),
			! $debug,
			10,
			$debug ? esc_html__( 'WP_DEBUG is enabled on what appears to be a production site. This can expose sensitive information to visitors.', 'za-creative-login-shield' ) : '',
			'dashboard'
		);
	}

	private static function check_weak_passwords() {
		global $wpdb;
		$passwords = get_option( 'zacls_common_passwords', array() );
		$common    = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			"SELECT COUNT(*) FROM {$wpdb->users} u
			INNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
			WHERE um.meta_key = 'zacls_weak_password' AND um.meta_value = 'yes'"
		);
		self::add_check(
			'weak_passwords',
			esc_html__( 'No Weak Passwords Detected', 'za-creative-login-shield' ),
			! $common,
			10,
			$common ? sprintf( esc_html__( '%d user(s) have weak or commonly-used passwords. Enforce the password policy and require password reset.', 'za-creative-login-shield' ), $common ) : '',
			'settings'
		);
	}

	private static function check_backup_plugin() {
		$backup_plugins = array(
			'updraftplus/updraftplus.php',
			'backwpup/backwpup.php',
			'backupwordpress/backupwordpress.php',
			'jetpack/jetpack.php',
			'vaultpress/vaultpress.php',
			'backupbuddy/backupbuddy.php',
			'wp-clone-by-wp-academy/wp-clone.php',
			'all-in-one-wp-migration/all-in-one-wp-migration.php',
			'duplicator/duplicator.php',
		);
		$found = false;
		foreach ( $backup_plugins as $plugin ) {
			if ( is_plugin_active( $plugin ) ) {
				$found = true;
				break;
			}
		}
		self::add_check(
			'backup_plugin',
			esc_html__( 'Backup Plugin Installed', 'za-creative-login-shield' ),
			$found,
			5,
			$found ? '' : esc_html__( 'No backup plugin detected. Regular backups are essential for disaster recovery.', 'za-creative-login-shield' ),
			'dashboard'
		);
	}
}
