<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://yourwebsite.com
 * @since      1.0.0
 *
 * @package    CSPG_Basic_SEO_Helper
 * @subpackage CSPG_Basic_SEO_Helper/includes
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    CSPG_Basic_SEO_Helper
 * @subpackage CSPG_Basic_SEO_Helper/includes
 * @author     CSP Geeks LLC <info@cspgeeks.com>
 */
class CSPG_Basic_SEO_Helper {

	/**
	 * The loader that's responsible for maintaining and registering all hooks that power
	 * the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      CSPG_Basic_SEO_Helper_Loader    $loader    Maintains and registers all hooks for the plugin.
	 */
	protected $loader;

	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $plugin_name    The string used to uniquely identify this plugin.
	 */
	protected $plugin_name;

	/**
	 * The current version of the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $version    The current version of the plugin.
	 */
	protected $version;

	/**
	 * Define the core functionality of the plugin.
	 *
	 * Set the plugin name and the plugin version that can be used throughout the plugin.
	 * Load the dependencies, define the locale, and set the hooks for the admin area and
	 * the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {
		if ( defined( 'CSPG_BASIC_SEO_HELPER_VERSION' ) ) {
			$this->version = CSPG_BASIC_SEO_HELPER_VERSION;
		} else {
			$this->version = '1.0.0';
		}
		$this->plugin_name = 'cspg-basic-seo-helper';

		$this->load_dependencies();
		$this->define_admin_hooks();
		$this->define_public_hooks();
	}

	/**
	 * Load the required dependencies for this plugin.
	 *
	 * Include the following files that make up the plugin:
	 *
	 * - CSPG_Basic_SEO_Helper_Loader. Orchestrates the hooks of the plugin.
	 * - CSPG_Basic_SEO_Helper_i18n. Defines internationalization functionality.
	 * - CSPG_Basic_SEO_Helper_Admin. Defines all hooks for the admin area.
	 * - CSPG_Basic_SEO_Helper_Public. Defines all hooks for the public side of the site.
	 *
	 * Create an instance of the loader which will be used to register the hooks
	 * with WordPress.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function load_dependencies() {

		/**
		 * The class responsible for orchestrating the actions and filters of the
		 * core plugin.
		 */
		require_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'includes/class-cspg-basic-seo-helper-loader.php';

		/**
		 * The class responsible for defining all actions that occur in the admin area.
		 */
		require_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'admin/class-cspg-basic-seo-helper-admin.php';

		/**
		 * The class responsible for defining all actions that occur in the public-facing
		 * side of the site.
		 */
		require_once CSPG_BASIC_SEO_HELPER_PLUGIN_PATH . 'public/class-cspg-basic-seo-helper-public.php';

		/**
		 * The class responsible for license management and validation.
		 * Disabled for free version
		 */
		// require_once BASIC_SEO_HELPER_PLUGIN_PATH . 'includes/class-basic-seo-helper-license.php';

		/**
		 * The class responsible for feature management and licensing.
		 * Disabled for free version
		 */
		// require_once BASIC_SEO_HELPER_PLUGIN_PATH . 'includes/class-basic-seo-helper-features.php';

