<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Modules\Maintenance;

use WPUltimateSecurity\UltimateSecurity\Modules\Base\AbstractModule;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use Core_Upgrader;
use Theme_Upgrader;
use Plugin_Upgrader;

class UpdateManager extends AbstractModule
{
    public const MODULE_ID = 'maintenance.update_manager';

    protected const VERSION = '2.0.0';

    /**
     * Get unique module identifier.
     */
    public static function getId(): string
    {
        return self::MODULE_ID;
    }

    /**
     * Get human-readable module name.
     */
    public static function getName(): string
    {
        return __('Update Manager', 'ultimate-security');
    }

    /**
     * Get module domain.
     */
    public static function getDomain(): string
    {
        return 'maintenance';
    }

	private static $options;

    /**
     * Boot the module after registration.
     */
	public static function boot(): void
	{
		self::$options = Utils::ultimate_security_get_option();

		add_action('wp_ajax_ultimate_security_send_update_notification_test_email', [self::class, 'ultimate_security_send_update_notification_test_email']);
		// add_action('wp_ajax_nopriv_ultimate_security_send_update_notification_test_email', [self::class, 'ultimate_security_send_update_notification_test_email']);

		add_action('wp_ajax_ultimate_security_update_plugins', [self::class, 'ultimate_security_update_plugins']);
		// add_action('wp_ajax_nopriv_ultimate_security_update_plugins', [self::class, 'ultimate_security_update_plugins']);

		add_action('wp_ajax_ultimate_security_update_themes', [self::class, 'ultimate_security_update_themes']);
		// add_action('wp_ajax_nopriv_ultimate_security_update_themes', [self::class, 'ultimate_security_update_themes']);

		add_action('wp_ajax_ultimate_security_update_core', [self::class, 'ultimate_security_update_core']);
		// add_action('wp_ajax_nopriv_ultimate_security_update_core', [self::class, 'ultimate_security_update_core']);

		// New endpoints for progress-based updates
		add_action('wp_ajax_ultimate_security_get_pending_updates', [self::class, 'ultimate_security_get_pending_updates']);
		add_action('wp_ajax_ultimate_security_update_single_plugin', [self::class, 'ultimate_security_update_single_plugin']);
		add_action('wp_ajax_ultimate_security_update_single_theme', [self::class, 'ultimate_security_update_single_theme']);


		// add_action('init', [self::class, 'ultimate_security_apply_update_settings']);

		// Hook for successful update notifications
		add_action('upgrader_process_complete', [self::class, 'ultimate_security_handle_update_complete'], 10, 2);
		add_action('ultimate_security_send_update_success_email', [self::class, 'ultimate_security_send_update_success_email'], 10, 2);

		$email_notifications = isset(self::$options['security']['updates']['email_notifications']) ? sanitize_text_field(wp_unslash(self::$options['security']['updates']['email_notifications'])) : 0;
		if ($email_notifications == 1) {
			add_filter('cron_schedules', [self::class, 'ultimate_security_custom_cron_schedules']);
			add_action('wp', [self::class, 'ultimate_security_schedule_daily_9am_cron']);
			add_action('ultimate_security_daily_9am_task', [self::class, 'ultimate_security_handle_daily_9am_task']);
		} else {
			// Deactivate the cron
			add_action('init', [self::class, 'ultimate_security_remove_daily_9am_cron']);
		}
		$core_notifications = isset(self::$options['security']['updates']['core_notifications']) ? sanitize_text_field(wp_unslash(self::$options['security']['updates']['core_notifications'])) : 0;
		if ($core_notifications) {
			add_filter('auto_core_update_send_email', '__return_false');
		}
	}
	public static function ultimate_security_send_update_notification_test_email()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {

			$email = (isset($_POST['email']) && sanitize_email(wp_unslash($_POST['email']))) ? sanitize_email(wp_unslash($_POST['email'])) : get_option('admin_email');
			self::ultimate_security_test_emails($email);

			wp_send_json_success(
				array(
					'success_message' => esc_html__('Email has been send successfully!.', 'ultimate-security'),
					'email' => $email,
				)
			);
		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
		wp_die();
	}
	public static function ultimate_security_custom_cron_schedules($schedules)
	{
		if (!isset($schedules['daily_9am'])) {
			$schedules['daily_9am'] = array(
				'interval' => 86400, // 24 hours
				'display' => __('Once Daily at 9 AM', 'ultimate-security'),
			);
		}

		return $schedules;
	}

