<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_File_Monitor {

	private static $checksums = array();

	public static function scan_core() {
		if ( ! function_exists( 'get_core_checksums' ) ) {
			require_once ABSPATH . 'wp-admin/includes/update.php';
		}

		global $wp_version;
		$checksums = get_core_checksums( $wp_version, 'en_US' );
		if ( ! is_array( $checksums ) ) {
			return array(
				'status'  => 'error',
				'message' => esc_html__( 'Unable to fetch WordPress core checksums.', 'za-creative-login-shield' ),
			);
		}

		self::$checksums = $checksums;
		$results         = array();
		$total_checked   = 0;
		$modified        = 0;
		$missing         = 0;

		foreach ( $checksums as $file => $expected_md5 ) {
			$path = ABSPATH . $file;
			if ( ! file_exists( $path ) ) {
				$missing++;
				$results[] = array(
					'file'   => $file,
					'status' => 'missing',
				);
				continue;
			}

			$total_checked++;
			$actual_md5 = md5_file( $path );
			if ( $actual_md5 !== $expected_md5 ) {
				$modified++;
				$results[] = array(
					'file'   => $file,
					'status' => 'modified',
					'type'   => 'core',
				);
			}
		}

		update_option( 'zacls_file_check_last', time() );
		update_option( 'zacls_file_check_results', $results );

		ZACLS_Audit_Trail::log(
			'file_scan_core',
			sprintf(
				esc_html__( 'Core file scan: %1$d checked, %2$d modified, %3$d missing', 'za-creative-login-shield' ),
				$total_checked,
				$modified,
				$missing
			)
		);

		return array(
			'status'        => $modified > 0 || $missing > 0 ? 'warning' : 'clean',
			'total_checked' => $total_checked,
			'modified'      => $modified,
			'missing'       => $missing,
			'results'       => $results,
		);
	}

	public static function scan_wp_config() {
		$results = array();

		if ( file_exists( ABSPATH . 'wp-config.php' ) ) {
			$results[] = array(
				'file'   => 'wp-config.php',
				'status' => 'exists',
				'hash'   => hash_file( 'sha256', ABSPATH . 'wp-config.php' ),
				'mtime'  => filemtime( ABSPATH . 'wp-config.php' ),
			);
		} elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) ) {
			$results[] = array(
				'file'   => 'wp-config.php (parent)',
				'status' => 'exists',
				'hash'   => hash_file( 'sha256', dirname( ABSPATH ) . '/wp-config.php' ),
				'mtime'  => filemtime( dirname( ABSPATH ) . '/wp-config.php' ),
			);
		} else {
			$results[] = array(
				'file'   => 'wp-config.php',
				'status' => 'missing',
			);
		}

		return $results;
	}

	public static function scan_htaccess() {
		$results = array();
		$path    = ABSPATH . '.htaccess';

		if ( file_exists( $path ) ) {
			$results[] = array(
				'file'   => '.htaccess',
				'status' => 'exists',
				'hash'   => hash_file( 'sha256', $path ),
				'mtime'  => filemtime( $path ),
				'size'   => filesize( $path ),
			);
		} else {
			$results[] = array(
				'file'   => '.htaccess',
				'status' => 'missing',
			);
		}

		return $results;
	}

	public static function scan_plugins() {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$plugins     = get_plugins();
		$results     = array();
		$found       = 0;

		$all_files = glob( WP_PLUGIN_DIR . '/*/*.php' );
		if ( false === $all_files ) {
			$all_files = array();
		}

		$checked = 0;
		foreach ( $plugins as $plugin_file => $plugin_data ) {
			$plugin_path = WP_PLUGIN_DIR . '/' . $plugin_file;
			if ( file_exists( $plugin_path ) ) {
				$hash = hash_file( 'sha256', $plugin_path );
				$results[] = array(
					'name'   => $plugin_data['Name'],
					'file'   => $plugin_file,
					'status' => 'exists',
					'hash'   => $hash,
					'version'=> $plugin_data['Version'],
				);
				$checked++;
			}
		}

		return array(
			'status'  => 'success',
			'checked' => $checked,
			'results' => $results,
		);
	}

	public static function scan_themes() {
		$themes = wp_get_themes();
		$results = array();

		foreach ( $themes as $slug => $theme ) {
			$stylesheet = $theme->get_stylesheet();
			$file_path  = $theme->get_stylesheet_directory() . '/style.css';
			$hash       = file_exists( $file_path ) ? hash_file( 'sha256', $file_path ) : '';

			$results[] = array(
				'name'    => $theme->get( 'Name' ),
				'slug'    => $slug,
				'status'  => file_exists( $file_path ) ? 'exists' : 'missing',
				'hash'    => $hash,
				'version' => $theme->get( 'Version' ),
			);
		}

		return $results;
	}

	public static function run_full_scan() {
		$core      = self::scan_core();
		$config    = self::scan_wp_config();
		$htaccess  = self::scan_htaccess();
		$plugins   = self::scan_plugins();
		$themes    = self::scan_themes();

		update_option( 'zacls_file_scan_results', compact( 'core', 'config', 'htaccess', 'plugins', 'themes' ) );
		update_option( 'zacls_file_scan_time', current_time( 'mysql' ) );

		$issues = ( $core['modified'] ?? 0 ) + ( $core['missing'] ?? 0 );
		ZACLS_Audit_Trail::log(
			'file_scan_full',
			sprintf(
				esc_html__( 'Full file integrity scan: %1$d core files checked, %2$d issues found', 'za-creative-login-shield' ),
				$core['total_checked'] ?? 0,
				$issues
			)
		);

		return compact( 'core', 'config', 'htaccess', 'plugins', 'themes' );
	}
}
