<?php
// sitemap.php — dynamic XML sitemap for Google & Bing
require 'config.php';

header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noindex');   // don't index the sitemap itself in SERPs

$baseUrl = 'https://genz-drip.shop';

// ---------- Static pages ----------
$staticPages = [
    ['loc' => '/',              'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => '/about.php',     'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => '/contact.php',   'priority' => '0.7', 'changefreq' => 'monthly'],
    ['loc' => '/shipping.php',  'priority' => '0.5', 'changefreq' => 'yearly'],
    ['loc' => '/returns.php',   'priority' => '0.5', 'changefreq' => 'yearly'],
    ['loc' => '/privacy.php',   'priority' => '0.4', 'changefreq' => 'yearly'],
    ['loc' => '/terms.php',     'priority' => '0.4', 'changefreq' => 'yearly'],
];

// ---------- Products ----------
$products = [];
try {
    $stmt = $pdo->query("
        SELECT id, name, created_at
        FROM tbl_product
        WHERE is_show = 1
        ORDER BY id ASC
    ");
    $products = $stmt->fetchAll();
} catch (Throwable $e) {
    error_log('[sitemap] Product query failed: ' . $e->getMessage());
}

// Fallback lastmod — if the DB has 0000-00-00 for older rows
$fallbackDate = date('Y-m-d');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// Static URLs
foreach ($staticPages as $page) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($baseUrl . $page['loc'], ENT_XML1) . "</loc>\n";
    echo "    <changefreq>" . $page['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $page['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// Product URLs
foreach ($products as $p) {
    $raw = $p['created_at'] ?? '';
    $lastmod = ($raw && $raw !== '0000-00-00 00:00:00')
        ? date('Y-m-d', strtotime($raw))
        : $fallbackDate;

    $url = $baseUrl . '/product.php?id=' . (int)$p['id'];

    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($url, ENT_XML1) . "</loc>\n";
    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>0.8</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>' . "\n";