<?php
/**
 * Main Plugin Class
 *
 * @package Post_Export_Import_With_Media
 * @since 1.1.0
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Main Plugin Class - Coordinates all plugin functionality
 */
class PEIWM_Main {

	/**
	 * Plugin instance
	 *
	 * @var PEIWM_Main|null
	 */
	private static $instance = null;

	/**
	 * Get plugin instance (Singleton pattern)
	 *
	 * @return PEIWM_Main
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor - Initialize plugin
	 */
	private function __construct() {
		$this->load_dependencies();
		$this->init_hooks();
		$this->init_global_post_protection();
	}

	/**
	 * Initialize global post protection to prevent null post warnings
	 */
	private function init_global_post_protection() {
		// Add early hook to protect against null post access
		add_action( 'init', array( $this, 'setup_global_post_protection' ), 1 );
		add_action( 'admin_init', array( $this, 'setup_admin_post_protection' ), 1 );
		
		// Add custom error handler for null post warnings
		add_action( 'plugins_loaded', array( $this, 'setup_error_suppression' ), 1 );
	}

	/**
	 * Helper function to check if Freemius is available (either from Free or Pro).
	 *
	 * @since 1.3.0
	 * @return object|null Freemius SDK object or null.
	 */
	public function is_pro_active() {
		$is_pro_installed = class_exists('PEIWM_Pro_Main') && $this->check_pro_plugin_exists();
		
		// Get the correct Freemius instance based on which plugin is handling it
		$freemius_instance = peiwm_get_freemius_instance();
		
		// If no Freemius instance available, return false
		if ( ! $freemius_instance ) {
			return false;
		}
		
		return $freemius_instance->can_use_premium_code__premium_only() && $is_pro_installed;
	}

	/**
	 * Helper function to check if Pro version is active.
	 *
	 * @since 1.3.0
	 * @return bool Whether Pro version is active.
	 */
	public function check_pro_plugin_exists() {
		// return is_plugin_active( 'post-export-import-with-media-pro/post-export-import-with-media-pro.php' );
		return file_exists( WP_PLUGIN_DIR . '/post-export-import-with-media-pro/post-export-import-with-media-pro.php' );
	}


	/**
	 * Setup error suppression for null post warnings
	 */
	public function setup_error_suppression() {
		// Only in admin context and for our plugin pages
		if ( is_admin() ) {
			// Set custom error handler to suppress null post warnings
			set_error_handler( array( $this, 'custom_error_handler' ), E_WARNING );
		}
	}

	/**
	 * Custom error handler to suppress null post property warnings
	 *
	 * @param int    $errno   Error number
	 * @param string $errstr  Error message
	 * @param string $errfile Error file
	 * @param int    $errline Error line
	 * @return bool True to suppress error, false to continue normal handling
	 */
	public function custom_error_handler( $errno, $errstr, $errfile, $errline ) {
		// Check if this is a null post property warning
		if ( $errno === E_WARNING && 
			 ( strpos( $errstr, 'Attempt to read property "post_status" on null' ) !== false ||
			   strpos( $errstr, 'Attempt to read property "ID" on null' ) !== false ||
			   strpos( $errstr, 'Attempt to read property' ) !== false && strpos( $errstr, 'on null' ) !== false ) ) {
			
			// Suppress these specific warnings
			return true;
		}
		
		// Let other errors be handled normally
		return false;
	}

	/**
	 * Setup global post protection
	 */
	public function setup_global_post_protection() {
		// Ensure global post is never null in admin context
		if ( is_admin() ) {
			add_action( 'wp_loaded', array( $this, 'ensure_valid_global_post' ), 1 );
			add_action( 'admin_head', array( $this, 'ensure_valid_global_post' ), 1 );
		}
	}

	/**
	 * Setup admin-specific post protection
	 */
	public function setup_admin_post_protection() {
		// Protect against null post in admin context
		add_action( 'current_screen', array( $this, 'ensure_valid_global_post' ), 1 );
		add_action( 'admin_enqueue_scripts', array( $this, 'ensure_valid_global_post' ), 1 );
	}

	/**
	 * Ensure global post is never null to prevent warnings
	 */
	public function ensure_valid_global_post() {
		global $post;
		
		// If post is null, create a minimal valid post object
		if ( null === $post ) {
			$post = new stdClass();
			$post->ID = 0;
			$post->post_status = 'publish';
			$post->post_type = 'post';
			$post->post_title = '';
			$post->post_content = '';
			$post->post_excerpt = '';
			$post->post_author = 0;
			$post->post_date = current_time( 'mysql' );
			$post->post_modified = current_time( 'mysql' );
			$post->post_name = '';
			$post->post_parent = 0;
			$post->menu_order = 0;
			$post->comment_status = 'closed';
			$post->ping_status = 'closed';
			$post->comment_count = 0;
		}
	}

