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

/**
 * Push generated JSON-LD into Yoast SEO or Rank Math instead of duplicating wp_head output.
 */
class AISB_SEO_Sync {

    public static function init() {
        add_filter('wpseo_schema_graph', [__CLASS__, 'yoast_inject_graph'], 20, 2);
        add_filter('rank_math/json_ld', [__CLASS__, 'rankmath_inject'], 20, 2);
    }

    public static function is_sync_mode() {
        $mode = aisb_get_settings()['seo_coexist_mode'] ?? 'smart';
        return $mode === 'sync_seo';
    }

    public static function sync_after_save($post_id, $schema, $type = '') {
        if (!self::is_sync_mode() || !$post_id || !is_array($schema)) {
            return false;
        }
        $type = $type ?: AISB_Rich_Results::primary_type_public($schema);
        $plugins = AISB_SEO_Plugins::detect();
        if (isset($plugins['rankmath'])) {
            return self::sync_rankmath($post_id, $schema, $type);
        }
        if (isset($plugins['yoast'])) {
            return self::sync_yoast_meta($post_id, $schema, $type);
        }
        return false;
    }

    private static function sync_rankmath($post_id, $schema, $type) {
        $key = 'rank_math_schema_' . sanitize_key($type);
        update_post_meta($post_id, $key, wp_slash(aisb_safe_json($schema)));
        update_post_meta($post_id, 'rank_math_rich_snippet', strtolower($type));
        update_post_meta($post_id, '_aisb_synced_seo', 'rankmath');
        return true;
    }

    private static function sync_yoast_meta($post_id, $schema, $type) {
        update_post_meta($post_id, '_aisb_yoast_schema_json', wp_slash(aisb_safe_json($schema)));
        update_post_meta($post_id, '_aisb_yoast_schema_type', sanitize_key($type));
        update_post_meta($post_id, '_aisb_synced_seo', 'yoast');
        return true;
    }

    public static function yoast_inject_graph($graph, $context) {
        if (!self::is_sync_mode()) {
            return $graph;
        }
        $post_id = 0;
        if (is_object($context) && isset($context->indexable)) {
            $post_id = (int) ($context->indexable->object_id ?? 0);
        } elseif (is_singular()) {
            $post_id = get_queried_object_id();
        }
        if (!$post_id) {
            return $graph;
        }
        $raw = get_post_meta($post_id, '_aisb_yoast_schema_json', true);
        if (!$raw) {
            return $graph;
        }
        $schema = is_string($raw) ? json_decode($raw, true) : $raw;
        if (!is_array($schema)) {
            return $graph;
        }
        unset($schema['@context']);
        $graph[] = $schema;
        return $graph;
    }

    public static function rankmath_inject($data, $jsonld) {
        if (!self::is_sync_mode() || !is_singular()) {
            return $data;
        }
        $post_id = get_queried_object_id();
        $type = get_post_meta($post_id, '_aisb_schema_type', true);
        if (!$type) {
            return $data;
        }
        $raw = get_post_meta($post_id, 'rank_math_schema_' . sanitize_key($type), true);
        if (!$raw) {
            $raw = get_post_meta($post_id, AISB_Schema::META_JSON, true);
        }
        $schema = is_string($raw) ? json_decode($raw, true) : $raw;
        if (is_array($schema)) {
            unset($schema['@context']);
            $data = array_merge($data, $schema);
        }
        return $data;
    }
}
