<?php
/**
 * STB Theme — SEO Meta Injector
 * Injects <title>, meta description, Open Graph, Twitter Cards,
 * canonical and hreflang via wp_head — without touching templates.
 *
 * @package STB
 */

if (!defined('ABSPATH')) exit;

require_once __DIR__ . '/seo-data.php';

/**
 * Site config — single source of truth for SEO URLs.
 * Override by defining STB_CANONICAL_BASE in wp-config.php once domain is live.
 */
function stb_seo_canonical_base() {
    if (defined('STB_CANONICAL_BASE') && STB_CANONICAL_BASE) {
        return rtrim(STB_CANONICAL_BASE, '/');
    }
    return rtrim(home_url('/'), '/');
}

function stb_seo_org_name()     { return 'STB Provider'; }
function stb_seo_org_legal()    { return 'STB Provider LTD'; }

function stb_seo_org_logo_url() {
    return get_template_directory_uri() . '/assets/images/logo.png';
}

function stb_seo_default_og_image() {
    $theme_dir = get_template_directory();
    $theme_uri = get_template_directory_uri();
    foreach (['og-default.jpg', 'og-default.png', 'og.jpg'] as $f) {
        if (file_exists($theme_dir . '/assets/images/' . $f)) {
            return $theme_uri . '/assets/images/' . $f;
        }
    }
    return $theme_uri . '/assets/images/logo.png';
}

/**
 * Build the canonical URL for the current request.
 */
function stb_seo_current_url($lang = null) {
    global $wp;
    $base = stb_seo_canonical_base();
    $req  = isset($wp->request) ? $wp->request : '';
    $path = $req ? ('/' . trim($req, '/') . '/') : '/';

    $url = $base . $path;
    if ($lang === 'fa') {
        $url = add_query_arg('lang', 'fa', $url);
    }
    return $url;
}

/**
 * Disable WP's title tag generation; we render our own.
 */
add_action('after_setup_theme', function () {
    remove_theme_support('title-tag');
}, 99);
remove_action('wp_head', '_wp_render_title_tag', 1);

/** Disable WP's default canonical (we emit our own). */
remove_action('wp_head', 'rel_canonical');

/** Remove WP generator tag. */
remove_action('wp_head', 'wp_generator');

/**
 * Override WP's default robots meta with our value.
 */
add_filter('wp_robots', function ($robots) {
    $val = stb_seo_robots_value();
    $robots = [];
    if (strpos($val, 'noindex') !== false) {
        $robots['noindex'] = true;
    } else {
        $robots['index']  = true;
    }
    $robots['follow'] = true;
    $robots['max-image-preview'] = 'large';
    $robots['max-snippet'] = -1;
    $robots['max-video-preview'] = -1;
    return $robots;
}, 99);

/**
 * Main injector: meta tags + OG + Twitter + canonical + hreflang.
 */
add_action('wp_head', 'stb_render_seo_head', 1);

