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

class SS_Schema {

    public static function init() {

        // Output schema in frontend
        add_action('wp_head', [__CLASS__, 'output_schema'], 20);

        // Save schema preview
        add_action('transition_post_status', [__CLASS__, 'save_schema'], 10, 3);

        // Disable conflicting schema (Yoast etc.)
        add_action('template_redirect', [__CLASS__, 'disable_conflicts'], 1);
    }

    /**
     * OUTPUT SCHEMA
     */
    public static function output_schema() {

        if (!is_singular()) return;

        global $post;

        $json = self::generate_schema($post->ID);

        if (!$json) return;

        echo '<script type="application/ld+json">' . wp_kses_data( $json ) . '</script>';
    }

    /**
     * YOUR ORIGINAL SCHEMA LOGIC (MOVED HERE)
     */
    public static function generate_schema($post_id) {

        $schema = [
            "@context" => "https://schema.org",
            "@graph"   => []
        ];

        $post_type = get_post_type($post_id);

        // ARTICLE
        if ($post_type === 'post') {
            $schema["@graph"][] = [
                "@type" => "Article",
                "@id"   => get_permalink($post_id) . "#article",
                "headline" => get_the_title($post_id),
                "url"      => get_permalink($post_id),
                "author"   => [
                    "@type" => "Person",
                    "name"  => get_the_author_meta('display_name'),
                    "url"   => get_author_posts_url(get_the_author_meta('ID'))
                ],
                "image" => get_the_post_thumbnail_url($post_id, 'full') ?: null,
                "datePublished" => get_the_date('c', $post_id),
                "dateModified"  => get_the_modified_date('c', $post_id),
                "inLanguage"    => get_bloginfo('language')
            ];
        }

        // GLOSSARY
        if ($post_type === 'ss_glossary') {

            $term    = get_the_title($post_id);
            $def     = get_post_meta($post_id, 'ss_definition', true);
            $related = (array) get_post_meta($post_id, 'ss_related_terms', true);
            $video   = get_post_meta($post_id, 'ss_video_url', true);

            $entry = [
                "@type" => "DefinedTerm",
                "@id"   => get_permalink($post_id) . "#definedterm",
                "name"  => $term,
                "description" => $def,
                "url"  => get_permalink($post_id),
                "inDefinedTermSet" => site_url('/glossary/#definedtermset')
            ];

            // Related terms (PRO)
            if (!empty($related) && function_exists('searchshifter_has_plan') && searchshifter_has_plan('pro')) {

                $entry["relatedLink"] = [];

                foreach ($related as $rid) {
                    if (!get_post_status($rid)) continue;

                    $entry["relatedLink"][] = [
                        "@type" => "DefinedTerm",
                        "name"  => get_the_title($rid),
                        "@id"   => get_permalink($rid) . "#definedterm"
                    ];
                }
            }

            // Video (Authority)
            if ($video && function_exists('searchshifter_has_plan') && searchshifter_has_plan('authority')) {
                $entry["subjectOf"] = [
                    "@type" => "VideoObject",
                    "url"   => $video
                ];
            }

            $schema["@graph"][] = $entry;

            // Term set
            $schema["@graph"][] = [
                "@type" => "DefinedTermSet",
                "@id"   => site_url('/glossary/#definedtermset'),
                "name"  => "SearchShifter Glossary",
                "url"   => site_url('/glossary/')
            ];
        }

        // FAQ
        if ($post_type === 'ss_qa') {

            $question = get_the_title($post_id);
            $answer   = get_post_meta($post_id, '_ss_qa_answer', true);

            if (!empty($question) && !empty($answer)) {

                $schema["@graph"][] = [
                    "@type" => "FAQPage",
                    "@id"   => get_permalink($post_id) . "#faq",
                    "mainEntity" => [
                        [
                            "@type" => "Question",
                            "name"  => $question,
                            "acceptedAnswer" => [
                                "@type" => "Answer",
                                "text"  => $answer
                            ]
                        ]
                    ]
                ];
            }
        }

        return wp_json_encode($schema, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }

    /**
     * SAVE SCHEMA FOR PREVIEW
     */
    public static function save_schema($new, $old, $post) {

        if ($new !== 'publish') return;

        $json = self::generate_schema($post->ID);

        update_post_meta($post->ID, '_ss_schema_json', $json);
    }

    /**
     * DISABLE YOAST / OTHER SCHEMA
     */
    public static function disable_conflicts() {

        $glossary_id = (int) get_option('ss_glossary_page_id');
        $faq_id      = (int) get_option('ss_faq_page_id');

        // Disable on:
        // 1. Glossary CPT
        // 2. Glossary Page
        // 3. FAQ Page

        if (
            is_singular('ss_glossary') ||
            ($glossary_id && is_page($glossary_id)) ||
            ($faq_id && is_page($faq_id))
        ) {

            add_filter('wpseo_json_ld_output', '__return_empty_array', 9999);
            add_filter('wpseo_schema_needs_to_output', '__return_false', 9999);

            remove_all_actions('wpseo_json_ld');
            remove_all_actions('wpseo_head');
        }
    }
}