<?php
/**
 * Dynamic XML Sitemap Generator
 * Generates sitemap for products, blogs, categories, and static pages
 * Place this file at: /sitemap.php
 * Access at: yoursite.com/sitemap.php or yoursite.com/sitemap.xml
 */

// Set header to XML
header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: max-age=86400'); // Cache for 24 hours

// Get base URL
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
$baseURL = $protocol . '://' . $_SERVER['SERVER_NAME'];

// Load products
$dataDir = __DIR__ . '/data';
$productsList = [];
$categories = [];
$blogs = [];

if (file_exists($dataDir . '/products.json')) {
    $productsList = json_decode(file_get_contents($dataDir . '/products.json'), true) ?: [];
}

if (file_exists($dataDir . '/categories.json')) {
    $categories = json_decode(file_get_contents($dataDir . '/categories.json'), true) ?: [];
}

// Try to get blogs from database
try {
    require_once __DIR__ . '/db_config.php';
    require_once __DIR__ . '/blog_helpers.php';
    if (isset($conn) && $conn) {
        $blogs = getBlogs($conn, ['limit' => 1000, 'order' => 'b.publish_date DESC']);
    }
} catch (Exception $e) {
    // Fallback if database connection fails
}

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

// Static pages with priority
$staticPages = [
    ['url' => '', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['url' => 'shop.php', 'priority' => '0.9', 'changefreq' => 'daily'],
    ['url' => 'blogs.php', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['url' => 'about.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['url' => 'contact.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['url' => 'cart.php', 'priority' => '0.5', 'changefreq' => 'weekly'],
];

// Add static pages
foreach ($staticPages as $page) {
    $url = $baseURL . '/' . $page['url'];
    $date = date('Y-m-d');
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
    echo "    <lastmod>$date</lastmod>\n";
    echo "    <changefreq>" . $page['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $page['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// Add categories
foreach ($categories as $category) {
    if (!empty($category['id']) && !empty($category['name'])) {
        $catSlug = strtolower(str_replace([' ', '&', '/'], ['-', 'and', '-'], $category['name']));
        $catSlug = preg_replace('/[^a-z0-9-]/', '', $catSlug);
        $catSlug = preg_replace('/-+/', '-', $catSlug);
        
        $url = $baseURL . '/category.php?id=' . urlencode($category['id']);
        $date = date('Y-m-d');
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
        echo "    <lastmod>$date</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.8</priority>\n";
        echo "  </url>\n";
    }
}

// Add products
foreach ($productsList as $product) {
    if (!empty($product['id']) && !empty($product['title'])) {
        $productSlug = strtolower(str_replace([' ', '&', '/'], ['-', 'and', '-'], $product['title']));
        $productSlug = preg_replace('/[^a-z0-9-]/', '', $productSlug);
        $productSlug = preg_replace('/-+/', '-', $productSlug);
        $productSlug = trim($productSlug, '-');
        
        $url = $baseURL . '/product.php?id=' . urlencode($product['id']);
        $date = date('Y-m-d', strtotime($product['updated'] ?? date('Y-m-d')));
        
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
        echo "    <lastmod>$date</lastmod>\n";
        echo "    <changefreq>weekly</changefreq>\n";
        echo "    <priority>0.7</priority>\n";
        
        // Add product images to sitemap
        if (!empty($product['image'])) {
            $imageUrl = $baseURL . '/' . $product['image'];
            echo "    <image:image>\n";
            echo "      <image:loc>" . htmlspecialchars($imageUrl) . "</image:loc>\n";
            echo "      <image:title>" . htmlspecialchars($product['title']) . "</image:title>\n";
            echo "    </image:image>\n";
        }
        
        echo "  </url>\n";
    }
}

// Add blogs
foreach ($blogs as $blog) {
    if (!empty($blog['slug'])) {
        $url = $baseURL . '/blog.php?slug=' . urlencode($blog['slug']);
        $date = date('Y-m-d', strtotime($blog['publish_date'] ?? $blog['created_at']));
        
        echo "  <url>\n";
        echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
        echo "    <lastmod>$date</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.7</priority>\n";
        
        // Add blog featured image if exists
        if (!empty($blog['featured_image'])) {
            $imageUrl = $baseURL . '/uploads/blog/' . $blog['featured_image'];
            echo "    <image:image>\n";
            echo "      <image:loc>" . htmlspecialchars($imageUrl) . "</image:loc>\n";
            echo "      <image:title>" . htmlspecialchars($blog['title']) . "</image:title>\n";
            echo "    </image:image>\n";
        }
        
        echo "  </url>\n";
    }
}

echo "</urlset>\n";
?>