	public static function ultimate_security_schedule_daily_9am_cron()
	{
		if (!wp_next_scheduled('ultimate_security_daily_9am_task')) {
			$timezone = get_option('timezone_string') ?: 'UTC'; // Get WP timezone
			$now = new \DateTime('now', new \DateTimeZone($timezone));
			$next_run = $now->setTime(9, 0, 0)->getTimestamp();

			if ($next_run < time()) {
				$next_run += 86400; // Move to next day if past 9 AM today
			}

			wp_schedule_event($next_run, 'daily_9am', 'ultimate_security_daily_9am_task');
		}
	}

	public static function ultimate_security_handle_daily_9am_task()
	{
		// Your custom task here
		$notification_type = isset(self::$options['security']['updates']['notification_type']) ? sanitize_text_field(wp_unslash(self::$options['security']['updates']['notification_type'])) : '';

		$email = isset(self::$options['security']['updates']['email_address']) ? sanitize_text_field(wp_unslash(self::$options['security']['updates']['email_address'])) : get_option('admin_email');

		$notification_type_values = $notification_type ? array_column(json_decode($notification_type), 'value') : [];
		$notification_type_codes = $notification_type ? array_column(json_decode($notification_type), 'code') : [];
		if (in_array('update_available', $notification_type_codes)) {
			self::ultimate_security_test_emails($email);
		}
	}

	public static function ultimate_security_remove_daily_9am_cron()
	{
		$timestamp = wp_next_scheduled('ultimate_security_daily_9am_task');
		if ($timestamp) {
			wp_unschedule_event($timestamp, 'ultimate_security_daily_9am_task');
		}
	}
	// add_action('init', 'ultimate_security_remove_daily_9am_cron');
	public static function ultimate_security_test_emails($email)
	{
		require_once ABSPATH . 'wp-admin/includes/theme.php';
		require_once ABSPATH . 'wp-admin/includes/plugin.php';
		require_once ABSPATH . 'wp-admin/includes/update.php';

		$user = get_user_by('email', $email);
		$display_name = $user ? $user->display_name : esc_html__('User', 'ultimate-security');
		// $headers = array('Content-Type: text/html; charset=UTF-8');
		$headers = array();


		// Initialize email content
		$output = '';
		$has_updates = false;

		$output .= __('Hello ', 'ultimate-security') . esc_html($display_name) . ',<br><br>';

		// ======================
		// 🔍 Plugin Updates
		// ======================
		wp_update_plugins();
		$all_plugins = Utils::get_plugins_cached();
		$plugin_updates = get_plugin_updates();

		if (!empty($plugin_updates)) {
			$has_updates = true;
			$output .= __('The following WordPress plugins have new updates:', 'ultimate-security') . '<br><br>';

			foreach ($plugin_updates as $plugin_file => $plugin_data) {
				$plugin = $all_plugins[$plugin_file];
				$output .= '- ' . esc_html($plugin['Name']) . ': ' . esc_html($plugin['Version']) . ' → ' . esc_html($plugin_data->update->new_version) . '<br>';
			}

			$output .= '<br>';
		}

		// ======================
		// 🎨 Theme Updates
		// ======================
		wp_update_themes();
		$all_themes = Utils::get_themes_cached();
		$theme_updates = get_theme_updates();

		if (!empty($theme_updates)) {
			$has_updates = true;
			$output .= __('The following WordPress themes have new updates:', 'ultimate-security') . '<br><br>';

			foreach ($theme_updates as $stylesheet => $theme_data) {
				$theme = $all_themes[$stylesheet];
				$output .= '- ' . esc_html($theme->get('Name')) . ': ' . esc_html($theme->get('Version')) . ' → ' . esc_html($theme_data->update['new_version']) . '<br>';
			}

			$output .= '<br>';
		}

		// Only send if there are updates
		if ($has_updates) {
			$output .= __('You can view your WordPress site here:', 'ultimate-security') . ' ' . get_home_url() . '<br>';
			$output .= __('Updates typically include security fixes, performance improvements, or new features.', 'ultimate-security');
			add_filter('wp_mail_content_type', 'set_html_content_type');
			wp_mail(
				$email,
				esc_html__('WordPress Updates Available', 'ultimate-security'),
				$output,
				$headers
			);
			remove_filter('wp_mail_content_type', 'set_html_content_type');
		}
	}

