<?php
/**
 * Plugin Name: ProRank SEO – All-in-One SEO & Performance for WordPress
 * Plugin URI: https://prorank.io
 * Description: All-in-one WordPress SEO and performance toolkit with on-page SEO, technical SEO, caching, and local image optimisation.
 * Version: 1.2.1
 * Author: ProRank
 * Author URI: https://prorank.io/about
 * License: GPL v2 or later
 * Text Domain: prorank-seo
 * Domain Path: /languages
 * Requires at least: 6.7
 * Tested up to: 6.9
 * Requires PHP: 8.2
 */

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

if ( ! function_exists( 'prorank_free_is_premium_activation_request' ) ) {
    /**
     * Detect a premium activation request before WordPress updates active plugins.
     *
     * This lets the free bootstrap step aside so premium can own the shared
     * PRORANK_* constants during the activation request itself.
     */
    function prorank_free_is_premium_activation_request() {
        $premium_basename = 'prorank-seo-premium/prorank-seo.php';
        $actions = [];

        if ( defined( 'WP_CLI' ) && WP_CLI ) {
            $argv = isset( $_SERVER['argv'] ) ? (array) $_SERVER['argv'] : [];
            $argv = array_map( 'sanitize_text_field', $argv );

            $is_plugin_activation_command =
                in_array( 'plugin', $argv, true ) &&
                in_array( 'activate', $argv, true ) &&
                (
                    in_array( 'prorank-seo-premium', $argv, true ) ||
                    in_array( $premium_basename, $argv, true )
                );

            if ( $is_plugin_activation_command ) {
                return true;
            }
        }

        if ( isset( $_REQUEST['action'] ) ) {
            $actions[] = sanitize_key( wp_unslash( $_REQUEST['action'] ) );
        }

        if ( isset( $_REQUEST['action2'] ) ) {
            $actions[] = sanitize_key( wp_unslash( $_REQUEST['action2'] ) );
        }

        $plugin = isset( $_REQUEST['plugin'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['plugin'] ) ) : '';
        $checked = isset( $_REQUEST['checked'] ) ? (array) wp_unslash( $_REQUEST['checked'] ) : [];
        $checked = array_map( 'sanitize_text_field', $checked );

        $is_activation_action = in_array( 'activate', $actions, true ) || in_array( 'activate-selected', $actions, true );
        $targets_premium = ( $plugin === $premium_basename ) || in_array( $premium_basename, $checked, true );

        return $is_activation_action && $targets_premium;
    }
}

// If Premium is active, bail out to avoid duplicate functionality/routes.
$prorank_active_plugins = (array) get_option( 'active_plugins', [] );
$prorank_network_plugins = (array) get_site_option( 'active_sitewide_plugins', [] );
if (
    defined( 'PRORANK_PREMIUM_VERSION' ) ||
    prorank_free_is_premium_activation_request() ||
    in_array( 'prorank-seo-premium/prorank-seo.php', $prorank_active_plugins, true ) ||
    isset( $prorank_network_plugins['prorank-seo-premium/prorank-seo.php'] )
) {
    return;
}


