<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Core;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Database\Database_Manager;
use Wisewand\Database\Database_Version;
use Wisewand\Database\Database_Upgrader;
use Wisewand\Admin\Traits\AJAX_Security;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- error_log() is only used within WP_DEBUG conditionals for debugging; direct database calls and schema changes required for database version migrations and custom plugin table operations

class Plugin {

	use AJAX_Security;

	private static $instance = null;
	private $initialized     = false;

	// Lazy-loaded components
	private $rest_controller  = null;
	private $security_manager = null;
	private $content_manager  = null;
	private $seo_manager      = null;
	private $wpml_manager     = null;
	private $admin_manager    = null;
	private $media_manager    = null;
	private $logger           = null;
	private $options          = null;
	private $rss_cron                = null;
	private $cron_scheduler          = null;
	private $widget_editor_support   = null;

	// Migration components (v2.8.0)
	private $brief_client        = null;
	private $migration_validator = null;
	private $migration_executor  = null;

	// Database health (v2.8.2)
	private $db_health_checker = null;

	public static function instance() {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		// Don't initialize everything immediately
		// Wait for WordPress to be ready
		add_action( 'init', array( $this, 'init_plugin' ), 10 );
	}

	public function init_plugin() {
		if ( $this->initialized ) {
			return;
		}

		try {
			// Instantiate before logger exists — checker handles null logger internally.
			$this->db_health_checker = new Database_Health_Checker();
			$this->db_health_checker->check_database_version();
			$this->init_components();

			// v2.8.2: CRON scheduling delegated to CRON_Scheduler
			// Register cron_schedules filter BEFORE ensure_cron_scheduled() so custom
			// schedules (every_5_minutes, etc.) are available when scheduling.
			$this->cron_scheduler = new \Wisewand\Core\CRON_Scheduler( $this->options, $this->logger );
			$this->cron_scheduler->set_admin_manager( $this->admin_manager );
			add_filter( 'cron_schedules', array( $this->cron_scheduler, 'add_cron_schedules' ) );
			$this->cron_scheduler->ensure_cron_scheduled();
			$hook_registry = new \Wisewand\Core\Hook_Registry(
				$this,
				$this->admin_manager,
				$this->security_manager,
				$this->rest_controller,
				$this->content_manager,
				$this->migration_validator,
				$this->migration_executor,
				$this->options,
				$this->logger,
				$this->widget_editor_support,
				$this->cron_scheduler
			);
			$hook_registry->init_hooks();
			$this->initialized = true;
		} catch ( Exception $e ) {
			if ( WP_DEBUG ) {
				error_log( 'Wisewand Plugin Init Error: ' . $e->getMessage() );
			}
		}
	}

	private function init_components() {
		// Initialize utilities first - these should always work
		$this->init_options();
		$this->init_logger();

		// v2.8.0: Initialize migration components (brief client, validator, executor)
		$this->init_brief_client();
		$this->init_migration_validator();
		$this->init_migration_executor();

		// Initialize other components only if their dependencies exist
		$this->init_security_manager();
		$this->init_media_manager();
		$this->init_admin_manager();

		// These depend on the above components
		$this->init_content_manager();
		$this->init_seo_manager();
		$this->init_wpml_manager();
		$this->init_rest_controller();

		// Widget editor support (self-contained, no dependencies)
		$this->init_widget_editor_support();
	}

