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

/**
 * SEO plugin bridge — softly integrates with Yoast SEO and Rank Math.
 *
 * - Pulls the focus keyword so prompts target the same intent the site owner already set.
 * - Prevents duplicate JSON-LD: if Yoast, Rank Math or AI Schema Builder already output
 *   schema on the frontend, AIVT suppresses its own output.
 */
class AIVT_SEO_Bridge {

    public static function yoast_active() {
        return defined('WPSEO_VERSION') || class_exists('WPSEO_Options');
    }

    public static function rankmath_active() {
        return class_exists('RankMath') || function_exists('rank_math');
    }

    /** True when another plugin already owns frontend schema output. */
    public static function schema_owned_externally() {
        if (class_exists('AISB_Schema')) {
            return true;
        }
        return self::yoast_active() || self::rankmath_active();
    }

    /** Human label for the active SEO plugin, or '' when none. */
    public static function active_label() {
        if (self::rankmath_active()) {
            return 'Rank Math';
        }
        if (self::yoast_active()) {
            return 'Yoast SEO';
        }
        return '';
    }

    /** Focus keyword for a post from Rank Math or Yoast, or '' when unset. */
    public static function focus_keyword($post_id) {
        $post_id = (int) $post_id;
        if (!$post_id) {
            return '';
        }
        // Rank Math (can be a comma-separated list — take the primary one).
        $rm = get_post_meta($post_id, 'rank_math_focus_keyword', true);
        if (is_string($rm) && $rm !== '') {
            $parts = array_filter(array_map('trim', explode(',', $rm)));
            if (!empty($parts)) {
                return sanitize_text_field($parts[0]);
            }
        }
        // Yoast SEO.
        $yo = get_post_meta($post_id, '_yoast_wpseo_focuskw', true);
        if (is_string($yo) && $yo !== '') {
            return sanitize_text_field($yo);
        }
        return '';
    }

    /** A prompt line describing the page's focus keyword + active SEO plugin, or ''. */
    public static function prompt_context($post_id) {
        $kw = self::focus_keyword($post_id);
        if ($kw === '') {
            return '';
        }
        return 'Primary target keyword (from ' . (self::active_label() ?: 'SEO plugin') . '): ' . $kw;
    }
}
