<?php
require_once __DIR__ . "/includes/db.php";

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

$base = "https://dizoro.shop";
$today = 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 Pages */
$static = [
  ["loc" => $base . "/",           "freq" => "daily",   "prio" => "1.0"],
  ["loc" => $base . "/products.php","freq" => "daily",  "prio" => "0.9"],
  ["loc" => $base . "/contact.php","freq" => "monthly", "prio" => "0.6"],
  ["loc" => $base . "/policies.php","freq" => "monthly","prio" => "0.5"],
];

foreach($static as $s){
  echo "<url>\n";
  echo "  <loc>{$s['loc']}</loc>\n";
  echo "  <lastmod>{$today}</lastmod>\n";
  echo "  <changefreq>{$s['freq']}</changefreq>\n";
  echo "  <priority>{$s['prio']}</priority>\n";
  echo "</url>\n";
}

/* ✅ Products from DB (Only Active) */
try{
  $stmt = $pdo->query("SELECT id, updated_at, created_at FROM products WHERE status=1 ORDER BY id DESC");
  $products = $stmt->fetchAll(PDO::FETCH_ASSOC);

  foreach($products as $p){
    $pid = (int)$p["id"];

    $last = $p["updated_at"] ?? $p["created_at"] ?? "";
    $last = $last ? date("Y-m-d", strtotime($last)) : $today;

    echo "<url>\n";
    echo "  <loc>{$base}/product.php?id={$pid}</loc>\n";
    echo "  <lastmod>{$last}</lastmod>\n";
    echo "  <changefreq>weekly</changefreq>\n";
    echo "  <priority>0.8</priority>\n";
    echo "</url>\n";
  }
}catch(Exception $e){
  // Silent fail (Production safe)
}

echo "</urlset>";