<?php
// generate-sitemap.php - Dynamic Sitemap Generator
// Version: 8.8.8-vine
// Copyright: Prime Gateway Academy | VineSub Tech
// Developer: Emmanuel Abimbola (Lead Developer)

require_once 'config.php';
require_once __DIR__ . '/includes/seo.php';

// Only allow admin access when run via browser
if (php_sapi_name() !== 'cli') {
    requireAdmin();
}

/**
 * Generate the complete sitemap
 * @param bool $output_directly Whether to output directly or return XML string
 * @return string|bool XML content or true/false if saved
 */
function generateSitemap($output_directly = false) {
    global $db;
    
    try {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">' . "\n";
        
        // =============================================
        // 1. STATIC PAGES
        // =============================================
        $static_pages = [
            ['url' => '', 'priority' => '1.0', 'changefreq' => 'daily', 'title' => 'Home'],
            ['url' => 'about', 'priority' => '0.9', 'changefreq' => 'monthly', 'title' => 'About Us'],
            ['url' => 'products', 'priority' => '0.9', 'changefreq' => 'daily', 'title' => 'Products'],
            ['url' => 'services', 'priority' => '0.9', 'changefreq' => 'daily', 'title' => 'Services'],
            ['url' => 'blog', 'priority' => '0.9', 'changefreq' => 'daily', 'title' => 'Blog'],
            ['url' => 'stories', 'priority' => '0.9', 'changefreq' => 'daily', 'title' => 'Stories'],
            ['url' => 'subscriptions', 'priority' => '0.8', 'changefreq' => 'weekly', 'title' => 'Subscriptions'],
            ['url' => 'tips', 'priority' => '0.8', 'changefreq' => 'weekly', 'title' => 'Support'],
            ['url' => 'contact', 'priority' => '0.8', 'changefreq' => 'monthly', 'title' => 'Contact'],
            ['url' => 'faq', 'priority' => '0.7', 'changefreq' => 'monthly', 'title' => 'FAQ'],
            ['url' => 'privacy', 'priority' => '0.5', 'changefreq' => 'yearly', 'title' => 'Privacy Policy'],
            ['url' => 'terms', 'priority' => '0.5', 'changefreq' => 'yearly', 'title' => 'Terms of Service'],
            ['url' => 'refund', 'priority' => '0.5', 'changefreq' => 'yearly', 'title' => 'Refund Policy'],
        ];
        
        foreach ($static_pages as $page) {
            $xml .= '  <url>' . "\n";
            $xml .= '    <loc>' . htmlspecialchars(SITE_URL . ($page['url'] ? $page['url'] . '.php' : 'index.php')) . '</loc>' . "\n";
            $xml .= '    <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
            $xml .= '    <changefreq>' . $page['changefreq'] . '</changefreq>' . "\n";
            $xml .= '    <priority>' . $page['priority'] . '</priority>' . "\n";
            $xml .= '  </url>' . "\n";
        }
        
        // =============================================
        // 2. PRODUCTS
        // =============================================
        try {
            $stmt = $db->prepare("SELECT id, slug, title, description, image_url, product_images, updated_at FROM products WHERE status = 1");
            $stmt->execute();
            $products = $stmt->fetchAll();
            
            foreach ($products as $product) {
                $slug = !empty($product['slug']) ? $product['slug'] : $product['id'];
                $url = SITE_URL . 'products/' . $slug;
                $lastmod = date('Y-m-d', strtotime($product['updated_at'] ?? 'now'));
                
                // Get product images
                $images = [];
                if (!empty($product['image_url'])) {
                    $images[] = $product['image_url'];
                }
                if (!empty($product['product_images'])) {
                    $product_images = json_decode($product['product_images'], true);
                    if (is_array($product_images)) {
                        foreach ($product_images as $img) {
                            if (filter_var($img, FILTER_VALIDATE_URL)) {
                                $images[] = $img;
                            }
                        }
                    }
                }
                
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
                $xml .= '    <changefreq>weekly</changefreq>' . "\n";
                $xml .= '    <priority>0.8</priority>' . "\n";
                
                // Add images
                foreach (array_slice($images, 0, 5) as $img) {
                    if (!empty($img)) {
                        $xml .= '    <image:image>' . "\n";
                        $xml .= '      <image:loc>' . htmlspecialchars($img) . '</image:loc>' . "\n";
                        $xml .= '      <image:title>' . htmlspecialchars($product['title']) . '</image:title>' . "\n";
                        $xml .= '    </image:image>' . "\n";
                    }
                }
                
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        // =============================================
        // 3. SERVICES
        // =============================================
        try {
            $stmt = $db->prepare("SELECT id, slug, title, description, featured_image, updated_at FROM services WHERE status = 1");
            $stmt->execute();
            $services = $stmt->fetchAll();
            
            foreach ($services as $service) {
                $slug = !empty($service['slug']) ? $service['slug'] : $service['id'];
                $url = SITE_URL . 'services/' . $slug;
                $lastmod = date('Y-m-d', strtotime($service['updated_at'] ?? 'now'));
                
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
                $xml .= '    <changefreq>weekly</changefreq>' . "\n";
                $xml .= '    <priority>0.8</priority>' . "\n";
                
                if (!empty($service['featured_image'])) {
                    $xml .= '    <image:image>' . "\n";
                    $xml .= '      <image:loc>' . htmlspecialchars($service['featured_image']) . '</image:loc>' . "\n";
                    $xml .= '      <image:title>' . htmlspecialchars($service['title']) . '</image:title>' . "\n";
                    $xml .= '    </image:image>' . "\n";
                }
                
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        // =============================================
        // 4. BLOG POSTS
        // =============================================
        try {
            $stmt = $db->prepare("SELECT id, slug, title, excerpt, feature_image, updated_at FROM blog_posts WHERE is_published = 1");
            $stmt->execute();
            $posts = $stmt->fetchAll();
            
            foreach ($posts as $post) {
                $slug = !empty($post['slug']) ? $post['slug'] : $post['id'];
                $url = SITE_URL . 'blog/' . $slug;
                $lastmod = date('Y-m-d', strtotime($post['updated_at'] ?? 'now'));
                
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
                $xml .= '    <changefreq>weekly</changefreq>' . "\n";
                $xml .= '    <priority>0.7</priority>' . "\n";
                
                // News article metadata
                if (!empty($post['title'])) {
                    $xml .= '    <news:news>' . "\n";
                    $xml .= '      <news:publication>' . "\n";
                    $xml .= '        <news:name>' . htmlspecialchars(getSetting('site_name', 'Prime Gateway Academy')) . '</news:name>' . "\n";
                    $xml .= '        <news:language>en</news:language>' . "\n";
                    $xml .= '      </news:publication>' . "\n";
                    $xml .= '      <news:publication_date>' . date('Y-m-d\TH:i:sO', strtotime($post['updated_at'] ?? 'now')) . '</news:publication_date>' . "\n";
                    $xml .= '      <news:title>' . htmlspecialchars($post['title']) . '</news:title>' . "\n";
                    $xml .= '    </news:news>' . "\n";
                }
                
                if (!empty($post['feature_image'])) {
                    $xml .= '    <image:image>' . "\n";
                    $xml .= '      <image:loc>' . htmlspecialchars($post['feature_image']) . '</image:loc>' . "\n";
                    $xml .= '      <image:title>' . htmlspecialchars($post['title']) . '</image:title>' . "\n";
                    $xml .= '    </image:image>' . "\n";
                }
                
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        // =============================================
        // 5. STORIES
        // =============================================
        try {
            $stmt = $db->prepare("SELECT id, slug, title, excerpt, feature_image, updated_at FROM stories WHERE status = 'published'");
            $stmt->execute();
            $stories = $stmt->fetchAll();
            
            foreach ($stories as $story) {
                $slug = !empty($story['slug']) ? $story['slug'] : $story['id'];
                $url = SITE_URL . 'stories/' . $slug;
                $lastmod = date('Y-m-d', strtotime($story['updated_at'] ?? 'now'));
                
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
                $xml .= '    <changefreq>weekly</changefreq>' . "\n";
                $xml .= '    <priority>0.8</priority>' . "\n";
                
                if (!empty($story['feature_image'])) {
                    $xml .= '    <image:image>' . "\n";
                    $xml .= '      <image:loc>' . htmlspecialchars($story['feature_image']) . '</image:loc>' . "\n";
                    $xml .= '      <image:title>' . htmlspecialchars($story['title']) . '</image:title>' . "\n";
                    $xml .= '    </image:image>' . "\n";
                }
                
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        // =============================================
        // 6. STORY CHAPTERS
        // =============================================
        try {
            $stmt = $db->prepare("
                SELECT c.id, c.chapter_number, c.title, c.created_at, c.updated_at, s.slug as story_slug, s.id as story_id 
                FROM story_chapters c
                JOIN stories s ON c.story_id = s.id
                WHERE s.status = 'published'
            ");
            $stmt->execute();
            $chapters = $stmt->fetchAll();
            
            foreach ($chapters as $chapter) {
                $story_slug = !empty($chapter['story_slug']) ? $chapter['story_slug'] : $chapter['story_id'];
                $url = SITE_URL . 'stories/' . $story_slug . '/chapter-' . $chapter['chapter_number'];
                $lastmod = date('Y-m-d', strtotime($chapter['updated_at'] ?? $chapter['created_at'] ?? 'now'));
                
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
                $xml .= '    <changefreq>weekly</changefreq>' . "\n";
                $xml .= '    <priority>0.7</priority>' . "\n";
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        // =============================================
        // 7. CATEGORIES
        // =============================================
        try {
            $stmt = $db->prepare("SELECT id, name, slug FROM categories WHERE status = 1");
            $stmt->execute();
            $categories = $stmt->fetchAll();
            
            foreach ($categories as $category) {
                $url = SITE_URL . 'blog/category/' . $category['slug'];
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
                $xml .= '    <changefreq>monthly</changefreq>' . "\n";
                $xml .= '    <priority>0.6</priority>' . "\n";
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        // =============================================
        // 8. GENRES (for stories)
        // =============================================
        try {
            $stmt = $db->prepare("SELECT id, name, slug FROM story_genres WHERE is_active = 1");
            $stmt->execute();
            $genres = $stmt->fetchAll();
            
            foreach ($genres as $genre) {
                $url = SITE_URL . 'stories.php?genre=' . $genre['slug'];
                $xml .= '  <url>' . "\n";
                $xml .= '    <loc>' . htmlspecialchars($url) . '</loc>' . "\n";
                $xml .= '    <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
                $xml .= '    <changefreq>monthly</changefreq>' . "\n";
                $xml .= '    <priority>0.5</priority>' . "\n";
                $xml .= '  </url>' . "\n";
            }
        } catch(Exception $e) {
            // Silently handle
        }
        
        $xml .= '</urlset>';
        
        // Save to file
        $file_path = __DIR__ . '/sitemap.xml';
        if (file_put_contents($file_path, $xml)) {
            chmod($file_path, 0644);
            
            if ($output_directly) {
                header('Content-Type: application/xml');
                echo $xml;
                exit;
            }
            
            return true;
        }
        
        return false;
        
    } catch(Exception $e) {
        error_log("Sitemap generation error: " . $e->getMessage());
        return false;
    }
}

// =============================================
// EXECUTE
// =============================================

// If called directly via browser
if (php_sapi_name() !== 'cli') {
    $action = $_GET['action'] ?? 'generate';
    
    if ($action === 'view') {
        // View the sitemap
        $sitemap_path = __DIR__ . '/sitemap.xml';
        if (file_exists($sitemap_path)) {
            header('Content-Type: application/xml');
            readfile($sitemap_path);
            exit;
        } else {
            // Generate and then show
            generateSitemap(true);
        }
    } elseif ($action === 'generate') {
        // Generate new sitemap
        $result = generateSitemap();
        if ($result) {
            echo '<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; background: #10b981; color: white; border-radius: 8px; text-align: center;">';
            echo '<h1>✅ Sitemap Generated Successfully!</h1>';
            echo '<p>The sitemap has been updated and is now available at:</p>';
            echo '<p><a href="/sitemap.xml" target="_blank" style="color: white; text-decoration: underline;">/sitemap.xml</a></p>';
            echo '<p style="margin-top: 20px; font-size: 14px; opacity: 0.8;">Last updated: ' . date('Y-m-d H:i:s') . '</p>';
            echo '</div>';
        } else {
            echo '<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; background: #ef4444; color: white; border-radius: 8px; text-align: center;">';
            echo '<h1>❌ Failed to Generate Sitemap</h1>';
            echo '<p>Please check error logs for more information.</p>';
            echo '</div>';
        }
    } else {
        echo '<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; background: #f59e0b; color: white; border-radius: 8px; text-align: center;">';
        echo '<h1>🔧 Sitemap Generator</h1>';
        echo '<p style="margin: 20px 0;">Generate a fresh sitemap for your website.</p>';
        echo '<a href="?action=generate" style="display: inline-block; background: #3b82f6; color: white; padding: 10px 30px; border-radius: 5px; text-decoration: none; margin: 10px 5px;">Generate Sitemap</a>';
        echo '<a href="?action=view" style="display: inline-block; background: #10b981; color: white; padding: 10px 30px; border-radius: 5px; text-decoration: none; margin: 10px 5px;">View Sitemap</a>';
        echo '</div>';
    }
    exit;
}

// If called from CLI, just generate silently
generateSitemap();
echo "Sitemap generated successfully!\n";