<?php
/**
 * The Pro Plugins AJAX handler.
 *
 * @package SEO_Pro_Stack
 * @subpackage SEO_Pro_Stack/Admin/Settings/AJAX
 */

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

/**
 * The Pro Plugins AJAX handler.
 */
class SEOProStack_AJAX_Pro_Plugins {

    /**
     * Initialize the AJAX handlers.
     */
    public function init() {
        add_action('wp_ajax_seoprostack_get_pro_plugins', array($this, 'get_pro_plugins'));
        add_action('wp_ajax_seoprostack_activate_plugin', array($this, 'activate_plugin'));
    }

    /**
     * Get the list of pro plugins.
     */
    public function get_pro_plugins() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'seoprostack_ajax_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }

        // Get category filter
        $category = isset($_POST['category']) ? sanitize_text_field($_POST['category']) : 'all';

        // Plugin data
        $plugins = $this->get_plugin_data($category);

        // Send response
        wp_send_json_success(array('plugins' => $plugins));
    }

    /**
     * Activate a plugin.
     */
    public function activate_plugin() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'seoprostack_ajax_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }

        // Check capabilities
        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(array('message' => 'You do not have permission to activate plugins'));
        }

        // Get plugin path
        if (!isset($_POST['plugin'])) {
            wp_send_json_error(array('message' => 'No plugin specified'));
        }

        $plugin = sanitize_text_field($_POST['plugin']);

        // Activate the plugin
        $result = activate_plugin($plugin);

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        } else {
            wp_send_json_success(array('message' => 'Plugin activated successfully'));
        }
    }

    /**
     * Get the plugin data based on category.
     *
     * @param string $category The plugin category.
     * @return array The plugin data.
     */
    private function get_plugin_data($category) {
        $plugins = array(
            array(
                'name' => 'Rank Math SEO',
                'version' => '1.0.123',
                'description' => 'The most advanced SEO plugin for WordPress that helps you optimize your website for search engines.',
                'url' => 'https://rankmath.com/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'rank-math-seo/rank-math.php',
                'category' => 'seo'
            ),
            array(
                'name' => 'WP Rocket',
                'version' => '3.14.4',
                'description' => 'The best WordPress caching plugin to speed up your website in a few clicks.',
                'url' => 'https://wp-rocket.me/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'wp-rocket/wp-rocket.php',
                'category' => 'performance'
            ),
            array(
                'name' => 'MonsterInsights',
                'version' => '8.14.0',
                'description' => 'The best Google Analytics plugin for WordPress that connects your website with Google Analytics.',
                'url' => 'https://www.monsterinsights.com/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'google-analytics-for-wordpress/googleanalytics.php',
                'category' => 'analytics'
            ),
            array(
                'name' => 'Yoast SEO',
                'version' => '21.2',
                'description' => 'The first true all-in-one SEO solution for WordPress, including on-page content analysis, XML sitemaps and much more.',
                'url' => 'https://yoast.com/wordpress/plugins/seo/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'wordpress-seo/wp-seo.php',
                'category' => 'seo'
            ),
            array(
                'name' => 'WP Cloudflare Super Page Cache',
                'version' => '4.7.0',
                'description' => 'Speed up your website by implementing full page caching using Cloudflare.',
                'url' => 'https://wordpress.org/plugins/wp-cloudflare-page-cache/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'wp-cloudflare-page-cache/wp-cloudflare-super-page-cache.php',
                'category' => 'performance'
            ),
            array(
                'name' => 'ExactMetrics',
                'version' => '7.14.1',
                'description' => 'Google Analytics Dashboard for WordPress. See how visitors find and use your website.',
                'url' => 'https://www.exactmetrics.com/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'google-analytics-dashboard-for-wp/gadwp.php',
                'category' => 'analytics'
            ),
            array(
                'name' => 'SEOPress',
                'version' => '7.2.2',
                'description' => 'Boost your SEO with SEOPress, a simple, fast and powerful WordPress SEO plugin.',
                'url' => 'https://www.seopress.org/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'wp-seopress/seopress.php',
                'category' => 'seo'
            ),
            array(
                'name' => 'WP-Optimize',
                'version' => '3.2.19',
                'description' => 'A comprehensive plugin with database clean-up, image compression and page caching features.',
                'url' => 'https://getwpo.com/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'wp-optimize/wp-optimize.php',
                'category' => 'performance'
            ),
            array(
                'name' => 'Fathom Analytics',
                'version' => '3.2.1',
                'description' => 'Simple, privacy-focused website analytics that doesn\'t compromise visitor privacy.',
                'url' => 'https://usefathom.com/',
                'status' => 'not-installed',
                'active' => false,
                'path' => 'fathom-analytics-wordpress-plugin/fathom-analytics.php',
                'category' => 'analytics'
            )
        );

        // Update plugin status (check if installed and active)
        foreach ($plugins as $key => $plugin) {
            if (file_exists(WP_PLUGIN_DIR . '/' . $plugin['path'])) {
                $plugins[$key]['status'] = 'installed';
                $plugins[$key]['active'] = is_plugin_active($plugin['path']);
            }
        }

        // Filter by category if needed
        if ($category !== 'all') {
            $plugins = array_filter($plugins, function($plugin) use ($category) {
                return $plugin['category'] === $category;
            });
        }

        return array_values($plugins);
    }
}