	private function init_options() {
		if ( ! class_exists( 'Wisewand\\Utils\\Options' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Options.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Utils\\Options' ) ) {
			$this->options = new \Wisewand\Utils\Options();
		}
	}

	private function init_logger() {
		if ( ! class_exists( 'Wisewand\\Logging\\Logger' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Logging/Logger.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Logging\\Logger' ) ) {
			$this->logger = new \Wisewand\Logging\Logger();
		}
	}

	/**
	 * Initialize Project Brief Client (v2.8.0)
	 *
	 * @since 2.8.0
	 */
	private function init_brief_client() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\API\\Project_Brief_Client' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/API/Project_Brief_Client.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\API\\Project_Brief_Client' ) ) {
			$this->brief_client = new \Wisewand\API\Project_Brief_Client( $this->options, $this->logger );
		}
	}

	/**
	 * Initialize Migration Validator (v2.8.0)
	 *
	 * @since 2.8.0
	 */
	private function init_migration_validator() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Migration\\Migration_Validator' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Migration/Migration_Validator.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Migration\\Migration_Validator' ) ) {
			$this->migration_validator = new \Wisewand\Migration\Migration_Validator( $this->options, $this->logger );
		}
	}

	/**
	 * Initialize Migration Executor (v2.8.0)
	 *
	 * @since 2.8.0
	 */
	private function init_migration_executor() {
		if ( ! $this->options || ! $this->logger || ! $this->migration_validator ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Migration\\Migration_Executor' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Migration/Migration_Executor.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Migration\\Migration_Executor' ) ) {
			$this->migration_executor = new \Wisewand\Migration\Migration_Executor( $this->options, $this->logger, $this->migration_validator );
		}
	}

	private function init_security_manager() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Security\\Security_Manager' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Security/Security_Manager.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Security\\Security_Manager' ) ) {
			$this->security_manager = new \Wisewand\Security\Security_Manager( $this->options, $this->logger );
		}
	}

	private function init_media_manager() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Media\\Media_Manager' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Media/Media_Manager.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Media\\Media_Manager' ) ) {
			$this->media_manager = new \Wisewand\Media\Media_Manager( $this->options, $this->logger );
		}
	}

	private function init_admin_manager() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		// Load API Client first since admin pages depend on it
		$api_client_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
		if ( file_exists( $api_client_file ) ) {
			require_once $api_client_file;
		}

		// Load admin sub-pages
		$admin_files = array(
			'includes/Admin/Admin_Manager.php',
			'includes/Admin/Wisewand_Articles_Page.php',
			'includes/Admin/Wisewand_API_Settings_Page.php',
			'includes/Admin/Wisewand_Projects_Page.php',
			'includes/Admin/Wisewand_RSS_Page.php',
			'includes/Admin/Dashboard_Page.php',
			'includes/Admin/Editorial_Calendar.php',
			'includes/Admin/SEO_Intelligence_Real.php',
		);

		// Load RSS classes
		$rss_files = array(
			'includes/RSS/RSS_Feed_Manager.php',
			'includes/RSS/RSS_Article_Manager.php',
			'includes/RSS/RSS_Sync_Engine.php',
			'includes/RSS/RSS_CRON.php',
		);

		foreach ( $admin_files as $file ) {
			$full_path = WISEWAND_PLUGIN_DIR . $file;
			if ( file_exists( $full_path ) ) {
				require_once $full_path;
			}
		}

		foreach ( $rss_files as $file ) {
			$full_path = WISEWAND_PLUGIN_DIR . $file;
			if ( file_exists( $full_path ) ) {
				require_once $full_path;
			}
		}

		if ( class_exists( 'Wisewand\\Admin\\Admin_Manager' ) ) {
			$this->admin_manager = new \Wisewand\Admin\Admin_Manager( $this->options, $this->logger );
		}
	}

	private function init_content_manager() {
		if ( ! $this->options || ! $this->logger || ! $this->media_manager ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Content\\Content_Manager' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Content/Content_Manager.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Content\\Content_Manager' ) ) {
			$this->content_manager = new \Wisewand\Content\Content_Manager( $this->options, $this->logger, $this->media_manager );
		}
	}

	private function init_seo_manager() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\SEO\\SEO_Manager' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/SEO/SEO_Manager.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\SEO\\SEO_Manager' ) ) {
			$this->seo_manager = new \Wisewand\SEO\SEO_Manager( $this->options, $this->logger );
		}
	}

	private function init_wpml_manager() {
		if ( ! $this->options || ! $this->logger ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\WPML\\WPML_Manager' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/WPML/WPML_Manager.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\WPML\\WPML_Manager' ) ) {
			$this->wpml_manager = new \Wisewand\WPML\WPML_Manager( $this->options, $this->logger );
		}
	}

	private function init_rest_controller() {
		if ( ! $this->security_manager || ! $this->content_manager || ! $this->logger || ! $this->options ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\API\\REST_Controller' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/API/REST_Controller.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\API\\REST_Controller' ) ) {
			$this->rest_controller = new \Wisewand\API\REST_Controller(
				$this->security_manager,
				$this->content_manager,
				$this->logger,
				$this->options
			);
		}
	}

	/**
	 * Initialize Widget Editor Support (v2.8.0)
	 *
	 * Provides Alpine.js widget preservation, KSES whitelisting, and
	 * Classic Editor forcing for posts with widgets.
	 *
	 * @since 2.8.0
	 */
	private function init_widget_editor_support() {
		if ( ! class_exists( 'Wisewand\\Editor\\Widget_Editor_Support' ) ) {
			$file = WISEWAND_PLUGIN_DIR . 'includes/Editor/Widget_Editor_Support.php';
			if ( file_exists( $file ) ) {
				require_once $file;
			}
		}

		if ( class_exists( 'Wisewand\\Editor\\Widget_Editor_Support' ) ) {
			$this->widget_editor_support = new \Wisewand\Editor\Widget_Editor_Support();
		}
	}

	public function check_plugin_updates() {
		$current_version = get_option( 'wisewand_plugin_version', '0.0.0' );

		if ( version_compare( $current_version, WISEWAND_PLUGIN_VERSION, '<' ) ) {
			// Delegate upgrade routines to Database_Health_Checker.
			$this->db_health_checker->upgrade_plugin( $current_version );
			update_option( 'wisewand_plugin_version', WISEWAND_PLUGIN_VERSION );
		}
	}

	/**
	 * Delegate database health check to Database_Health_Checker.
	 *
	 * Hooked to admin_init (priority 5) via Hook_Registry. Forwards to the
	 * dedicated checker so Plugin.php remains a thin bootstrap controller.
	 *
	 * @since 2.8.2
	 */
	public function check_database_health() {
		if ( $this->db_health_checker ) {
			$this->db_health_checker->check_database_health();
		}
	}

	// Safe getters that check if components exist
	public function get_rest_controller() {
		return $this->rest_controller;
	}

	public function get_security_manager() {
		return $this->security_manager;
	}

	public function get_content_manager() {
		return $this->content_manager;
	}

	public function get_seo_manager() {
		return $this->seo_manager;
	}

	public function get_wpml_manager() {
		return $this->wpml_manager;
	}

	public function get_admin_manager() {
		return $this->admin_manager;
	}

	public function get_media_manager() {
		return $this->media_manager;
	}

	public function get_logger() {
		return $this->logger;
	}

	public function get_options() {
		return $this->options;
	}

	public function is_initialized() {
		return $this->initialized;
	}

	/**
	 * Show activation notice instead of forcing redirect
	 * WordPress.org compliant - no dashboard hijacking
	 */
	public function handle_activation_redirect() {
		// Check if we should show the activation notice
		if ( ! get_transient( 'wisewand_activation_redirect' ) ) {
			return;
		}

		// Delete the redirect transient
		delete_transient( 'wisewand_activation_redirect' );

		// Set a flag to show the admin notice instead
		set_transient( 'wisewand_show_activation_notice', true, 300 ); // 5 minutes
	}

	/**
	 * Display activation notice with link to settings
	 */
	public function show_activation_notice() {
		// Only show if the transient is set
		if ( ! get_transient( 'wisewand_show_activation_notice' ) ) {
			return;
		}

		// Check if user dismissed the notice
		$user_id = get_current_user_id();
		if ( get_user_meta( $user_id, 'wisewand_activation_notice_dismissed', true ) ) {
			delete_transient( 'wisewand_show_activation_notice' );
			return;
		}

		// Enqueue inline script for notice dismissal
		$this->enqueue_activation_notice_script();

		$settings_url = admin_url( 'admin.php?page=wisewand-settings' );
		?>
		<div class="notice notice-success is-dismissible" data-dismissible="wisewand-activation-notice">
			<p>
				<strong><?php esc_html_e( 'Wisewand Activated!', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong><br>
				<?php
				printf(
					/* translators: %s: Link to settings page */
					esc_html__( 'Thank you for installing Wisewand. Get started by %s to configure your API keys and preferences.', 'wisewand-ai-content-writer-seo-content-generator' ),
					'<a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'visiting the settings page', 'wisewand-ai-content-writer-seo-content-generator' ) . '</a>'
				);
				?>
			</p>
		</div>
		<?php
	}

	/**
	 * Enqueue inline script for activation notice dismissal
	 */
	private function enqueue_activation_notice_script() {
		// Ensure jQuery is loaded (it's a default WP admin script)
		wp_enqueue_script( 'jquery' );

		$nonce = wp_create_nonce( 'wisewand_dismiss_notice' );

		// Add inline script for notice dismissal
		$script = "
		jQuery(document).ready(function($) {
			$(document).on('click', '.notice[data-dismissible=\"wisewand-activation-notice\"] .notice-dismiss', function() {
				$.post(ajaxurl, {
					action: 'wisewand_dismiss_activation_notice',
					nonce: '" . esc_js( $nonce ) . "'
				});
			});
		});
		";

		wp_add_inline_script( 'jquery', $script );
	}

	/**
	 * Handle AJAX request to dismiss activation notice
	 */
	public function dismiss_activation_notice() {
		check_ajax_referer( 'wisewand_dismiss_notice', 'nonce' );

		$user_id = get_current_user_id();
		update_user_meta( $user_id, 'wisewand_activation_notice_dismissed', true );
		delete_transient( 'wisewand_show_activation_notice' );

		wp_send_json_success();
	}

	/**
	 * AJAX Handler - Manual CRON trigger (for dashboard refresh button)
	 * Runs status check immediately when user clicks refresh
	 */
	public function ajax_manual_cron_trigger() {
		$this->verify_ajax_request( 'wisewand_dashboard' );

		$this->logger->info( 'Manual CRON trigger via dashboard refresh button' );

		try {
			// Run status check CRON immediately
			$this->run_status_check_cron();

			wp_send_json_success(
				array(
					'message'   => esc_html__( 'Status check completed', 'wisewand-ai-content-writer-seo-content-generator' ),
					'timestamp' => current_time( 'mysql' ),
				)
			);

		} catch ( \Exception $e ) {
			$this->logger->error( 'Manual CRON trigger failed', array( 'error' => $e->getMessage() ) );
			wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
		}
	}

	/**
	 * AJAX Handler - Manual full CRON trigger (for dashboard button)
	 * Runs complete CRON with logging
	 */
	public function ajax_manual_full_cron_trigger() {
		$this->verify_ajax_request( 'wisewand_dashboard', 'manage_options' );

		$this->logger->info( 'Manual full CRON trigger via dashboard button' );

		try {
			// Capture logs during execution
			$logs = array();

			// Run full daily CRON
			$this->run_editorial_calendar_cron();

			// Get summary from option
			$summary_json = get_option( 'wisewand_cron_last_summary', '{}' );
			$summary      = json_decode( $summary_json, true );

			wp_send_json_success(
				array(
					'message'   => esc_html__( 'CRON completed successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
					'summary'   => $summary,
					'timestamp' => current_time( 'mysql' ),
					'logs'      => $logs,
				)
			);

		} catch ( \Exception $e ) {
		$this->logger->error( 'Manual full CRON trigger failed', array( 'error' => $e->getMessage() ) );
		wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
	}
}

/**
 * AJAX Handler - Manual RSS sync trigger
 * Runs RSS sync immediately
 */
public function ajax_manual_rss_trigger() {
	$this->verify_ajax_request( 'wisewand_dashboard', 'manage_options' );

	$this->logger->info( 'Manual RSS sync trigger via dashboard button' );

	try {
		// Run RSS sync
		$this->run_rss_sync_cron();

		wp_send_json_success(
			array(
				'message'   => esc_html__( 'RSS Sync completed successfully', 'wisewand-ai-content-writer-seo-content-generator' ),
				'timestamp' => current_time( 'mysql' ),
			)
		);

	} catch ( \Exception $e ) {
		$this->logger->error( 'Manual RSS sync trigger failed', array( 'error' => $e->getMessage() ) );
		wp_send_json_error( array( 'message' => esc_html( $e->getMessage() ) ) );
	}
}
	/**
	 * Run status check CRON (every 15 minutes)
	 * Lightweight operation - only checks if generating articles are ready
	 */
	public function run_status_check_cron() {
		if ( ! $this->content_manager ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Automation\\Calendar_CRON' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Automation/Calendar_CRON.php';
		}

		$calendar_cron = new \Wisewand\Automation\Calendar_CRON(
			$this->options,
			$this->logger,
			$this->content_manager
		);

		// Only run status check (lightweight, fast)
		$calendar_cron->run_status_check_only();
	}

	/**
	 * Import a single ready content entry (webhook-triggered)
	 *
	 * @param int $entry_id Calendar entry ID to import
	 */
	public function run_import_ready_content( $entry_id ) {
		if ( ! $this->content_manager ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Automation\\Calendar_CRON' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Automation/Calendar_CRON.php';
		}

		if ( ! class_exists( 'Wisewand\\Calendar\\Calendar_Entry_Manager' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Calendar/Calendar_Entry_Manager.php';
		}

		$calendar_cron = new \Wisewand\Automation\Calendar_CRON(
			$this->options,
			$this->logger,
			$this->content_manager
		);

		// Get the entry
		$payload_builder = new \Wisewand\Utils\Wisewand_Payload_Builder( $this->options, $this->logger );
		$entry_manager   = new \Wisewand\Calendar\Calendar_Entry_Manager( $this->options, $this->logger, $payload_builder );

		$entry = $entry_manager->get_entry( $entry_id );
		if ( is_wp_error( $entry ) ) {
			if ( $this->logger ) {
				$this->logger->error(
					'Failed to import ready content - entry not found',
					array(
						'entry_id' => $entry_id,
						'error'    => $entry->get_error_message(),
					)
				);
			}
			return;
		}

		// Import the entry using the private method via reflection
		$reflection = new \ReflectionClass( $calendar_cron );
		$method     = $reflection->getMethod( 'import_and_publish_entry' );
		$method->setAccessible( true );
		$result = $method->invoke( $calendar_cron, $entry );

		if ( is_wp_error( $result ) ) {
			if ( $this->logger ) {
				$this->logger->error(
					'Webhook-triggered import failed',
					array(
						'entry_id' => $entry_id,
						'error'    => $result->get_error_message(),
					)
				);
			}
		} elseif ( $this->logger ) {
				$this->logger->info(
					'Webhook-triggered import successful',
					array(
						'entry_id' => $entry_id,
						'post_id'  => $result,
					)
				);
		}
	}

	/**
	 * Run full editorial calendar CRON (daily at 2 AM)
	 * Heavy operations - generate, import, retry
	 */
	public function run_editorial_calendar_cron() {
		if ( ! $this->content_manager ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\Automation\\Calendar_CRON' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Automation/Calendar_CRON.php';
		}

		$calendar_cron = new \Wisewand\Automation\Calendar_CRON(
			$this->options,
			$this->logger,
			$this->content_manager
		);

		// Run full daily operations (pass force_retry = true for manual trigger)
		$calendar_cron->run( true ); // ✅ Force retry when manually triggered!
	}

	/**
	 * Run RSS feeds sync CRON (hourly)
	 * Checks feeds and imports new articles automatically
	 */
	public function run_rss_sync_cron() {
		if ( ! $this->content_manager ) {
			return;
		}

		if ( ! class_exists( 'Wisewand\\RSS\\RSS_CRON' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/RSS/RSS_CRON.php';
		}

		if ( ! class_exists( 'Wisewand\\Calendar\\Calendar_Entry_Manager' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Calendar/Calendar_Entry_Manager.php';
		}

		// Initialize Calendar Entry Manager (required by RSS_CRON)
		$payload_builder  = new \Wisewand\Utils\Wisewand_Payload_Builder( $this->options, $this->logger );
		$calendar_manager = new \Wisewand\Calendar\Calendar_Entry_Manager( $this->options, $this->logger, $payload_builder );

		$this->rss_cron = new \Wisewand\RSS\RSS_CRON(
			$this->options,
			$this->logger,
			$this->content_manager,
			$calendar_manager
		);

		// Run RSS sync
		$this->rss_cron->run();
	}

	/**
	 * Sync WordPress publish status to Wisewand API
	 * Triggered when post status changes (publish, unpublish, quick edit, bulk edit)
	 * Implements bidirectional sync between WordPress and Wisewand
	 *
	 * @param string  $new_status New post status
	 * @param string  $old_status Old post status
	 * @param WP_Post $post Post object
	 */
	public function sync_publish_status_to_wisewand( $new_status, $old_status, $post ) {
		// Only process when status changes TO or FROM 'publish'
		if ( $new_status === $old_status ) {
			return; // No status change
		}

		if ( $new_status !== 'publish' && $old_status !== 'publish' ) {
			return; // Neither publishing nor unpublishing
		}

		// Only process posts that came from Wisewand
		$wisewand_article_id = get_post_meta( $post->ID, '_wisewand_external_id', true );
		if ( empty( $wisewand_article_id ) ) {
			return; // Not a Wisewand article - skip
		}

		// Determine publish status
		$is_published = ( $new_status === 'publish' );
		$action       = $is_published ? 'published' : 'unpublished';

		if ( WP_DEBUG ) {
			error_log( 'WISEWAND_SYNC: Post #' . $post->ID . ' ' . $action . ' manually, syncing to Wisewand article ' . $wisewand_article_id );
			error_log( 'WISEWAND_SYNC: Status change: ' . $old_status . ' → ' . $new_status );
		}

		// Send PATCH request to Wisewand API
		if ( ! class_exists( 'Wisewand\\Utils\\Wisewand_API_Client' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Wisewand_API_Client.php';
		}

		if ( ! $this->options ) {
			if ( WP_DEBUG ) {
				error_log( 'WISEWAND_SYNC: Options not available, skipping sync' );
			}
			return;
		}

		try {
			$api_client = new \Wisewand\Utils\Wisewand_API_Client(
				$this->options->get( 'wisewand_api_key' ),
				$this->logger
			);
			$result     = $api_client->update_article(
				$wisewand_article_id,
				array(
					'is_published' => $is_published,
				)
			);

			if ( is_wp_error( $result ) ) {
				if ( $this->logger ) {
					$this->logger->warning(
						'Failed to sync is_published to Wisewand',
						array(
							'post_id'      => $post->ID,
							'article_id'   => $wisewand_article_id,
							'is_published' => $is_published,
							'error'        => $result->get_error_message(),
						)
					);
				}
				if ( WP_DEBUG ) {
					error_log( 'WISEWAND_SYNC: PATCH failed - ' . $result->get_error_message() );
				}
				return; // Soft fail - don't block WordPress publishing
			}

			if ( $this->logger ) {
				$this->logger->info(
					'Synced publish status to Wisewand',
					array(
						'post_id'      => $post->ID,
						'article_id'   => $wisewand_article_id,
						'is_published' => $is_published,
						'action'       => $action,
					)
				);
			}

			if ( WP_DEBUG ) {
				error_log( 'WISEWAND_SYNC: ✅ Successfully updated Wisewand article ' . $wisewand_article_id . ' is_published = ' . ( $is_published ? 'true' : 'false' ) );
			}

			// Also update calendar entry if exists (keeps calendar accurate)
			global $wpdb;
			$calendar_table = $wpdb->prefix . 'wisewand_editorial_calendar';

			if ( $is_published ) {
				// Publishing: Update imported_draft OR imported_scheduled → imported_published
				// Handle both draft and scheduled posts (scheduled posts auto-publish via WP cron)
				$updated = $wpdb->query(
					$wpdb->prepare(
						"UPDATE %i SET wordpress_status = %s
						WHERE wordpress_post_id = %d
						AND wordpress_status IN ('imported_draft', 'imported_scheduled')",
						$calendar_table,
						'imported_published',
						$post->ID
					)
				);

				if ( $updated > 0 && WP_DEBUG ) {
					error_log( 'WISEWAND_SYNC: Updated calendar entry to imported_published (was imported_draft or imported_scheduled)' );
				}
			} else {
				// Unpublishing: Update imported_published → imported_draft
				$updated = $wpdb->query(
					$wpdb->prepare(
						"UPDATE %i SET wordpress_status = %s
						WHERE wordpress_post_id = %d
						AND wordpress_status = %s",
						$calendar_table,
						'imported_draft',
						$post->ID,
						'imported_published'
					)
				);

				if ( $updated > 0 && WP_DEBUG ) {
					error_log( 'WISEWAND_SYNC: Updated calendar entry from imported_published to imported_draft' );
				}
			}
		} catch ( \Exception $e ) {
			if ( $this->logger ) {
				$this->logger->error(
					'Exception syncing publish status to Wisewand',
					array(
						'post_id'    => $post->ID,
						'article_id' => $wisewand_article_id,
						'error'      => $e->getMessage(),
					)
				);
			}
			if ( WP_DEBUG ) {
				error_log( 'WISEWAND_SYNC: Exception - ' . $e->getMessage() );
			}
			// Soft fail - don't disrupt WordPress publishing
		}
	}

	/**
	 * Wrapper for Editorial Calendar CRON (Daily)
	 * Fixes: call_user_func_array callback error
	 */
	public function run_calendar_cron() {
		if ( ! class_exists( 'Wisewand\\Automation\\Calendar_CRON' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Automation/Calendar_CRON.php';
		}

		if ( $this->options && $this->logger && $this->content_manager ) {
			$cron = new \Wisewand\Automation\Calendar_CRON( $this->options, $this->logger, $this->content_manager );
			$cron->run();
		}
	}

	/**
	 * Wrapper for RSS Sync (Alias to match hook name)
	 */
	public function run_rss_sync() {
		$this->run_rss_sync_cron();
	}

	/**
	 * Run RSS Discovery Phase (v2.2.0)
	 * REMOVED in v2.3.0 - Simplified CRON system
	 *
	 * @since 2.2.0
	 * @deprecated 2.3.0 Use run_rss_sync() instead
	 */
	public function run_rss_discovery() {
		// v2.3.0: Redirect to unified sync method
		$this->run_rss_sync();
	}

	/**
	 * Run RSS Import Phase (v2.2.0)
	 * REMOVED in v2.3.0 - Simplified CRON system
	 *
	 * @since 2.2.0
	 * @deprecated 2.3.0 Use run_rss_sync() instead
	 */
	public function run_rss_import() {
		// v2.3.0: Redirect to unified sync method
		$this->run_rss_sync();
	}

	/**
	 * Display migration validation notice (v2.8.0)
	 *
	 * Shows non-dismissible notice if project brief validation fails.
	 * Blocks migration until user configures project brief properly.
	 *
	 * @since 2.8.0
	 */
	public function show_migration_validation_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( ! $this->migration_validator || ! $this->migration_validator->is_migration_needed() ) {
			return;
		}

		// Only reaches here if API key or project ID is missing.
		$status = $this->migration_validator->get_validation_status();

		if ( empty( $status['blocking_issues'] ) ) {
			return;
		}
		?>
		<div class="notice notice-warning is-dismissible">
			<p>
				<strong><?php esc_html_e( 'Wisewand: Complete your setup', 'wisewand-ai-content-writer-seo-content-generator' ); ?></strong>
			</p>
			<ul style="list-style: disc; margin-left: 20px;">
				<?php foreach ( $status['blocking_issues'] as $issue ) : ?>
					<li><?php echo wp_kses_post( $issue ); ?></li>
				<?php endforeach; ?>
			</ul>
			<p>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=wisewand-settings' ) ); ?>" class="button button-primary">
					<?php esc_html_e( 'Go to Settings', 'wisewand-ai-content-writer-seo-content-generator' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

}