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

class SS_Freshness {
    public static function init() {
        add_filter('the_content', [__CLASS__, 'inject_lastmod'], 20);
        add_action('wp_head',     [__CLASS__, 'meta_lastmod'], 5);

        // If Yoast is active, ensure dateModified is set.
        add_filter('wpseo_schema_webpage', [__CLASS__, 'yoast_date'], 10, 1);

        // If RankMath is active, ensure dateModified is set.
        add_filter('rank_math/json_ld', [__CLASS__, 'rankmath_date'], 10, 1);
    }

    /** Append a visible <time> element for ss_qa posts */
    public static function inject_lastmod($content){
        if (!is_singular('ss_qa') || is_admin()) return $content;

        $iso   = get_post_modified_time('c', true);
        $human = get_post_modified_time(get_option('date_format'), true);

        // Don’t duplicate if already present
        if (stripos($content, 'class="ss-lastmod"') !== false) return $content;

        $stamp = sprintf(
            '<p class="ss-lastmod-wrap"><time class="ss-lastmod" datetime="%s">Last updated: %s</time></p>',
            esc_attr($iso),
            esc_html($human)
        );

        // Try to place after the last paragraph; fall back to append
        $new = preg_replace('#</p>\s*(?!.*</p>)#is', '</p>'.$stamp, $content, 1);
        return $new ?: ($content.$stamp);
    }

    /** Expose ISO timestamp in meta for crawlers */
    public static function meta_lastmod(){
        if (!is_singular('ss_qa')) return;
        $iso = get_post_modified_time('c', true);
        printf(
            "\n<meta name=\"last-modified\" content=\"%s\" />\n<meta property=\"og:updated_time\" content=\"%s\" />\n<meta property=\"article:modified_time\" content=\"%s\" />\n",
            esc_attr($iso), esc_attr($iso), esc_attr($iso)
        );
    }

    /** Yoast: force dateModified */
    public static function yoast_date($data){
        if (!is_singular('ss_qa')) return $data;
        $data['dateModified'] = get_post_modified_time('c', true);
        return $data;
    }

    /** RankMath: force dateModified on relevant graphs */
    public static function rankmath_date($graphs){
        if (!is_singular('ss_qa') || !is_array($graphs)) return $graphs;
        $iso = get_post_modified_time('c', true);
        foreach ($graphs as &$g) {
            if (!empty($g['@type']) && in_array($g['@type'], ['WebPage','Article','QAPage'], true)) {
                $g['dateModified'] = $iso;
            }
        }
        return $graphs;
    }
}