		$this->loader = new CSPG_Basic_SEO_Helper_Loader();
	}

	/**
	 * Register all of the hooks related to the admin area functionality
	 * of the plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function define_admin_hooks() {

		$plugin_admin = new CSPG_Basic_SEO_Helper_Admin( $this->get_plugin_name(), $this->get_version() );

		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );
		$this->loader->add_action( 'admin_init', $plugin_admin, 'admin_init' );
		$this->loader->add_action( 'admin_menu', $plugin_admin, 'admin_menu' );
		$this->loader->add_action( 'add_meta_boxes', $plugin_admin, 'add_meta_boxes' );
		$this->loader->add_action( 'save_post', $plugin_admin, 'save_meta_box' );

		// Register post meta for REST API access
		$this->loader->add_action( 'init', $plugin_admin, 'register_post_meta' );

		// Run database migration check
		$this->loader->add_action( 'admin_init', $this, 'check_and_migrate_options' );

		// Add plugin action links
		$this->loader->add_filter( 'plugin_action_links_' . CSPG_BASIC_SEO_HELPER_PLUGIN_BASENAME, $plugin_admin, 'add_plugin_action_links' );

		// Initialize licensing system - disabled for free version
		// $this->define_license_hooks();
	}

	/**
	 * Register all of the hooks related to the public-facing functionality
	 * of the plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function define_public_hooks() {

		$plugin_public = new CSPG_Basic_SEO_Helper_Public( $this->get_plugin_name(), $this->get_version() );

		$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
		$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
		$this->loader->add_action( 'wp_head', $plugin_public, 'remove_wp_canonical', 0 ); // Priority 0 to run before rel_canonical
		$this->loader->add_action( 'wp_head', $plugin_public, 'add_seo_meta_tags' );
		$this->loader->add_filter( 'document_title_parts', $plugin_public, 'filter_document_title' );

		// Add sitemap functionality
		$this->loader->add_action( 'init', $this, 'add_sitemap_rewrite_rules' );
		$this->loader->add_action( 'init', $this, 'disable_wp_sitemap' );
		$this->loader->add_action( 'template_redirect', $plugin_public, 'handle_sitemap_request' );

		// Add sitemap cache invalidation hooks
		$this->loader->add_action( 'save_post', $plugin_public, 'invalidate_sitemap_cache' );
		$this->loader->add_action( 'delete_post', $plugin_public, 'invalidate_sitemap_cache' );
		$this->loader->add_action( 'wp_trash_post', $plugin_public, 'invalidate_sitemap_cache' );
		$this->loader->add_action( 'untrash_post', $plugin_public, 'invalidate_sitemap_cache' );
	}

	/**
	 * Check and migrate options from old prefixes to new prefixes.
	 * Runs once on admin_init to ensure backward compatibility.
	 *
	 * @since    1.2.14
	 */
	public function check_and_migrate_options() {
		// Check if migration has already been run
		$db_version = get_option( 'cspgbase_db_version' );

		if ( '1.2.14' === $db_version ) {
			return; // Migration already complete
		}

		// Map of old option names to new option names
		$option_migrations = array(
			// Array options
			'basic_seo_helper_options'            => 'cspgbase_options',
			'basic_seo_helper_sitemap_settings'   => 'cspgbase_sitemap_settings',
			// Individual options
			'bsh_enable_canonical'                => 'cspgbase_enable_canonical',
			'bsh_enable_open_graph'               => 'cspgbase_enable_open_graph',
			'bsh_enable_twitter_cards'            => 'cspgbase_enable_twitter_cards',
			'bsh_enable_author_meta'              => 'cspgbase_enable_author_meta',
			'bsh_default_title_template'          => 'cspgbase_default_title_template',
			'bsh_default_description_template'    => 'cspgbase_default_description_template',
			'bsh_default_og_title_template'       => 'cspgbase_default_og_title_template',
			'bsh_default_og_description_template' => 'cspgbase_default_og_description_template',
			'bsh_fallback_text'                   => 'cspgbase_fallback_text',
			'bsh_title_separator'                 => 'cspgbase_title_separator',
		);

		// Migrate each option
		foreach ( $option_migrations as $old_name => $new_name ) {
			$old_value = get_option( $old_name );

			// Only migrate if old option exists and new option doesn't
			if ( false !== $old_value ) {
				$new_value = get_option( $new_name );
				if ( false === $new_value ) {
					// Copy old option to new option name
					add_option( $new_name, $old_value );
				}
			}
		}

		// Mark migration as complete
		update_option( 'cspgbase_db_version', '1.2.14' );
	}

	/**
	 * Run the loader to execute all of the hooks with WordPress.
	 *
	 * @since    1.0.0
	 */
	public function run() {
		$this->loader->run();
	}

	/**
	 * The name of the plugin used to uniquely identify it within the context of
	 * WordPress and to define internationalization functionality.
	 *
	 * @since     1.0.0
	 * @return    string    The name of the plugin.
	 */
	public function get_plugin_name() {
		return $this->plugin_name;
	}

	/**
	 * The reference to the class that orchestrates the hooks with the plugin.
	 *
	 * @since     1.0.0
	 * @return    Basic_SEO_Helper_Loader    Orchestrates the hooks of the plugin.
	 */
	public function get_loader() {
		return $this->loader;
	}

	/**
	 * Retrieve the version number of the plugin.
	 *
	 * @since     1.0.0
	 * @return    string    The version number of the plugin.
	 */
	public function get_version() {
		return $this->version;
	}

	/**
	 * Add sitemap rewrite rules
	 *
	 * @since    1.0.3
	 */
	public function add_sitemap_rewrite_rules() {
		// Main sitemap index
		add_rewrite_rule( '^sitemap\.xml$', 'index.php?basic_seo_sitemap=index', 'top' );

		// Posts sitemap
		add_rewrite_rule( '^posts-sitemap\.xml$', 'index.php?basic_seo_sitemap=posts', 'top' );

		// Pages sitemap
		add_rewrite_rule( '^pages-sitemap\.xml$', 'index.php?basic_seo_sitemap=pages', 'top' );

		add_rewrite_tag( '%basic_seo_sitemap%', '([a-zA-Z]+)' );

		// Flush rewrite rules if they haven't been flushed yet for this version
		if ( get_option( 'cspg_basic_seo_helper_sitemap_rewrite_version' ) !== CSPG_BASIC_SEO_HELPER_VERSION ) {
			flush_rewrite_rules();
			update_option( 'cspg_basic_seo_helper_sitemap_rewrite_version', CSPG_BASIC_SEO_HELPER_VERSION );
		}
	}

	/**
	 * Disable WordPress built-in sitemap functionality
	 *
	 * @since    1.1.0
	 */
	public function disable_wp_sitemap() {
		// Check if sitemap is enabled in plugin settings
		$sitemap_settings = get_option( 'cspgbase_sitemap_settings', array() );
		if ( isset( $sitemap_settings['enabled'] ) && '1' === $sitemap_settings['enabled'] ) {
			// Disable WordPress's built-in XML sitemaps
			remove_action( 'init', 'wp_sitemaps_get_server' );

			// Remove WordPress sitemap rewrite rules
			add_filter( 'wp_sitemaps_enabled', '__return_false' );

			// Ensure our sitemap takes precedence by removing WP's sitemap.xml redirect
			add_filter( 'redirect_canonical', array( $this, 'prevent_sitemap_redirect' ), 10, 2 );
		}
	}

	/**
	 * Prevent WordPress from redirecting sitemap.xml to wp-sitemap.xml
	 *
	 * @since    1.1.0
	 * @param    string    $redirect_url    The redirect URL.
	 * @param    string    $requested_url   The requested URL.
	 * @return   string|false              Modified redirect URL or false to prevent redirect.
	 */
	public function prevent_sitemap_redirect( $redirect_url, $requested_url ) {
		// If the request is for sitemap.xml, don't redirect it
		if ( strpos( $requested_url, 'sitemap.xml' ) !== false ) {
			return false;
		}
		return $redirect_url;
	}

	/**
	 * Define the licensing system hooks.
	 *
	 * @since    1.0.4
	 * @access   private
	 */
	private function define_license_hooks() {
		// License system disabled for free version
		// Initialize license manager
		// $license_manager = new Basic_SEO_Helper_License();

		// Initialize feature manager with license manager
		// $feature_manager = new Basic_SEO_Helper_Features($license_manager);

		// Make sure both are initialized (they have their own constructor hooks)
		// No additional hooks needed here as the classes handle their own initialization
	}
}
