<?php
require_once 'includes/config.php';

header('Content-Type: application/xml; charset=utf-8');

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

// Static pages
$pages = [
    SITE_URL,
    SITE_URL . 'about.php',
    SITE_URL . 'products.php',
    SITE_URL . 'services.php',
    SITE_URL . 'blog.php',
    SITE_URL . 'contact.php',
    SITE_URL . 'privacy-policy.php',
    SITE_URL . 'terms-conditions.php',
    SITE_URL . 'cookie-policy.php',
    SITE_URL . 'disclaimer.php',
    SITE_URL . 'sitemap.php',
];

foreach ($pages as $url) {
    $xml .= '  <url>' . "\n";
    $xml .= '    <loc>' . h($url) . '</loc>' . "\n";
    $xml .= '    <changefreq>monthly</changefreq>' . "\n";
    $xml .= '    <priority>0.8</priority>' . "\n";
    $xml .= '  </url>' . "\n";
}

// Products
$products = db_fetch_all("SELECT slug, updated_at FROM products WHERE status = 'published'");
foreach ($products as $product) {
    $xml .= '  <url>' . "\n";
    $xml .= '    <loc>' . SITE_URL . 'product-details.php?slug=' . h($product['slug']) . '</loc>' . "\n";
    $xml .= '    <lastmod>' . date('Y-m-d', strtotime($product['updated_at'] ?: 'now')) . '</lastmod>' . "\n";
    $xml .= '    <changefreq>weekly</changefreq>' . "\n";
    $xml .= '    <priority>0.9</priority>' . "\n";
    $xml .= '  </url>' . "\n";
}

// Blog posts
$posts = db_fetch_all("SELECT slug, published_at FROM blog_posts WHERE status = 'published'");
foreach ($posts as $post) {
    $xml .= '  <url>' . "\n";
    $xml .= '    <loc>' . SITE_URL . 'blog-details.php?slug=' . h($post['slug']) . '</loc>' . "\n";
    $xml .= '    <lastmod>' . date('Y-m-d', strtotime($post['published_at'])) . '</lastmod>' . "\n";
    $xml .= '    <changefreq>monthly</changefreq>' . "\n";
    $xml .= '    <priority>0.7</priority>' . "\n";
    $xml .= '  </url>' . "\n";
}

// Services
$services = db_fetch_all("SELECT slug, updated_at FROM services WHERE status = 'published'");
foreach ($services as $service) {
    $xml .= '  <url>' . "\n";
    $xml .= '    <loc>' . SITE_URL . 'services.php#service-' . h($service['slug']) . '</loc>' . "\n";
    $xml .= '    <changefreq>monthly</changefreq>' . "\n";
    $xml .= '    <priority>0.6</priority>' . "\n";
    $xml .= '  </url>' . "\n";
}

$xml .= '</urlset>';

// Save to file
file_put_contents(__DIR__ . '/sitemap.xml', $xml);

echo "Sitemap generated successfully.";