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

class SS_Org_Sync {

    const OPT = 'ss_org_sync'; // stores: name, url, logo_url, email, sitemap_url

    public static function init() {
        // If neither Yoast nor Rank Math is active, print our own Organization JSON-LD
        if ( ! defined('WPSEO_VERSION') && ! class_exists('RankMath') ) {
            add_action('wp_head', [__CLASS__, 'print_org_jsonld'], 90);
        }

        // Yoast: enrich org (do not overwrite fields Yoast already has)
        add_filter('wpseo_schema_organization', [__CLASS__, 'yoast_org'], 20, 1);

        // Rank Math: enrich org (works with their JSON-LD array)
        add_filter('rank_math/json_ld', [__CLASS__, 'rankmath_org'], 99, 3);
    }

    /** Read settings with WP-derived defaults */
    private static function get() : array {
        $opt = (array) get_option(self::OPT, []);
        $name = trim($opt['name'] ?? get_bloginfo('name'));
        $url  = esc_url_raw( $opt['url'] ?? home_url('/') );
        $email= sanitize_email( $opt['email'] ?? get_option('admin_email') );
        $logo = esc_url_raw( $opt['logo_url'] ?? self::detect_logo_url() );
        $map  = esc_url_raw( $opt['sitemap_url'] ?? self::detect_sitemap_url() );
        return compact('name','url','email','logo','map');
    }

    private static function detect_logo_url() : string {
        $id = (int) get_theme_mod('custom_logo');
        if ($id) {
            $src = wp_get_attachment_image_src($id, 'full');
            if (!empty($src[0])) return esc_url_raw($src[0]);
        }
        $icon = get_site_icon_url(512);
        return $icon ? esc_url_raw($icon) : '';
    }

    private static function detect_sitemap_url() : string {
        if (defined('WPSEO_VERSION') || class_exists('RankMath')) return home_url('/sitemap_index.xml');
        if (function_exists('wp_sitemaps_get_server')) return home_url('/wp-sitemap.xml');
        return home_url('/sitemap.xml');
    }

    /** Standalone JSON-LD when no SEO plugin handles Organization */
    public static function print_org_jsonld() {
        $o = self::get();
        $graph = [
            '@context' => 'https://schema.org',
            '@type'    => 'Organization',
            'name'     => $o['name'],
            'url'      => $o['url'],
        ];
        if ($o['logo']) {
            $graph['logo'] = [
                '@type' => 'ImageObject',
                'url'   => $o['logo'],
            ];
        }
        if ($o['email']) {
            $graph['contactPoint'][] = [
                '@type'       => 'ContactPoint',
                'email'       => $o['email'],
                'contactType' => 'customer support',
            ];
        }
        echo "\n<script type=\"application/ld+json\">".wp_json_encode($graph, JSON_UNESCAPED_SLASHES)."</script>\n";
    }

    /** Yoast bridge: fill only missing fields */
    public static function yoast_org($data){
        $o = self::get();
        if (empty($data['name']) && $o['name']) $data['name'] = $o['name'];
        if (empty($data['url'])  && $o['url'])  $data['url']  = $o['url'];

        if (empty($data['logo']) && $o['logo']) {
            $data['logo'] = ['@type'=>'ImageObject','url'=>$o['logo']];
        }

        if (empty($data['contactPoint']) && $o['email']) {
            $data['contactPoint'] = [[
                '@type'=>'ContactPoint','email'=>$o['email'],'contactType'=>'customer support'
            ]];
        }
        return $data;
    }

    /** Rank Math bridge: add or enrich Organization */
    public static function rankmath_org($data, $jsonld, $type){
        $o = self::get();

        // If Rank Math already has Organization, enrich it
        if (isset($data['Organization']) && is_array($data['Organization'])) {
            $org =& $data['Organization'];
            if (empty($org['name']) && $o['name']) $org['name'] = $o['name'];
            if (empty($org['url'])  && $o['url'])  $org['url']  = $o['url'];
            if (empty($org['logo']) && $o['logo']) $org['logo'] = ['@type'=>'ImageObject','url'=>$o['logo']];
            if (empty($org['contactPoint']) && $o['email']) {
                $org['contactPoint'] = [[ '@type'=>'ContactPoint','email'=>$o['email'],'contactType'=>'customer support' ]];
            }
            return $data;
        }

        // Otherwise inject a minimal Organization piece (Rank Math-compatible)
        $org = [
            '@type' => 'Organization',
            'name'  => $o['name'],
            'url'   => $o['url'],
        ];
        if ($o['logo'])  $org['logo'] = ['@type'=>'ImageObject','url'=>$o['logo']];
        if ($o['email']) $org['contactPoint'] = [[ '@type'=>'ContactPoint','email'=>$o['email'],'contactType'=>'customer support' ]];

        $data['Organization'] = $org;
        return $data;
    }
}
