<?php
/**
 * Plugin Name: Wisewand - AI Content Writer & SEO Content Generator
 * Plugin URI: https://wisewand.ai
 * Description: AI content generator and SEO writing assistant. Automate blog posts, editorial calendars, and content creation with AI-powered SEO optimization.
 * Version:           2.9.13
 * Author: Wisewand
 * Author URI: https://wisewand.ai
 * Text Domain: wisewand-ai-content-writer-seo-content-generator
 * Domain Path: /languages
 * Requires at least: 6.2
 * Tested up to: 6.8
 * Requires PHP: 8.0
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

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

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- error_log() is only used within WP_DEBUG conditionals for debugging

// Define plugin constants (with protection against redefinition)
if ( ! defined( 'WISEWAND_PLUGIN_VERSION' ) ) {
	define( 'WISEWAND_PLUGIN_VERSION', '2.9.13' );
}
if ( ! defined( 'WISEWAND_VERSION' ) ) {
	/**
	 * Current plugin version.
	 */
	define( 'WISEWAND_VERSION', '2.9.13' );
}
if ( ! defined( 'WISEWAND_PLUGIN_FILE' ) ) {
	define( 'WISEWAND_PLUGIN_FILE', __FILE__ );
}
if ( ! defined( 'WISEWAND_PLUGIN_DIR' ) ) {
	define( 'WISEWAND_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'WISEWAND_PLUGIN_URL' ) ) {
	define( 'WISEWAND_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'WISEWAND_PLUGIN_BASENAME' ) ) {
	define( 'WISEWAND_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
}

// Minimum requirements check
if ( ! function_exists( 'wisewand_check_requirements' ) ) {
	function wisewand_check_requirements() {
		$requirements_met = true;
		$errors           = array();

		// Check PHP version
		if ( version_compare( PHP_VERSION, '8.0', '<' ) ) {
			$requirements_met = false;
			$errors[]         = sprintf(
				'Wisewand requires PHP 8.0 or higher. You are running PHP %s.',
				PHP_VERSION
			);
		}

		// Check WordPress version
		global $wp_version;
		if ( version_compare( $wp_version, '6.0', '<' ) ) {
			$requirements_met = false;
			$errors[]         = sprintf(
				'Wisewand requires WordPress 6.0 or higher. You are running WordPress %s.',
				$wp_version
			);
		}

		// Check if REST API is available
		if ( ! class_exists( 'WP_REST_Server' ) ) {
			$requirements_met = false;
			$errors[]         = 'Wisewand-plugin requires WordPress REST API to be enabled.';
		}

		if ( ! $requirements_met ) {
			add_action(
				'admin_notices',
				function () use ( $errors ) {
					echo '<div class="notice notice-error"><p>';
					echo '<strong>Wisewand-plugin could not be activated:</strong><br>';
					foreach ( $errors as $error ) {
						echo '• ' . esc_html( $error ) . '<br>';
					}
					echo '</p></div>';
				}
			);

			// Deactivate plugin
			if ( function_exists( 'deactivate_plugins' ) ) {
				deactivate_plugins( plugin_basename( __FILE__ ) );
			}
			return false;
		}

		return true;
	}
}

// Simple autoloader function
if ( ! function_exists( 'wisewand_autoloader' ) ) {
	function wisewand_autoloader( $class_name ) {
		// Only load classes in our namespace
		if ( strpos( $class_name, 'Wisewand\\' ) !== 0 ) {
			return;
		}

		// Convert namespace to file path
		$class_path = str_replace( 'Wisewand\\', '', $class_name );
		$class_path = str_replace( '\\', DIRECTORY_SEPARATOR, $class_path );

		$file_path = WISEWAND_PLUGIN_DIR . 'includes' . DIRECTORY_SEPARATOR . $class_path . '.php';

		// Validate that the resolved path is within the plugin directory (prevent path traversal)
		$real_path  = realpath( $file_path );
		$plugin_dir = realpath( WISEWAND_PLUGIN_DIR );

		if ( $real_path && $plugin_dir && strpos( $real_path, $plugin_dir ) === 0 && file_exists( $real_path ) ) {
			require_once $real_path;
		}
	}
}

// Pre-load critical classes to avoid dependency issues
if ( ! function_exists( 'wisewand_preload_classes' ) ) {
	function wisewand_preload_classes() {
		$critical_classes = array(
			'includes/Utils/Options.php',
			'includes/Utils/Wisewand_API_Client.php',
			'includes/Utils/DataForSEO_Universal.php',
			'includes/Logging/Logger.php',
			'includes/Utils/Wisewand_Payload_Builder.php',
		);

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

// Register autoloader safely
if ( function_exists( 'spl_autoload_register' ) ) {
	spl_autoload_register( 'wisewand_autoloader' );
}

// Global variable to hold plugin instance
$GLOBALS['wisewand_plugin_instance'] = null;

// Initialize plugin function
if ( ! function_exists( 'wisewand_init_plugin' ) ) {
	function wisewand_init_plugin() {
		// Prevent multiple initializations
		if ( ! empty( $GLOBALS['wisewand_plugin_instance'] ) ) {
			return;
		}

		// Check requirements first
		if ( ! wisewand_check_requirements() ) {
			return;
		}

		// Pre-load critical classes
		wisewand_preload_classes();

		// Load plugin text domain for translations
		load_plugin_textdomain(
			'wisewand-ai-content-writer-seo-content-generator',
			false,
			dirname( plugin_basename( __FILE__ ) ) . '/languages'
		);

		// Try to initialize main plugin class safely
		try {
			if ( class_exists( 'Wisewand\\Core\\Plugin' ) ) {
				$GLOBALS['wisewand_plugin_instance'] = Wisewand\Core\Plugin::instance();
			} else {
				// Fallback: try to require the main class file manually
				$plugin_file = WISEWAND_PLUGIN_DIR . 'includes/Core/Plugin.php';
				if ( file_exists( $plugin_file ) ) {
					require_once $plugin_file;
					if ( class_exists( 'Wisewand\\Core\\Plugin' ) ) {
						$GLOBALS['wisewand_plugin_instance'] = Wisewand\Core\Plugin::instance();
					}
				}
			}
		} catch ( Exception $e ) {
			add_action(
				'admin_notices',
				function () use ( $e ) {
					echo '<div class="notice notice-error"><p>';
					echo '<strong>Wisewand Plugin Error:</strong> ' . esc_html( $e->getMessage() );
					echo '</p></div>';
				}
			);

			if ( WP_DEBUG ) {
				error_log( 'Wisewand Plugin Error: ' . $e->getMessage() );
				error_log( 'Wisewand Plugin Trace: ' . $e->getTraceAsString() );
			}
		}
	}
}

// Activation hook with safe error handling
if ( ! function_exists( 'wisewand_activate_plugin' ) ) {
	function wisewand_activate_plugin() {
		if ( ! wisewand_check_requirements() ) {
			return;
		}

		try {
			// Try to load and run activator
			$activator_file = WISEWAND_PLUGIN_DIR . 'includes/Core/Activator.php';
			if ( file_exists( $activator_file ) ) {
				require_once $activator_file;
				if ( class_exists( 'Wisewand\\Core\\Activator' ) ) {
					Wisewand\Core\Activator::activate();
				}
			}
		} catch ( Exception $e ) {
			if ( WP_DEBUG ) {
				error_log( 'Wisewand Activation Error: ' . $e->getMessage() );
			}
			// Don't prevent activation, just log the error
		}
	}
}

// Deactivation hook with safe error handling
if ( ! function_exists( 'wisewand_deactivate_plugin' ) ) {
	function wisewand_deactivate_plugin() {
		try {
			$deactivator_file = WISEWAND_PLUGIN_DIR . 'includes/Core/Deactivator.php';
			if ( file_exists( $deactivator_file ) ) {
				require_once $deactivator_file;
				if ( class_exists( 'Wisewand\\Core\\Deactivator' ) ) {
					Wisewand\Core\Deactivator::deactivate();
				}
			}
		} catch ( Exception $e ) {
			if ( WP_DEBUG ) {
				error_log( 'Wisewand Deactivation Error: ' . $e->getMessage() );
			}
		}
	}
}

// Uninstall hook with safe error handling
if ( ! function_exists( 'wisewand_uninstall_plugin' ) ) {
	function wisewand_uninstall_plugin() {
		try {
			$uninstaller_file = WISEWAND_PLUGIN_DIR . 'includes/Core/Uninstaller.php';
			if ( file_exists( $uninstaller_file ) ) {
				require_once $uninstaller_file;
				if ( class_exists( 'Wisewand\\Core\\Uninstaller' ) ) {
					Wisewand\Core\Uninstaller::uninstall();
				}
			}
		} catch ( Exception $e ) {
			if ( WP_DEBUG ) {
				error_log( 'Wisewand Uninstall Error: ' . $e->getMessage() );
			}
		}
	}
}

// Hook into WordPress with error handling
add_action( 'plugins_loaded', 'wisewand_init_plugin' );
register_activation_hook( __FILE__, 'wisewand_activate_plugin' );
register_deactivation_hook( __FILE__, 'wisewand_deactivate_plugin' );
register_uninstall_hook( __FILE__, 'wisewand_uninstall_plugin' );

// Add a simple admin notice if plugin fails to load properly
add_action(
	'admin_notices',
	function () {
		if ( is_admin() && current_user_can( 'activate_plugins' ) ) {
			if ( empty( $GLOBALS['wisewand_plugin_instance'] ) ) {
				$current_screen = get_current_screen();
				if ( $current_screen && $current_screen->id === 'plugins' ) {
					echo '<div class="notice notice-warning"><p>';
					echo '<strong>Wisewand Plugin:</strong> Plugin loaded but main class not initialized. Check error logs if issues persist.';
					echo '</p></div>';
				}
			}
		}
	}
);