function stb_render_seo_head() {
    $lang  = function_exists('stb_lang') ? stb_lang() : 'en';
    $entry = stb_get_seo_entry(null, $lang);

    $brand        = stb_seo_org_name();
    $title_text   = isset($entry['title']) && $entry['title'] ? $entry['title'] : (wp_get_document_title() ?: $brand);
    $desc_text    = isset($entry['desc']) && $entry['desc'] ? $entry['desc'] : '';
    $keywords     = isset($entry['keywords']) && $entry['keywords'] ? $entry['keywords'] : '';

    // Apply post-level fallbacks ONLY when seo-data has no entry for this slug.
    // For configured pages, the seo-data values are authoritative.
    $has_configured_entry = !empty($entry['title']) && !empty($entry['desc']);

    if (is_singular() && !$has_configured_entry) {
        $pid = get_the_ID();

        // Description: legacy + Yoast + RankMath, then excerpt fallback
        if (!$desc_text) {
            $candidates = [
                get_post_meta($pid, '_blog_meta_desc', true),
                get_post_meta($pid, '_yoast_wpseo_metadesc', true),
                get_post_meta($pid, 'rank_math_description', true),
            ];
            foreach ($candidates as $c) {
                if ($c) { $desc_text = $c; break; }
            }
            if (!$desc_text) {
                $excerpt = get_the_excerpt();
                if ($excerpt) {
                    $desc_text = wp_strip_all_tags($excerpt);
                } else {
                    $raw = wp_strip_all_tags(get_the_content());
                    $desc_text = wp_trim_words($raw, 30, '…');
                }
            }
        }

        // Title: legacy/Yoast/RankMath, then post title | brand
        $t_candidates = [
            get_post_meta($pid, '_blog_og_title', true),
            get_post_meta($pid, '_yoast_wpseo_title', true),
            get_post_meta($pid, '_yoast_wpseo_opengraph-title', true),
            get_post_meta($pid, 'rank_math_title', true),
            get_post_meta($pid, 'rank_math_facebook_title', true),
        ];
        $found = '';
        foreach ($t_candidates as $c) {
            if ($c) { $found = $c; break; }
        }
        if ($found) {
            $title_text = $found . ' | ' . $brand;
        } else {
            $title_text = get_the_title() . ' | ' . $brand;
        }
    }

    $canonical = stb_seo_current_url($lang);
    $en_url    = stb_seo_current_url('en');
    $fa_url    = stb_seo_current_url('fa');

    $og_image = stb_seo_default_og_image();
    if (is_singular()) {
        $fid = get_post_thumbnail_id();
        if ($fid) {
            $src = wp_get_attachment_image_src($fid, 'full');
            if ($src && $src[0]) $og_image = $src[0];
        }
        $legacy = get_post_meta(get_the_ID(), '_blog_og_image', true);
        if ($legacy) $og_image = $legacy;
    }

    $og_type       = is_singular('post') ? 'article' : 'website';
    $og_locale     = ($lang === 'fa') ? 'fa_IR' : 'en_US';
    $og_locale_alt = ($lang === 'fa') ? 'en_US' : 'fa_IR';

    echo "\n<!-- STB SEO -->\n";
    echo '<title>' . esc_html($title_text) . "</title>\n";

    if ($desc_text) {
        echo '<meta name="description" content="' . esc_attr($desc_text) . "\">\n";
    }
    if ($keywords) {
        echo '<meta name="keywords" content="' . esc_attr($keywords) . "\">\n";
    }

    echo '<link rel="canonical" href="' . esc_url($canonical) . "\">\n";

    echo '<link rel="alternate" hreflang="en" href="' . esc_url($en_url) . "\">\n";
    echo '<link rel="alternate" hreflang="fa" href="' . esc_url($fa_url) . "\">\n";
    echo '<link rel="alternate" hreflang="x-default" href="' . esc_url($en_url) . "\">\n";

    echo '<meta property="og:type" content="' . esc_attr($og_type) . "\">\n";
    echo '<meta property="og:site_name" content="' . esc_attr($brand) . "\">\n";
    echo '<meta property="og:title" content="' . esc_attr($title_text) . "\">\n";
    if ($desc_text) {
        echo '<meta property="og:description" content="' . esc_attr($desc_text) . "\">\n";
    }
    echo '<meta property="og:url" content="' . esc_url($canonical) . "\">\n";
    echo '<meta property="og:image" content="' . esc_url($og_image) . "\">\n";
    echo '<meta property="og:image:width" content="1200">' . "\n";
    echo '<meta property="og:image:height" content="630">' . "\n";
    echo '<meta property="og:locale" content="' . esc_attr($og_locale) . "\">\n";
    echo '<meta property="og:locale:alternate" content="' . esc_attr($og_locale_alt) . "\">\n";

    echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
    echo '<meta name="twitter:title" content="' . esc_attr($title_text) . "\">\n";
    if ($desc_text) {
        echo '<meta name="twitter:description" content="' . esc_attr($desc_text) . "\">\n";
    }
    echo '<meta name="twitter:image" content="' . esc_url($og_image) . "\">\n";

    echo "<!-- /STB SEO -->\n\n";
}

/**
 * Robots policy: noindex for utility pages and search.
 */
function stb_seo_robots_value() {
    if (is_search() || is_404()) return 'noindex, follow';

    $noindex_slugs = ['sample-page'];
    if (is_singular()) {
        $slug = get_post()->post_name ?? '';
        if (in_array($slug, $noindex_slugs, true)) {
            return 'noindex, follow';
        }
    }
    return 'index, follow';
}

/**
 * Ensure <html> has lang + dir attrs aligned with current language.
 */
add_filter('language_attributes', function ($output) {
    $lang   = function_exists('stb_lang') ? stb_lang() : 'en';
    $is_rtl = function_exists('stb_is_rtl_lang') ? stb_is_rtl_lang() : ($lang === 'fa');
    $code   = $lang === 'fa' ? 'fa-IR' : 'en-US';
    $dir    = $is_rtl ? 'rtl' : 'ltr';
    return 'lang="' . esc_attr($code) . '" dir="' . esc_attr($dir) . '"';
}, 20);
