<?php
declare(strict_types=1);


/**
 * Competitor Switcher
 *
 * Handles competitor plugin compatibility guidance
 *
 * @package ProRank\SEO\Admin
 */

namespace ProRank\SEO\Admin;

use ProRank\SEO\Core\Compatibility\CompetitorDetector;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * CompetitorSwitcher class
 */


class CompetitorSwitcher {
    
    /**
     * Initialize the switcher
     */
    public function init(): void {
        // Add AJAX handler for compatibility guidance.
        add_action('wp_ajax_prorank_deactivate_competitors', [$this, 'handle_bulk_deactivation']);
    }
    
    /**
     * Handle competitor action request.
     *
     * WordPress.org policy does not allow a plugin to change activation
     * state of other plugins. This endpoint now returns a list of detected
     * competitor plugins so the site owner can deactivate them manually.
     */
    public function handle_bulk_deactivation(): void {
        // Check nonce
        $nonce = filter_input(INPUT_POST, 'nonce', FILTER_SANITIZE_STRING);
        if (!$nonce || !wp_verify_nonce($nonce, 'prorank_deactivate_competitors')) {
            wp_die( esc_html__( 'Security check failed', 'prorank-seo' ) );
        }
        
        // Check permissions
        if (!current_user_can('activate_plugins')) {
            wp_die( esc_html__( 'You do not have permission to deactivate plugins', 'prorank-seo' ) );
        }
        
        $detector = new CompetitorDetector();
        $competitors = $detector->get_active_seo_competitors_details();
        
        $detected = [];
        foreach ($competitors as $competitor) {
            if (!is_array($competitor)) {
                continue;
            }

            $detected[] = [
                'name' => isset($competitor['name']) ? (string) $competitor['name'] : '',
                'file' => isset($competitor['file']) ? (string) $competitor['file'] : '',
            ];
        }

        wp_send_json_success([
            'requires_manual_action' => true,
            'detected' => $detected,
            'message' => __('Please deactivate conflicting SEO plugins manually from Plugins > Installed Plugins.', 'prorank-seo'),
        ]);
    }
}
