<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-seo-sitemap.php
// Description: Dynamic XML sitemap — posts, pages, products, auto-updated - NUCLEAR+++
// Last Edited: 2026-04-23
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

class SeoSitemap
{
    private const QUERY_VAR = 'amai_sitemap';

    // --------------------------------------------------
    // Register hooks
    // --------------------------------------------------
    public static function register(): void
    {
        add_action('init',             [self::class, 'addRewriteRule']);
        add_filter('query_vars',       [self::class, 'addQueryVar']);
        add_action('template_redirect',[self::class, 'maybeServe']);
    }

    // --------------------------------------------------
    // Add rewrite rule for /sitemap.xml
    // --------------------------------------------------
    public static function addRewriteRule(): void
    {
        add_rewrite_rule('^sitemap\.xml$', 'index.php?' . self::QUERY_VAR . '=1', 'top');
    }

    // --------------------------------------------------
    // Register query var
    // --------------------------------------------------
    public static function addQueryVar(array $vars): array
    {
        $vars[] = self::QUERY_VAR;
        return $vars;
    }

    // --------------------------------------------------
    // Serve sitemap if query var is set
    // --------------------------------------------------
    public static function maybeServe(): void
    {
        if ((int) get_query_var(self::QUERY_VAR, 0) !== 1) {
            return;
        }

        // Bypass coming-soon redirect for sitemap
        self::serve();
        exit;
    }

    // --------------------------------------------------
    // Build and output the XML sitemap
    // --------------------------------------------------
    private static function serve(): void
    {
        $urls = [];

        // Homepage
        $urls[] = [
            'loc'        => home_url('/'),
            'lastmod'    => gmdate('c'),
            'changefreq' => 'daily',
            'priority'   => '1.0',
        ];

        // Public post types to include
        $post_types = ['post', 'page'];
        if (post_type_exists('product')) {
            $post_types[] = 'product';
        }

        // Pages to exclude — WP utility pages and marketing virtual routes
        $excluded_slugs = [
            'coming-soon',
            'cart',
            'checkout',
            'my-account',
            'order-received',
            'get-started',
        ];

        foreach ($post_types as $post_type) {
            $posts = get_posts([
                'post_type'      => $post_type,
                'post_status'    => 'publish',
                'posts_per_page' => -1,
                'no_found_rows'  => true,
                'fields'         => 'all',
            ]);

            foreach ($posts as $post) {
                if (!$post instanceof \WP_Post) {
                    continue;
                }
                if (in_array($post->post_name, $excluded_slugs, true)) {
                    continue;
                }

                $permalink = get_permalink($post->ID);
                if ($permalink === false) {
                    continue;
                }

                // Check robots meta — skip noindex posts
                $robots = SeoData::get($post->ID, 'robots');
                if ($robots !== null && str_contains($robots, 'noindex')) {
                    continue;
                }

                // Use canonical URL if set
                $canonical = SeoData::get($post->ID, 'canonical_url');
                $loc       = ($canonical !== null && $canonical !== '') ? $canonical : $permalink;

                $lastmod  = gmdate('c', strtotime($post->post_modified_gmt));
                $priority = match ($post_type) {
                    'page'    => '0.8',
                    'product' => '0.9',
                    default   => '0.7',
                };

                $urls[] = [
                    'loc'        => $loc,
                    'lastmod'    => $lastmod,
                    'changefreq' => 'weekly',
                    'priority'   => $priority,
                ];
            }
        }

        header('Content-Type: application/xml; charset=utf-8');
        header('X-Robots-Tag: noindex');
        header('Cache-Control: public, max-age=3600');

        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

        foreach ($urls as $url) {
            echo "\t<url>\n";
            echo "\t\t<loc>" . esc_url($url['loc']) . "</loc>\n";
            echo "\t\t<lastmod>" . esc_html($url['lastmod']) . "</lastmod>\n";
            echo "\t\t<changefreq>" . esc_html($url['changefreq']) . "</changefreq>\n";
            echo "\t\t<priority>" . esc_html($url['priority']) . "</priority>\n";
            echo "\t</url>\n";
        }

        echo '</urlset>';
    }

    // --------------------------------------------------
    // Flush rewrite rules on activation — call from plugin activate hook
    // --------------------------------------------------
    public static function flushRewrites(): void
    {
        self::addRewriteRule();
        flush_rewrite_rules();
    }
}