<?php

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

final class LVSW_Helpers {
	public static function log_event( $summary ) {
		$logs   = get_option( LVSW_Plugin::LOG_OPTION, array() );
		$logs[] = array(
			'time'    => gmdate( 'Y-m-d H:i:s' ),
			'summary' => (string) $summary,
		);
		if ( count( $logs ) > 200 ) {
			$logs = array_slice( $logs, -200 );
		}
		update_option( LVSW_Plugin::LOG_OPTION, $logs );
	}

	public static function fast_mode_cutoff_ts( $opts ) {
		if ( empty( $opts['fast_mode_enabled'] ) ) {
			return 0;
		}
		$days = isset( $opts['fast_mode_days'] ) ? (int) $opts['fast_mode_days'] : 0;
		if ( $days <= 0 ) {
			return 0;
		}
		return time() - ( $days * DAY_IN_SECONDS );
	}

	public static function count_warnings( $details ) {
		if ( empty( $details ) || ! is_array( $details ) ) {
			return 0;
		}

		$keys  = array(
			'core_recent_changes',
			'core_suspicious_recent',
			'js_suspected',
			'plugin_malware',
			'theme_malware',
			'muplugins_malware',
			'wpcontent_root_php',
			'uploads_exec_files',
			'uploads_php_suspected',
			'new_admins',
			'suspicious_admins',
			'admin_hygiene',
			'new_pre_user_id_entries',
			'users_can_register',
			'new_plugins',
			'deleted_plugins',
		);
		$count = 0;
		foreach ( $keys as $key ) {
			if ( ! empty( $details[ $key ] ) ) {
				$count++;
			}
		}
		return $count;
	}

