<?php
/**
 * STB Theme — Dynamic Sitemap Generator
 * Serves sitemap.xml (index) and per-type sub-sitemaps under /stb-sitemap-*.xml.
 *
 * URLs:
 *   /sitemap.xml                  → index
 *   /stb-sitemap-pages.xml        → all WP pages
 *   /stb-sitemap-posts.xml        → all blog posts
 *   /stb-sitemap-encyclopedia.xml → all encyclopedia terms
 *
 * Each entry includes xhtml:link hreflang for EN/FA/x-default.
 * Disables WP core sitemap.
 *
 * @package STB
 */

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

// Kill core WP sitemap
add_filter('wp_sitemaps_enabled', '__return_false');

/**
 * Register rewrite rules and serve XML.
 */
add_action('init', function () {
    add_rewrite_rule('^sitemap\.xml$',                 'index.php?stb_sitemap=index',        'top');
    add_rewrite_rule('^stb-sitemap-pages\.xml$',       'index.php?stb_sitemap=pages',        'top');
    add_rewrite_rule('^stb-sitemap-posts\.xml$',       'index.php?stb_sitemap=posts',        'top');
    add_rewrite_rule('^stb-sitemap-encyclopedia\.xml$','index.php?stb_sitemap=encyclopedia', 'top');
});

add_filter('query_vars', function ($vars) {
    $vars[] = 'stb_sitemap';
    return $vars;
});

add_action('template_redirect', function () {
    $key = get_query_var('stb_sitemap');
    if (!$key) return;

    header('Content-Type: application/xml; charset=UTF-8');
    header('X-Robots-Tag: noindex, follow');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";

    switch ($key) {
        case 'index':        stb_sitemap_index();        break;
        case 'pages':        stb_sitemap_pages();        break;
        case 'posts':        stb_sitemap_posts();        break;
        case 'encyclopedia': stb_sitemap_encyclopedia(); break;
        default: status_header(404);
    }
    exit;
});

function stb_sitemap_index() {
    $base = stb_seo_canonical_base();
    $now  = current_time('c');
    echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    foreach (['pages', 'posts', 'encyclopedia'] as $sub) {
        printf("  <sitemap>\n    <loc>%s/stb-sitemap-%s.xml</loc>\n    <lastmod>%s</lastmod>\n  </sitemap>\n",
            esc_url($base), esc_attr($sub), esc_attr($now));
    }
    echo '</sitemapindex>';
}

function stb_sitemap_pages() {
    $pages = get_posts([
        'post_type'      => 'page',
        'post_status'    => 'publish',
        'numberposts'    => -1,
        'orderby'        => 'menu_order',
        'order'          => 'ASC',
    ]);

    stb_sitemap_urlset_open();

    // Front page
    $base = stb_seo_canonical_base();
    stb_sitemap_url_entry($base . '/', current_time('c'), '1.0', 'daily');

    foreach ($pages as $p) {
        $url  = get_permalink($p->ID);
        $mod  = get_post_modified_time('c', false, $p);
        $prio = '0.7';
        $freq = 'weekly';

        $important = ['home','trading-accounts','markets','platforms','execution','pamm','copy-trading','ib','affiliate','academy','encyclopedia','company','contact'];
        if (in_array($p->post_name, $important, true)) {
            $prio = '0.9';
        }
        $excluded = ['sample-page'];
        if (in_array($p->post_name, $excluded, true)) continue;

        stb_sitemap_url_entry($url, $mod, $prio, $freq);
    }

    stb_sitemap_urlset_close();
}

function stb_sitemap_posts() {
    $posts = get_posts([
        'post_type'   => 'post',
        'post_status' => 'publish',
        'numberposts' => -1,
    ]);

    stb_sitemap_urlset_open();
    foreach ($posts as $p) {
        stb_sitemap_url_entry(
            get_permalink($p->ID),
            get_post_modified_time('c', false, $p),
            '0.6',
            'weekly'
        );
    }
    stb_sitemap_urlset_close();
}

function stb_sitemap_encyclopedia() {
    $terms = get_posts([
        'post_type'   => 'stb_encyclopedia',
        'post_status' => 'publish',
        'numberposts' => -1,
    ]);

    stb_sitemap_urlset_open();
    foreach ($terms as $p) {
        stb_sitemap_url_entry(
            get_permalink($p->ID),
            get_post_modified_time('c', false, $p),
            '0.6',
            'monthly'
        );
    }
    stb_sitemap_urlset_close();
}

function stb_sitemap_urlset_open() {
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
    echo '        xmlns:xhtml="http://www.w3.org/1999/xhtml">' . "\n";
}
function stb_sitemap_urlset_close() {
    echo '</urlset>';
}

/**
 * Emit a <url> element with xhtml:link hreflang variants.
 */
function stb_sitemap_url_entry($url, $lastmod, $priority, $changefreq) {
    // Compute EN (no lang param) + FA (lang=fa) URLs from base path
    $base_url = preg_replace('/[?&]lang=fa/', '', $url);
    $base_url = preg_replace('/\?$/', '', $base_url);
    $en_url   = $base_url;
    $fa_url   = add_query_arg('lang', 'fa', $base_url);

    echo "  <url>\n";
    printf("    <loc>%s</loc>\n", esc_url($en_url));
    printf("    <lastmod>%s</lastmod>\n", esc_attr($lastmod));
    printf("    <changefreq>%s</changefreq>\n", esc_attr($changefreq));
    printf("    <priority>%s</priority>\n", esc_attr($priority));
    printf("    <xhtml:link rel=\"alternate\" hreflang=\"en\" href=\"%s\"/>\n", esc_url($en_url));
    printf("    <xhtml:link rel=\"alternate\" hreflang=\"fa\" href=\"%s\"/>\n", esc_url($fa_url));
    printf("    <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\"%s\"/>\n", esc_url($en_url));
    echo "  </url>\n";
}

/**
 * Inject sitemap line into the virtual robots.txt (in case no static one).
 */
add_filter('robots_txt', function ($output, $public) {
    if (!$public) return $output;
    $base = stb_seo_canonical_base();
    $extra  = "\n";
    $extra .= "Disallow: /wp-admin/\n";
    $extra .= "Disallow: /wp-content/plugins/\n";
    $extra .= "Disallow: /?s=\n";
    $extra .= "\n# AI crawlers\n";
    foreach (['GPTBot','ClaudeBot','OAI-SearchBot','PerplexityBot','Google-Extended','Applebot-Extended','CCBot'] as $ua) {
        $extra .= "User-agent: {$ua}\nAllow: /\n\n";
    }
    $extra .= "Sitemap: {$base}/sitemap.xml\n";
    return $output . $extra;
}, 10, 2);
