<?php
require_once "functions.php";

/* Set XML Header */
header("Content-Type: application/xml; charset=UTF-8");

$base = "https://" . $_SERVER['HTTP_HOST'] . "/";

/* Fetch Categories */
$cats = $conn->query("SELECT id, name, updated_at FROM categories WHERE status=1 ORDER BY id ASC");

/* Fetch Products */
$products = $conn->query("
    SELECT id, name, updated_at 
    FROM products 
    WHERE status=1 
    ORDER BY id DESC
");

/* Today's date as fallback */
$today = date("Y-m-d");
?>
<?xml version="1.0" encoding="UTF-8"?>
<urlset 
      xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
      xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">

    <!-- HOME PAGE -->
    <url>
        <loc><?= $base ?></loc>
        <lastmod><?= $today ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- CONTACT PAGE -->
    <url>
        <loc><?= $base ?>contact.php</loc>
        <lastmod><?= $today ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>

    <!-- CATEGORIES -->
    <?php while($c = $cats->fetch_assoc()): ?>
    <url>
        <loc><?= $base ?>category.php?id=<?= $c['id'] ?></loc>
        <lastmod><?= $c['updated_at'] ?: $today ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endwhile; ?>

    <!-- PRODUCTS -->
    <?php while($p = $products->fetch_assoc()): ?>
    <url>
        <loc><?= $base ?>product.php?id=<?= $p['id'] ?></loc>
        <lastmod><?= $p['updated_at'] ?: $today ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.9</priority>
    </url>
    <?php endwhile; ?>

</urlset>