	/**
	 * Force update WordPress core
	 */
	public static function ultimate_security_update_core()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
			// Include necessary files for updates
			require_once ABSPATH . 'wp-admin/includes/update.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

			// Get current and latest WP versions
			$current_version = get_bloginfo('version');
			$updates = get_core_updates();

			if (!empty($updates) && is_array($updates) && isset($updates[0]->current)) {
				set_time_limit(300); // 5 minutes
				$latest_version = $updates[0]->current;
				if (version_compare($current_version, $latest_version, '<')) {
					// Update Core
					$upgrader = new Core_Upgrader();
					$result = $upgrader->upgrade($updates[0]);
				}
			}
			wp_send_json_success([
				'success_message' => __('WordPress core has been updated successfully.', 'ultimate-security'),
			]);
			
		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
	}

	/**
	 * Force update all plugins
	 */
	public static function ultimate_security_update_plugins()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
			require_once ABSPATH . 'wp-admin/includes/update.php';
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-core-upgrader.php';

			wp_update_plugins();
			$plugin_upgrader = new Plugin_Upgrader();
			$plugin_updates = get_site_transient('update_plugins');
			if (is_array($plugin_updates) && sizeof($plugin_updates))
				set_time_limit(sizeof($plugin_updates) * 300);

			$plugins = !empty($plugin_updates->response) ? $plugin_upgrader->bulk_upgrade(array_keys($plugin_updates->response)) : [];
			wp_send_json_success([
				'success_message' => __('All plugins have been updated successfully.', 'ultimate-security'),
			]);
			
		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
		wp_die();
	}

	/**
	 * Force update all themes
	 */
	public static function ultimate_security_update_themes()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
			require_once ABSPATH . 'wp-admin/includes/update.php';
			require_once ABSPATH . 'wp-admin/includes/upgrade.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-core-upgrader.php';

			set_time_limit(300);
			wp_update_themes();
			$theme_upgrader = new Theme_Upgrader();
			$theme_updates = get_site_transient('update_themes');
			if (is_array($theme_updates) && sizeof($theme_updates))
				set_time_limit(sizeof($theme_updates) * 300);

			$themes = !empty($theme_updates->response) ? $theme_upgrader->bulk_upgrade(array_keys($theme_updates->response)) : [];
			wp_send_json_success([
				'success_message' => __('All themes have been updated successfully.', 'ultimate-security'),
			]);

		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
		wp_die();
	}

	/**
	 * Get list of all pending updates with details
	 */
	public static function ultimate_security_get_pending_updates()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
			require_once ABSPATH . 'wp-admin/includes/update.php';
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
			require_once ABSPATH . 'wp-admin/includes/theme.php';

			// Force check for updates
			wp_update_plugins();
			wp_update_themes();

			$updates = [
				'plugins' => [],
				'themes' => [],
				'core' => null
			];

			// Get plugin updates
			$all_plugins = Utils::get_plugins_cached();
			$plugin_updates = get_site_transient('update_plugins');
			if (!empty($plugin_updates->response)) {
				foreach ($plugin_updates->response as $plugin_file => $plugin_data) {
					$plugin_info = isset($all_plugins[$plugin_file]) ? $all_plugins[$plugin_file] : [];
					$updates['plugins'][] = [
						'file' => $plugin_file,
						'name' => isset($plugin_info['Name']) ? $plugin_info['Name'] : $plugin_file,
						'current_version' => isset($plugin_info['Version']) ? $plugin_info['Version'] : '',
						'new_version' => isset($plugin_data->new_version) ? $plugin_data->new_version : '',
					];
				}
			}

			// Get theme updates
			$all_themes = Utils::get_themes_cached();
			$theme_updates = get_site_transient('update_themes');
			if (!empty($theme_updates->response)) {
				foreach ($theme_updates->response as $theme_slug => $theme_data) {
					$theme_info = isset($all_themes[$theme_slug]) ? $all_themes[$theme_slug] : null;
					$updates['themes'][] = [
						'slug' => $theme_slug,
						'name' => $theme_info ? $theme_info->get('Name') : $theme_slug,
						'current_version' => $theme_info ? $theme_info->get('Version') : '',
						'new_version' => isset($theme_data['new_version']) ? $theme_data['new_version'] : '',
					];
				}
			}

			// Get core updates
			$core_updates = get_core_updates();
			if (!empty($core_updates) && is_array($core_updates) && isset($core_updates[0]->current)) {
				$current_version = get_bloginfo('version');
				$latest_version = $core_updates[0]->current;
				if (version_compare($current_version, $latest_version, '<')) {
					$updates['core'] = [
						'current_version' => $current_version,
						'new_version' => $latest_version,
					];
				}
			}

			wp_send_json_success($updates);
		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
		wp_die();
	}

	/**
	 * Update a single plugin
	 */
	public static function ultimate_security_update_single_plugin()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
			$plugin_file = isset($_POST['plugin_file']) ? sanitize_text_field(wp_unslash($_POST['plugin_file'])) : '';

			if (empty($plugin_file)) {
				wp_send_json_error(['error_message' => __('Plugin file is required.', 'ultimate-security')]);
				wp_die();
			}

			require_once ABSPATH . 'wp-admin/includes/update.php';
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';

			set_time_limit(300);

			// Get plugin info before update (use cached version)
			$all_plugins = Utils::get_plugins_cached();
			$plugin_info = isset($all_plugins[$plugin_file]) ? $all_plugins[$plugin_file] : [];
			$old_version = isset($plugin_info['Version']) ? $plugin_info['Version'] : '';

			// Silent upgrader skin to suppress output
			$skin = new \WP_Ajax_Upgrader_Skin();
			$upgrader = new Plugin_Upgrader($skin);
			$result = $upgrader->upgrade($plugin_file);

			// Get new version after update (clear cache and get fresh data)
			wp_cache_delete('plugins', 'plugins');
			Utils::clear_all_caches(); // Clear our static cache
			$all_plugins = Utils::get_plugins_cached();
			$plugin_info_new = isset($all_plugins[$plugin_file]) ? $all_plugins[$plugin_file] : [];
			$new_version = isset($plugin_info_new['Version']) ? $plugin_info_new['Version'] : '';

			if (is_wp_error($result)) {
				wp_send_json_error([
					'error_message' => $result->get_error_message(),
					'plugin_file' => $plugin_file,
					'plugin_name' => isset($plugin_info['Name']) ? $plugin_info['Name'] : $plugin_file,
					'old_version' => $old_version,
				]);
			} elseif ($result === false) {
				wp_send_json_error([
					'error_message' => __('Update failed.', 'ultimate-security'),
					'plugin_file' => $plugin_file,
					'plugin_name' => isset($plugin_info['Name']) ? $plugin_info['Name'] : $plugin_file,
					'old_version' => $old_version,
				]);
			} else {
				wp_send_json_success([
					'success_message' => __('Plugin updated successfully.', 'ultimate-security'),
					'plugin_file' => $plugin_file,
					'plugin_name' => isset($plugin_info['Name']) ? $plugin_info['Name'] : $plugin_file,
					'old_version' => $old_version,
					'new_version' => $new_version,
				]);
			}
		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
		wp_die();
	}

	/**
	 * Update a single theme
	 */
	public static function ultimate_security_update_single_theme()
	{
		if (isset($_POST['security']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'ultimate_security_nonce')) {
			$theme_slug = isset($_POST['theme_slug']) ? sanitize_text_field(wp_unslash($_POST['theme_slug'])) : '';

			if (empty($theme_slug)) {
				wp_send_json_error(['error_message' => __('Theme slug is required.', 'ultimate-security')]);
				wp_die();
			}

			require_once ABSPATH . 'wp-admin/includes/update.php';
			require_once ABSPATH . 'wp-admin/includes/theme.php';
			require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
			require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader.php';

			set_time_limit(300);

			// Get theme info before update
			$theme = wp_get_theme($theme_slug);
			$old_version = $theme->exists() ? $theme->get('Version') : '';
			$theme_name = $theme->exists() ? $theme->get('Name') : $theme_slug;

			// Silent upgrader skin to suppress output
			$skin = new \WP_Ajax_Upgrader_Skin();
			$upgrader = new Theme_Upgrader($skin);
			$result = $upgrader->upgrade($theme_slug);

			// Get new version after update
			wp_clean_themes_cache();
			$theme_new = wp_get_theme($theme_slug);
			$new_version = $theme_new->exists() ? $theme_new->get('Version') : '';

			if (is_wp_error($result)) {
				wp_send_json_error([
					'error_message' => $result->get_error_message(),
					'theme_slug' => $theme_slug,
					'theme_name' => $theme_name,
					'old_version' => $old_version,
				]);
			} elseif ($result === false) {
				wp_send_json_error([
					'error_message' => __('Update failed.', 'ultimate-security'),
					'theme_slug' => $theme_slug,
					'theme_name' => $theme_name,
					'old_version' => $old_version,
				]);
			} else {
				wp_send_json_success([
					'success_message' => __('Theme updated successfully.', 'ultimate-security'),
					'theme_slug' => $theme_slug,
					'theme_name' => $theme_name,
					'old_version' => $old_version,
					'new_version' => $new_version,
				]);
			}
		} else {
			wp_send_json_error(array('error_message' => esc_html__('Nonce verification failed. Please try again.', 'ultimate-security')));
		}
		wp_die();
	}

	/**
	 * Handle update completion - send notification if enabled and track timestamps
	 *
	 * @param \WP_Upgrader $upgrader The upgrader instance.
	 * @param array $hook_extra Extra info about the update.
	 */
	public static function ultimate_security_handle_update_complete($upgrader, $hook_extra)
	{
		// Track last update timestamps
		self::ultimate_security_track_update_timestamp($hook_extra);

		$options = self::$options;

		// Check if email notifications are enabled
		$email_notifications = isset($options['security']['updates']['email_notifications'])
			? sanitize_text_field($options['security']['updates']['email_notifications'])
			: '0';

		if ($email_notifications !== '1') {
			return;
		}

		// Check if successful_update notification type is enabled
		$notification_type = isset($options['security']['updates']['notification_type'])
			? sanitize_text_field($options['security']['updates']['notification_type'])
			: '';

		$notification_type_codes = [];
		if ($notification_type) {
			$decoded = json_decode($notification_type);
			if (is_array($decoded)) {
				$notification_type_codes = array_column($decoded, 'code');
			}
		}

		// Get email address(es) - supports multiple comma-separated or JSON array
		$email_setting = isset($options['security']['updates']['email_address'])
			? $options['security']['updates']['email_address']
			: get_option('admin_email');

		// Parse emails - could be JSON array, comma-separated, or single email
		$emails = [];
		if (is_string($email_setting)) {
			// Try to decode as JSON first
			$decoded = json_decode($email_setting);
			if (is_array($decoded)) {
				foreach ($decoded as $item) {
					if (is_object($item) && isset($item->value)) {
						$emails[] = sanitize_email($item->value);
					} elseif (is_string($item)) {
						$emails[] = sanitize_email($item);
					}
				}
			} else {
				// Treat as comma-separated or single email
				$email_list = explode(',', $email_setting);
				foreach ($email_list as $e) {
					$emails[] = sanitize_email(trim($e));
				}
			}
		}

		$emails = array_filter($emails); // Remove empty values
		if (empty($emails)) {
			$emails = [get_option('admin_email')];
		}

		// Check if we should send notifications for this type
		$send_successful = in_array('successful_update', $notification_type_codes);
		$send_failed = in_array('failed_update', $notification_type_codes);

		if (!$send_successful && !$send_failed) {
			return;
		}

		// Determine what was updated
		$update_type = isset($hook_extra['type']) ? $hook_extra['type'] : '';
		$action = isset($hook_extra['action']) ? $hook_extra['action'] : '';

		if ($action !== 'update') {
			return;
		}

		$updated_items = [];

		if ($update_type === 'plugin') {
			// Get plugin details
			$plugins = isset($hook_extra['plugins']) ? $hook_extra['plugins'] : [];
			if (isset($hook_extra['plugin'])) {
				$plugins[] = $hook_extra['plugin'];
			}

			// Use cached plugins list (clear first since we just updated)
			Utils::clear_all_caches();
			$all_plugins = Utils::get_plugins_cached();

			foreach ($plugins as $plugin_file) {
				if (isset($all_plugins[$plugin_file])) {
					$updated_items[] = [
						'type' => 'plugin',
						'name' => $all_plugins[$plugin_file]['Name'],
						'version' => $all_plugins[$plugin_file]['Version'],
					];
				}
			}
		} elseif ($update_type === 'theme') {
			// Get theme details
			$themes = isset($hook_extra['themes']) ? $hook_extra['themes'] : [];
			if (isset($hook_extra['theme'])) {
				$themes[] = $hook_extra['theme'];
			}

			foreach ($themes as $theme_slug) {
				$theme = wp_get_theme($theme_slug);
				if ($theme->exists()) {
					$updated_items[] = [
						'type' => 'theme',
						'name' => $theme->get('Name'),
						'version' => $theme->get('Version'),
					];
				}
			}
		} elseif ($update_type === 'core') {
			$updated_items[] = [
				'type' => 'core',
				'name' => 'WordPress',
				'version' => get_bloginfo('version'),
			];
		}

		if (empty($updated_items)) {
			return;
		}

		// Store updates in transient for batching (in case multiple updates happen)
		$batch_key = 'ultimate_security_update_batch_' . date('Y-m-d-H');
		$existing_batch = get_transient($batch_key);
		if (!$existing_batch) {
			$existing_batch = [
				'successful' => [],
				'failed' => [],
			];
		}

		// Add items to appropriate bucket (for now, assume success - failures handled separately)
		$existing_batch['successful'] = array_merge($existing_batch['successful'], $updated_items);
		set_transient($batch_key, $existing_batch, HOUR_IN_SECONDS);

		// Schedule a single email to be sent (avoid multiple emails for batch updates)
		$schedule_args = [
			$batch_key,
			implode(',', $emails),
			$send_successful,
			$send_failed
		];

		if (!wp_next_scheduled('ultimate_security_send_update_success_email', $schedule_args)) {
			wp_schedule_single_event(time() + 60, 'ultimate_security_send_update_success_email', $schedule_args);
		}
	}

	/**
	 * Send update notification email (supports success and failed)
	 *
	 * @param string $batch_key The transient key for the batch.
	 * @param string $emails Comma-separated email addresses.
	 * @param bool $send_successful Whether to send for successful updates.
	 * @param bool $send_failed Whether to send for failed updates.
	 */
	public static function ultimate_security_send_update_success_email($batch_key, $emails, $send_successful = true, $send_failed = false)
	{
		$batch_data = get_transient($batch_key);

		if (empty($batch_data)) {
			return;
		}

		// Delete the transient
		delete_transient($batch_key);

		// Parse batch data - handle both old and new format
		$successful_items = [];
		$failed_items = [];

		if (isset($batch_data['successful'])) {
			$successful_items = $batch_data['successful'];
			$failed_items = isset($batch_data['failed']) ? $batch_data['failed'] : [];
		} else {
			// Old format - treat all as successful
			$successful_items = $batch_data;
		}

		$email_list = array_map('trim', explode(',', $emails));

		// Send successful update notification
		if ($send_successful && !empty($successful_items)) {
			$output = self::build_update_email_content($successful_items, 'success');
			foreach ($email_list as $email) {
				if (!empty($email) && is_email($email)) {
					add_filter('wp_mail_content_type', [self::class, 'set_html_content_type']);
					wp_mail(
						$email,
						esc_html__('WordPress Updates Completed Successfully', 'ultimate-security'),
						$output
					);
					remove_filter('wp_mail_content_type', [self::class, 'set_html_content_type']);
				}
			}
		}

		// Send failed update notification
		if ($send_failed && !empty($failed_items)) {
			$output = self::build_update_email_content($failed_items, 'failed');
			foreach ($email_list as $email) {
				if (!empty($email) && is_email($email)) {
					add_filter('wp_mail_content_type', [self::class, 'set_html_content_type']);
					wp_mail(
						$email,
						esc_html__('WordPress Updates Failed', 'ultimate-security'),
						$output
					);
					remove_filter('wp_mail_content_type', [self::class, 'set_html_content_type']);
				}
			}
		}
	}

	/**
	 * Build email content for update notifications
	 *
	 * @param array $items The items to include in the email.
	 * @param string $type 'success' or 'failed'.
	 * @return string HTML email content.
	 */
	private static function build_update_email_content($items, $type = 'success')
	{
		$output = '';
		$output .= __('Hello,', 'ultimate-security') . '<br><br>';

		if ($type === 'success') {
			$output .= __('The following items were successfully updated on your WordPress site:', 'ultimate-security') . '<br><br>';
		} else {
			$output .= '<strong style="color: #dc3545;">' . __('Warning: The following updates failed on your WordPress site:', 'ultimate-security') . '</strong><br><br>';
		}

		// Group by type
		$plugins = array_filter($items, function ($item) {
			return $item['type'] === 'plugin';
		});
		$themes = array_filter($items, function ($item) {
			return $item['type'] === 'theme';
		});
		$core = array_filter($items, function ($item) {
			return $item['type'] === 'core';
		});

		if (!empty($plugins)) {
			$output .= '<strong>' . __('Plugins:', 'ultimate-security') . '</strong><br>';
			foreach ($plugins as $plugin) {
				$output .= '- ' . esc_html($plugin['name']);
				if (isset($plugin['version'])) {
					$output .= ' (v' . esc_html($plugin['version']) . ')';
				}
				if ($type === 'failed' && isset($plugin['error'])) {
					$output .= ' - <span style="color: #dc3545;">' . esc_html($plugin['error']) . '</span>';
				}
				$output .= '<br>';
			}
			$output .= '<br>';
		}

		if (!empty($themes)) {
			$output .= '<strong>' . __('Themes:', 'ultimate-security') . '</strong><br>';
			foreach ($themes as $theme) {
				$output .= '- ' . esc_html($theme['name']);
				if (isset($theme['version'])) {
					$output .= ' (v' . esc_html($theme['version']) . ')';
				}
				if ($type === 'failed' && isset($theme['error'])) {
					$output .= ' - <span style="color: #dc3545;">' . esc_html($theme['error']) . '</span>';
				}
				$output .= '<br>';
			}
			$output .= '<br>';
		}

		if (!empty($core)) {
			$output .= '<strong>' . __('WordPress Core:', 'ultimate-security') . '</strong><br>';
			foreach ($core as $item) {
				$output .= '- ' . esc_html($item['name']);
				if (isset($item['version'])) {
					$output .= ' (v' . esc_html($item['version']) . ')';
				}
				if ($type === 'failed' && isset($item['error'])) {
					$output .= ' - <span style="color: #dc3545;">' . esc_html($item['error']) . '</span>';
				}
				$output .= '<br>';
			}
			$output .= '<br>';
		}

		$output .= __('Your site:', 'ultimate-security') . ' ' . get_home_url() . '<br><br>';
		$output .= __('This email was sent by Ultimate Security plugin.', 'ultimate-security');

		return $output;
	}

	/**
	 * Set HTML content type for emails
	 */
	public static function set_html_content_type()
	{
		return 'text/html';
	}

	/**
	 * Track last update timestamps for plugins and themes
	 *
	 * @param array $hook_extra Extra info about the update.
	 */
	public static function ultimate_security_track_update_timestamp($hook_extra)
	{
		$update_type = isset($hook_extra['type']) ? $hook_extra['type'] : '';
		$action = isset($hook_extra['action']) ? $hook_extra['action'] : '';

		if ($action !== 'update') {
			return;
		}

		$last_updated_times = get_option('ultimate_security_last_update_times', [
			'plugins' => [],
			'themes' => [],
			'core' => null
		]);

		$current_time = current_time('mysql');

		if ($update_type === 'plugin') {
			$plugins = isset($hook_extra['plugins']) ? $hook_extra['plugins'] : [];
			if (isset($hook_extra['plugin'])) {
				$plugins[] = $hook_extra['plugin'];
			}

			foreach ($plugins as $plugin_file) {
				$last_updated_times['plugins'][$plugin_file] = $current_time;
			}
		} elseif ($update_type === 'theme') {
			$themes = isset($hook_extra['themes']) ? $hook_extra['themes'] : [];
			if (isset($hook_extra['theme'])) {
				$themes[] = $hook_extra['theme'];
			}

			foreach ($themes as $theme_slug) {
				$last_updated_times['themes'][$theme_slug] = $current_time;
			}
		} elseif ($update_type === 'core') {
			$last_updated_times['core'] = $current_time;
		}

		update_option('ultimate_security_last_update_times', $last_updated_times);
	}

	// Apply settings
	public static function ultimate_security_apply_update_settings()
	{
		$options = self::$options;

		// Plugin updates //manual_updates, auto, disable
		if ($options['security']['updates']['plugin_updates'] === 'auto') {
			add_filter('auto_update_plugin', '__return_true');
		} elseif ($options['security']['updates']['plugin_updates'] === 'disable') {

			// remove_action('load-update-core.php', 'wp_update_plugins');
			// wp_clear_scheduled_hook('wp_update_plugins');
			// add_filter('auto_update_plugin', '__return_false');

			// // Hide "update available" notification in plugin list
			// add_filter('pre_site_transient_update_plugins', '__return_null');

			add_filter( 'auto_update_plugin', '__return_false' );
			add_filter( 'pre_site_transient_update_plugins', '__return_null' );
			// add_filter( 'auto_update_theme', '__return_false' );
			// add_filter( 'pre_site_transient_update_themes', '__return_null' );
		}
		// Theme updates
		if ($options['security']['updates']['theme_updates'] === 'auto') {
			add_filter('auto_update_theme', '__return_true');
		} elseif ($options['security']['updates']['theme_updates'] === 'disable') {

			remove_action('load-update-core.php', 'wp_update_themes');
			wp_clear_scheduled_hook('wp_update_themes');
			add_filter('auto_update_theme', '__return_false');

			// Hide "update available" notification in themes list
			add_filter('pre_site_transient_update_themes', '__return_null');
		}

		// Disable translation updates
		if ($options['security']['updates']['disable_translation_updates']) {
			add_filter('auto_update_translation', '__return_false');
		}

		// WordPress core updates
		$core_updates = $options['security']['updates']['core_updates'];
		if ($core_updates === 'disable') {
			add_filter('auto_update_core', '__return_false');
		} elseif ($core_updates === 'disable_auto') {
			add_filter('allow_minor_auto_core_updates', '__return_false');
			add_filter('allow_major_auto_core_updates', '__return_false');
		} elseif ($core_updates === 'minor') {
			add_filter('allow_minor_auto_core_updates', '__return_true');
		} elseif ($core_updates === 'major') {
			add_filter('allow_major_auto_core_updates', '__return_true');
		} elseif ($core_updates === 'development') {
			add_filter('allow_dev_auto_core_updates', '__return_true');
		}

		// Enable updates for VCS installations
		if ($options['security']['updates']['vcs_updates']) {
			add_filter('automatic_updates_is_vcs_checkout', '__return_false', 10, 2);
		}

		// Updates nags only for Admin
		if ($options['security']['updates']['admin_update_nags']) {
			add_filter('admin_init', function () {
				if (!current_user_can('manage_options')) {
					remove_action('admin_notices', 'update_nag', 3);
					remove_action('admin_notices', 'maintenance_nag', 10);
					remove_action('network_admin_notices', 'maintenance_nag', 10);
				}
			});
		}

		
	}

}
