<?php
defined( 'ABSPATH' ) || exit;

/**
 * REEID — Neutralize SEO plugins on Woo INLINE product pages
 *
 * Scope:
 * - Woo single products ONLY
 * - OPTION-GATED ownership
 * - Fully insulated from normal pages
 */

add_action( 'wp', function () {

    /* OPTION GATE */
    if ( ! get_option( 'reeid_seo_override_hreflang', false ) ) {
        return;
    }

    if ( is_admin() || wp_doing_ajax() ) {
        return;
    }

    if ( ! function_exists( 'is_product' ) || ! is_product() ) {
        return;
    }

    /*
     * =====================
     * Disable SEO plugin canonical / hreflang
     * =====================
     */

    // Rank Math
    add_filter( 'rank_math/frontend/canonical', '__return_false', 99 );
    add_filter( 'rank_math/frontend/hreflang', '__return_false', 99 );
    add_filter( 'rank_math/frontend/hreflang/links', '__return_empty_array', 99 );

    // Yoast
    add_filter( 'wpseo_robots', '__return_false', 99 );
    add_filter( 'wpseo_canonical', '__return_false', 99 );
    add_filter( 'wpseo_hreflang_links', '__return_empty_array', 99 );

    // SEOPress
    add_filter( 'seopress_robots', '__return_false', 99 );
    add_filter( 'seopress_canonical', '__return_false', 99 );
    add_filter( 'seopress_hreflang_links', '__return_empty_array', 99 );

    // All in One SEO
    add_filter( 'aioseo_robots_meta', '__return_false', 99 );
    add_filter( 'aioseo_canonical_url', '__return_false', 99 );
    add_filter( 'aioseo_hreflang_tags', '__return_empty_array', 99 );

    /*
     * Remove WordPress core canonical
     */
    add_action( 'wp_head', function () {
        remove_action( 'wp_head', 'rel_canonical', 10 );
    }, 0 );

    /*
     * Remove SureRank canonical + meta output
     */
    add_action( 'wp_head', function () {

        global $wp_filter;

        if ( empty( $wp_filter['wp_head']->callbacks[2] ) ) {
            return;
        }

        foreach ( $wp_filter['wp_head']->callbacks[2] as $key => $cb ) {

            if (
                is_array( $cb['function'] ) &&
                is_object( $cb['function'][0] ) &&
                $cb['function'][0] instanceof \SureRank\Inc\Frontend\Meta_Data
            ) {
                unset( $wp_filter['wp_head']->callbacks[2][ $key ] );
            }
        }

    }, 0 );

}, 1 );


/**
 * FINAL AUTHORITY: Rank Math robots override (Woo only)
 */
add_action( 'rank_math/head', function () {

    if ( ! get_option( 'reeid_seo_override_hreflang', false ) ) {
        return;
    }

    if ( ! function_exists( 'is_product' ) || ! is_product() ) {
        return;
    }

    remove_action( 'rank_math/head', [ '\RankMath\Frontend\Head', 'robots' ], 20 );
    remove_action( 'rank_math/head', [ '\RankMath\Frontend\Head', 'robots' ], 10 );
    remove_action( 'rank_math/head', [ '\RankMath\Frontend\Head', 'robots' ], 1 );
    remove_action( 'rank_math/head', [ '\RankMath\Frontend\Head', 'robots' ], 0 );

    echo "<meta name=\"robots\" content=\"index, follow\" />\n";

}, 0 );