	public static function get_environment_notes() {
		$notes = array();
		if ( ! empty( $_SERVER['HTTP_CF_RAY'] ) || ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) || ! empty( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) {
			$notes[] = 'Cloudflare headers detected';
		}
		if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) || ! empty( $_SERVER['HTTP_X_REAL_IP'] ) ) {
			$notes[] = 'Reverse proxy headers detected';
		}
		$notes[] = 'PHP ' . PHP_VERSION;
		$notes[] = 'WP ' . get_bloginfo( 'version' );
		return implode( ' | ', $notes );
	}

	public static function get_hardening_status( $opts ) {
		return array(
			'block_xmlrpc'               => ! empty( $opts['block_xmlrpc'] ),
			'block_file_editing'         => ! empty( $opts['block_file_mods'] ),
			'block_file_updates'         => ! empty( $opts['disallow_file_mods'] ),
			'disable_deletion'           => ! empty( $opts['disable_deletion'] ),
			'secure_head_cleanup'        => ! empty( $opts['secure_head_cleanup'] ),
			'hide_login_errors'          => ! empty( $opts['hide_login_errors'] ),
			'limit_login_attempts'       => ! empty( $opts['limit_login_attempts'] ),
			'block_pingbacks'            => ! empty( $opts['block_pingbacks'] ),
			'block_user_enum'            => ! empty( $opts['block_user_enum'] ),
			'block_comments'             => ! empty( $opts['block_comments'] ),
			'disable_app_passwords'      => ! empty( $opts['disable_application_passwords'] ),
			'block_admin_password_reset' => ! empty( $opts['block_admin_password_reset'] ),
		);
	}

	public static function get_blocked_ips_this_month_count() {
		$month = gmdate( 'Y-m' );
		$data  = get_option( LVSW_Plugin::BLOCKED_IPS_OPTION, array() );
		if ( ! is_array( $data ) || empty( $data[ $month ] ) || ! is_array( $data[ $month ] ) ) {
			return 0;
		}
		return count( $data[ $month ] );
	}

	public static function record_blocked_ip( $ip ) {
		if ( empty( $ip ) ) {
			return;
		}
		$month = gmdate( 'Y-m' );
		$data  = get_option( LVSW_Plugin::BLOCKED_IPS_OPTION, array() );
		if ( ! is_array( $data ) ) {
			$data = array();
		}
		if ( ! isset( $data[ $month ] ) || ! is_array( $data[ $month ] ) ) {
			$data[ $month ] = array();
		}
		$data[ $month ][ $ip ] = time();
		if ( count( $data ) > 12 ) {
			ksort( $data );
			$data = array_slice( $data, -12, null, true );
		}
		update_option( LVSW_Plugin::BLOCKED_IPS_OPTION, $data );
	}

	public static function send_email_report( $email, $details, $stats ) {
		if ( empty( $email ) || empty( $details ) ) {
			return;
		}

		$subject = '[Lumiverse Security Watchdog] Security Report for ' . get_bloginfo( 'name' );
		$lines   = array(
			'Lumiverse Security Watchdog scan report',
			'Site: ' . home_url(),
			'Generated: ' . date_i18n( 'Y-m-d H:i:s' ),
			'Files scanned (last run): ' . (int) ( $stats['files_scanned'] ?? 0 ),
			'Warnings (last run): ' . (int) ( $stats['warnings'] ?? 0 ),
			'',
		);

		foreach ( self::build_email_sections( $details ) as $section ) {
			$lines[] = '==================================================';
			$lines[] = $section['title'] . ' [RISK: ' . $section['risk'] . ']';
			$lines[] = 'What to do next: ' . $section['next'];
			$lines[] = '';
			foreach ( $section['body'] as $line ) {
				$lines[] = $line;
			}
			$lines[] = '';
		}

		$lines[] = 'Regards,';
		$lines[] = 'Lumiverse Security Watchdog';
		wp_mail( $email, $subject, implode( "\n", $lines ) );
		self::log_event( 'Report email sent to ' . $email );
	}

	private static function build_email_sections( $details ) {
		$sections = array();
		$push     = static function( $title, $risk, $next, $body ) use ( &$sections ) {
			if ( empty( $body ) ) {
				return;
			}
			$sections[] = array(
				'title' => $title,
				'risk'  => $risk,
				'next'  => $next,
				'body'  => $body,
			);
		};

		if ( ! empty( $details['core_suspicious_recent'] ) ) {
			$body = array( 'Suspicious patterns in recently modified core PHP:' );
			foreach ( $details['core_suspicious_recent'] as $file => $hits ) {
				$body[] = ' - ' . $file;
				foreach ( (array) $hits as $hit ) {
					$body[] = '    match: ' . $hit;
				}
			}
			$push( 'Core suspicious PHP (last 7 days)', 'HIGH', 'Reinstall WordPress core and investigate how these files changed.', $body );
		}

		if ( ! empty( $details['core_recent_changes'] ) ) {
			$body = array( 'Important core files modified in last 7 days:' );
			foreach ( $details['core_recent_changes'] as $row ) {
				$body[] = ' - ' . ( $row['path'] ?? '' ) . ' (mtime: ' . ( ! empty( $row['mtime'] ) ? date( 'c', (int) $row['mtime'] ) : 'n/a' ) . ')';
			}
			$push( 'Core recent changes', 'MEDIUM', 'If you did not just update WordPress, investigate and consider a clean core reinstall.', $body );
		}

		if ( ! empty( $details['users_can_register'] ) ) {
			$body = array(
				'WordPress setting “Anyone can register” is enabled.',
				'Auto-fix enabled: ' . ( ! empty( $details['users_can_register']['fix_enabled'] ) ? 'Yes' : 'No' ),
			);
			$push( 'Open registration enabled', 'MEDIUM', 'Disable it if the site should not allow open signups and review recent users.', $body );
		}

		foreach ( array(
			'plugin_malware'    => array( 'Plugins suspicious indicators', 'HIGH', 'Disable or replace suspicious plugins and investigate the install source.' ),
			'theme_malware'     => array( 'Themes suspicious indicators', 'HIGH', 'Inspect theme files and restore a clean copy.' ),
			'muplugins_malware' => array( 'MU-plugins suspicious indicators', 'HIGH', 'Unknown MU-plugins are common persistence points. Remove or review immediately.' ),
		) as $key => $meta ) {
			if ( empty( $details[ $key ] ) ) {
				continue;
			}
			$body = array( 'Findings:' );
			foreach ( $details[ $key ] as $group => $info ) {
				$body[] = ' - ' . $group;
				if ( ! empty( $info['suspicious_name'] ) ) {
					$body[] = '    suspicious folder/name';
				}
				if ( ! empty( $info['files'] ) ) {
					foreach ( $info['files'] as $file => $matches ) {
						$body[] = '    - ' . $file;
						foreach ( (array) $matches as $m ) {
							$body[] = '       match: ' . $m;
						}
					}
				}
			}
			$push( $meta[0], $meta[1], $meta[2], $body );
		}

		if ( ! empty( $details['js_suspected'] ) ) {
			$body = array( 'Suspicious JS files:' );
			foreach ( $details['js_suspected'] as $file => $reasons ) {
				$body[] = ' - ' . $file;
				foreach ( (array) $reasons as $reason ) {
					$body[] = '    * ' . $reason;
				}
			}
			$push( 'JS suspicious indicators', 'MEDIUM', 'Inspect these files and verify their source.', $body );
		}

		if ( ! empty( $details['wpcontent_root_php'] ) ) {
			$body = array( 'wp-content root PHP findings:' );
			foreach ( $details['wpcontent_root_php'] as $row ) {
				$body[] = ' - ' . ( $row['path'] ?? '' ) . ' (' . ( $row['type'] ?? '' ) . ')';
				if ( ! empty( $row['hits'] ) ) {
					foreach ( (array) $row['hits'] as $hit ) {
						$body[] = '    hit: ' . $hit;
					}
				}
				if ( ! empty( $row['note'] ) ) {
					$body[] = '    note: ' . $row['note'];
				}
			}
			$push( 'wp-content root PHP findings', 'MEDIUM', 'Review these files. Some are legitimate cache drop-ins, some are persistence tricks.', $body );
		}

		if ( ! empty( $details['uploads_exec_files'] ) ) {
			$body = array( 'Executable files found in uploads:' );
			foreach ( $details['uploads_exec_files'] as $path ) {
				$body[] = ' - ' . $path;
			}
			$push( 'Executable files in uploads', 'HIGH', 'Uploads should almost never contain executables. Quarantine and investigate immediately.', $body );
		}

		if ( ! empty( $details['uploads_php_suspected'] ) ) {
			$body = array( 'Suspicious PHP found in uploads:' );
			foreach ( $details['uploads_php_suspected'] as $file => $hits ) {
				$body[] = ' - ' . $file;
				foreach ( (array) $hits as $hit ) {
					$body[] = '    match: ' . $hit;
				}
			}
			$push( 'Suspicious PHP in uploads', 'HIGH', 'Treat this as compromise until proven otherwise.', $body );
		}

		if ( ! empty( $details['new_admins'] ) ) {
			$body = array( 'New administrator accounts:' );
			foreach ( $details['new_admins'] as $id => $data ) {
				$body[] = sprintf( ' - ID:%s user:%s email:%s created:%s', $id, $data['user_login'] ?? '', $data['user_email'] ?? '', ! empty( $data['registered'] ) ? date( 'c', (int) $data['registered'] ) : '' );
			}
			$push( 'New administrator detected', 'MEDIUM', 'Confirm the account is expected. Remove unknown admins and rotate credentials.', $body );
		}

		if ( ! empty( $details['suspicious_admins'] ) ) {
			$body = array( 'Suspicious administrator accounts:' );
			foreach ( $details['suspicious_admins'] as $id => $data ) {
				$body[] = sprintf( ' - ID:%s user:%s email:%s', $id, $data['user_login'] ?? '', $data['user_email'] ?? '' );
			}
			$push( 'Suspicious administrator accounts', 'HIGH', 'Inspect these users. Invalid emails and strange usernames are common in compromises.', $body );
		}

		if ( ! empty( $details['admin_hygiene'] ) ) {
			$body = array( 'Admin hygiene warnings:' );
			foreach ( $details['admin_hygiene'] as $id => $row ) {
				$body[] = ' - ID:' . $id . ' user:' . ( $row['user_login'] ?? '' ) . ' — ' . ( $row['reason'] ?? '' );
			}
			$push( 'Admin hygiene warnings', 'LOW', 'Consider renaming common admin usernames and making sure strong passwords and 2FA are in use.', $body );
		}

		if ( ! empty( $details['new_pre_user_id_entries'] ) ) {
			$body = array( '_pre_user_id* options found:' );
			foreach ( $details['new_pre_user_id_entries'] as $name => $row ) {
				$body[] = ' - ' . $name;
			}
			$push( 'Database _pre_user_id entries', 'MEDIUM', 'Review plugins and database for persistence mechanisms.', $body );
		}

		if ( ! empty( $details['new_plugins'] ) ) {
			$body = array( 'New plugins detected:' );
			foreach ( $details['new_plugins'] as $plugin ) {
				$body[] = ' - ' . $plugin;
			}
			$push( 'New plugins detected', 'LOW', 'Confirm these installs are expected.', $body );
		}

		if ( ! empty( $details['deleted_plugins'] ) ) {
			$body = array( 'Deleted plugins detected:' );
			foreach ( $details['deleted_plugins'] as $plugin ) {
				$body[] = ' - ' . $plugin;
			}
			$push( 'Deleted plugins detected', 'LOW', 'Confirm deletions are expected. Unexpected deletions can indicate tampering.', $body );
		}

		return $sections;
	}
}