// Define plugin constants
if ( ! defined( 'PRORANK_VERSION' ) ) {
    define( 'PRORANK_VERSION', '1.2.1' );
}
if ( ! defined( 'PRORANK_SEO_VERSION' ) ) {
    define( 'PRORANK_SEO_VERSION', PRORANK_VERSION ); // Alias for compatibility
}
if ( ! defined( 'PRORANK_PLUGIN_FILE' ) ) {
    define( 'PRORANK_PLUGIN_FILE', __FILE__ );
}
if ( ! defined( 'PRORANK_PLUGIN_DIR' ) ) {
    define( 'PRORANK_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'PRORANK_PLUGIN_URL' ) ) {
    define( 'PRORANK_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'PRORANK_PLUGIN_BASENAME' ) ) {
    define( 'PRORANK_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
}
if ( ! defined( 'PRORANK_SEO_URL' ) ) {
    define( 'PRORANK_SEO_URL', PRORANK_PLUGIN_URL );
}

// Load API configuration constants
require_once PRORANK_PLUGIN_DIR . 'prorank-config-constants.php';

// Load plugin autoloader
$prorank_autoloader = PRORANK_PLUGIN_DIR . 'includes/autoload.php';
if ( file_exists( $prorank_autoloader ) ) {
    require_once $prorank_autoloader;
}

/**
 * Get the main plugin instance
 *
 * @return \ProRank\SEO\Plugin
 */
if ( ! function_exists( 'prorank' ) ) {
    function prorank() {
        return \ProRank\SEO\Plugin::get_instance();
    }
}

// Load the plugin instance
add_action( 'plugins_loaded', function() {
    // Initialize the plugin
    $instance = ProRank\SEO\Plugin::get_instance();

    // Ensure image optimization background callbacks are registered early
    if ( method_exists( $instance, 'register_image_optimization_actions' ) ) {
        $instance->register_image_optimization_actions();
    }

    // Directly register internal linking REST endpoints
    add_action('rest_api_init', function() {
        $endpoints_file = PRORANK_PLUGIN_DIR . 'includes/Core/RestApi/InternalLinkingEndpoints.php';
        if (file_exists($endpoints_file)) {
            require_once PRORANK_PLUGIN_DIR . 'includes/Core/RestApi/InternalLinkingEndpoints.php';
            if (function_exists('\ProRank\SEO\Core\RestApi\register_internal_linking_endpoints')) {
                \ProRank\SEO\Core\RestApi\register_internal_linking_endpoints();
            }
        }
    }, 5);

    // Initialize Link Click Tracker
    $tracker_file = PRORANK_PLUGIN_DIR . 'includes/Core/LinkClickTracker.php';
    if (file_exists($tracker_file)) {
        require_once PRORANK_PLUGIN_DIR . 'includes/Core/LinkClickTracker.php';
    }

}, 5 );

// Load WP-CLI commands
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    // Load CLI command files - they self-register with WP_CLI::add_command()
    $prorank_cli_commands = [
        PRORANK_PLUGIN_DIR . 'includes/CLI/ImageOptimizationCommand.php',
    ];

    foreach ( $prorank_cli_commands as $prorank_cli_file ) {
        if ( file_exists( $prorank_cli_file ) ) {
            require_once $prorank_cli_file;
        }
    }
}

// Activation hook
register_activation_hook( __FILE__, function() {
    // Ensure autoloader is loaded
    $prorank_autoloader = PRORANK_PLUGIN_DIR . 'includes/autoload.php';
    if ( file_exists( $prorank_autoloader ) ) {
        require_once $prorank_autoloader;
    }

    // Run activation through Lifecycle service
    if ( class_exists( 'ProRank\SEO\Core\Lifecycle' ) ) {
        ProRank\SEO\Core\Lifecycle::activate();
    }

    // Create link tracker table
    $tracker_file = PRORANK_PLUGIN_DIR . 'includes/Core/LinkClickTracker.php';
    if ( file_exists( $tracker_file ) ) {
        require_once PRORANK_PLUGIN_DIR . 'includes/Core/LinkClickTracker.php';
        if ( class_exists( 'ProRank\SEO\Core\LinkClickTracker' ) ) {
            $tracker = new ProRank\SEO\Core\LinkClickTracker();
            $tracker->create_table();
        }
    }

} );

// Deactivation hook
register_deactivation_hook( __FILE__, function() {
    // Ensure autoloader is loaded
    $prorank_autoloader = PRORANK_PLUGIN_DIR . 'includes/autoload.php';
    if ( file_exists( $prorank_autoloader ) ) {
        require_once $prorank_autoloader;
    }

    // Run deactivation through Lifecycle service
    if ( class_exists( 'ProRank\SEO\Core\Lifecycle' ) ) {
        ProRank\SEO\Core\Lifecycle::deactivate();
    }

} );

// Uninstall hook (via uninstall.php for better practice)

// Internal linking endpoints are registered by the main plugin on rest_api_init.
