<?php
/**
 * Compatibility layer — detects competing SEO plugins (Yoast, RankMath, AIOSEO,
 * The SEO Framework, SEOPress) and lets Brainwerk SEO Suite stand down to avoid duplicate
 * meta tags, canonicals, schema and sitemaps.
 *
 * The user can override the auto-detection with the `seo_force_takeover`
 * setting, in which case Brainwerk SEO Suite always emits its tags.
 *
 * @package Brainwerk SEO Suite
 */

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

class Seoforge_Compat {

    /** Map of plugin file → human label. */
    private static $known = array(
        'wordpress-seo/wp-seo.php'                => 'Yoast SEO',
        'wordpress-seo-premium/wp-seo-premium.php'=> 'Yoast SEO Premium',
        'seo-by-rank-math/rank-math.php'          => 'Rank Math',
        'seo-by-rank-math-pro/rank-math-pro.php'  => 'Rank Math Pro',
        'all-in-one-seo-pack/all_in_one_seo_pack.php' => 'All in One SEO',
        'autodescription/autodescription.php'     => 'The SEO Framework',
        'wp-seopress/seopress.php'                => 'SEOPress',
        'wp-seopress-pro/seopress-pro.php'        => 'SEOPress Pro',
    );

    /** Cached detection result. */
    private static $detected = null;

    /**
     * Returns ['active' => bool, 'name' => string|null, 'file' => string|null].
     */
    public static function detect_competitor() {
        if ( null !== self::$detected ) {
            return self::$detected;
        }
        $active = (array) get_option( 'active_plugins', array() );
        if ( is_multisite() ) {
            $network = (array) get_site_option( 'active_sitewide_plugins', array() );
            $active  = array_unique( array_merge( $active, array_keys( $network ) ) );
        }
        foreach ( self::$known as $file => $label ) {
            if ( in_array( $file, $active, true ) ) {
                self::$detected = array( 'active' => true, 'name' => $label, 'file' => $file );
                return self::$detected;
            }
        }
        self::$detected = array( 'active' => false, 'name' => null, 'file' => null );
        return self::$detected;
    }

    /**
     * True when Brainwerk SEO Suite should stand down on meta/schema/sitemap output.
     */
    public static function should_stand_down() {
        if ( (bool) Seoforge_Settings::get( 'seo_force_takeover', false ) ) {
            return false;
        }
        $det = self::detect_competitor();
        return $det['active'];
    }

    /** Used to render the dashboard notice + privacy-snippet section. */
    public static function competitor_label() {
        $det = self::detect_competitor();
        return $det['name'];
    }
}
