<?php
if (!defined('ABSPATH')) exit;

/**
 * Coexistence with Yoast SEO, Rank Math and other JSON-LD emitters.
 */
class AISB_SEO_Plugins {

    public static function detect() {
        $found = [];
        if (defined('WPSEO_VERSION') || class_exists('WPSEO_Options')) {
            $found['yoast'] = [
                'name'    => 'Yoast SEO',
                'version' => defined('WPSEO_VERSION') ? WPSEO_VERSION : '',
            ];
        }
        if (defined('RANK_MATH_VERSION') || class_exists('RankMath')) {
            $found['rankmath'] = [
                'name'    => 'Rank Math',
                'version' => defined('RANK_MATH_VERSION') ? RANK_MATH_VERSION : '',
            ];
        }
        if (defined('AIOSEO_VERSION')) {
            $found['aioseo'] = ['name' => 'All in One SEO', 'version' => AIOSEO_VERSION];
        }
        if (defined('SEOPRESS_VERSION')) {
            $found['seopress'] = ['name' => 'SEOPress', 'version' => SEOPRESS_VERSION];
        }
        return apply_filters('aisb_detected_seo_plugins', $found);
    }

    public static function has_competitor_schema() {
        return !empty(self::detect());
    }

    /**
     * Should PEWIT output JSON-LD on this request?
     *
     * @param string $mode pewit_only|smart|disabled
     */
    public static function should_output_frontend($post_id, $mode = '') {
        if ($mode === '' || $mode === null) {
            $mode = aisb_get_settings()['seo_coexist_mode'] ?? 'smart';
        }
        if ($mode === 'disabled') {
            return false;
        }
        if ($mode === 'sync_seo') {
            return false;
        }
        if ($mode === 'pewit_only') {
            return true;
        }
        // smart: output ours; user disables frontend if duplicate is a problem
        if ($mode === 'smart' && self::has_competitor_schema()) {
            return apply_filters('aisb_should_output_with_seo_plugin', true, $post_id);
        }
        return true;
    }

    public static function admin_notice_html() {
        $plugins = self::detect();
        if (empty($plugins)) {
            return '';
        }
        $names = implode(', ', array_column($plugins, 'name'));
        return sprintf(
            /* translators: %s: comma-separated SEO plugin names */
            /* translators: %s are replaced with dynamic values */ __('Detected: %s. Use Output → coexistence: Smart, Sync to SEO plugin, or PEWIT only.', 'pewit-ai-schema-builder'),
            esc_html($names)
        );
    }
}