	/**
	 * Load plugin dependencies
	 */
	private function load_dependencies() {
		// Load core classes
		require_once PEIWM_PLUGIN_PATH . 'includes/class-admin-menu.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-ajax-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-post-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-page-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-media-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-settings-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-themes-plugins-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-widgets-menus-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-admin-download-buttons.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-batch-settings.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-batch-processor.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-heartbeat-handler.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-scheduled-exports.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-generic-recommendations.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-cpt-acf-exporter.php';
		require_once PEIWM_PLUGIN_PATH . 'includes/class-user-handler.php';
	}

	/**
	 * Initialize WordPress hooks
	 */
	private function init_hooks() {
		// Initialize components
		add_action( 'init', array( $this, 'init_components' ) );
		
		// Cleanup hooks
		add_action( 'wp_scheduled_delete', array( $this, 'cleanup_temp_files' ) );
		
		// Admin init
		add_action( 'admin_init', array( $this, 'admin_init' ) );
		
		// Register settings
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		
		// Fix wp-editor script conflict
		add_action( 'admin_enqueue_scripts', array( $this, 'fix_script_conflicts' ), 1 );
	}

	/**
	 * Initialize plugin components
	 */
	public function init_components() {
		// Initialize admin menu
		PEIWM_Admin_Menu::get_instance();
		
		// Initialize AJAX handler
		PEIWM_Ajax_Handler::get_instance();
		
		// Initialize post handler
		PEIWM_Post_Handler::get_instance();
		
		// Initialize page handler
		PEIWM_Page_Handler::get_instance();
		
		// Initialize media handler
		PEIWM_Media_Handler::get_instance();
		
		// Initialize settings handler
		PEIWM_Settings_Handler::get_instance();
		
		// Initialize themes & plugins handler
		PEIWM_Themes_Plugins_Handler::get_instance();
		
		// Initialize widgets & menus handler
		PEIWM_Widgets_Menus_Handler::get_instance();
		
		// Initialize admin download buttons
		PEIWM_Admin_Download_Buttons::get_instance();
		
		// Initialize batch settings
		PEIWM_Scheduled_Exports::get_instance();
		
		// Initialize batch settings
		PEIWM_Batch_Settings::get_instance();
		
		// Initialize batch processor
		PEIWM_Batch_Processor::get_instance();
		
		// Initialize heartbeat handler
		PEIWM_Heartbeat_Handler::get_instance();

		// Initialize CPT & ACF Exporter
		if ( $this->is_pro_active() ) {
			PEIM_CPT_ACF_Exporter::get_instance()->init();
		}

		// Initialize user handler
		PEIWM_User_Handler::get_instance();
		
		// Initialize recommendations
		if ( class_exists( 'Recommendations' ) ) {
			new Recommendations();
		}
	}

	/**
	 * Initialize admin settings
	 */
	public function admin_init() {
		$this->add_capabilities();
	}

	/**
	 * Add custom capabilities
	 */
	private function add_capabilities() {
		$role = get_role( 'administrator' );
		if ( $role && ! $role->has_cap( 'peiwm_manage' ) ) {
			$role->add_cap( 'peiwm_manage' );
		}
	}

	/**
	 * Fix script conflicts
	 *
	 * @param string $hook Current admin page hook
	 */
	public function fix_script_conflicts( $hook ) {
		// Prevent wp-editor script conflict on widgets page
		if ( in_array( $hook, array( 'widgets.php', 'customize.php' ), true ) ) {
			wp_dequeue_script( 'wp-editor' );
		}
	}

	/**
	 * Register plugin settings
	 */
	public function register_settings() {
		register_setting( 'peiwm_admin_download_buttons', 'peiwm_enable_admin_download_buttons' );

		register_setting(
			'peiwm_settings',
			'peiwm_user_import_default_password',
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
				'default'           => '',
			)
		);

		register_setting(
			'peiwm_settings',
			'peiwm_user_import_send_email',
			array(
				'type'              => 'boolean',
				'sanitize_callback' => 'rest_sanitize_boolean',
				'default'           => false,
			)
		);
	}

	/**
	 * Cleanup temporary files
	 */
	public function cleanup_temp_files() {
		$upload_dir = wp_upload_dir();
		$temp_dir = $upload_dir['basedir'] . '/peiwm-temp/';
		
		if ( is_dir( $temp_dir ) ) {
			$files = glob( $temp_dir . '*' );
			$now = time();
			
			foreach ( $files as $file ) {
				if ( is_file( $file ) && ( $now - filemtime( $file ) ) > 3600 ) { // 1 hour
					wp_delete_file( $file );
				}
			}
		}
	}
}