<?php
/**
 * sitemap.xml.php
 * Dynamic XML sitemap for SEO
 */
require_once __DIR__ . '/api/core/db.php';

header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: public, max-age=86400');

$base = 'https://mitraekacatur.com';

$staticPages = [
    ['loc' => $base . '/',                  'priority' => '1.0',  'changefreq' => 'weekly'],
    ['loc' => $base . '/?p=about',          'priority' => '0.7',  'changefreq' => 'monthly'],
    ['loc' => $base . '/?p=services',       'priority' => '0.9',  'changefreq' => 'monthly'],
    ['loc' => $base . '/?p=projects',       'priority' => '0.9',  'changefreq' => 'weekly'],
    ['loc' => $base . '/?p=blogs',          'priority' => '0.8',  'changefreq' => 'daily'],
    ['loc' => $base . '/?p=contact',        'priority' => '0.7',  'changefreq' => 'monthly'],
    ['loc' => $base . '/?p=service-details&service=mechanical', 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => $base . '/?p=service-details&service=electrical', 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => $base . '/?p=service-details&service=plumbing',   'priority' => '0.8', 'changefreq' => 'monthly'],
    ['loc' => $base . '/?p=service-details&service=bms',        'priority' => '0.8', 'changefreq' => 'monthly'],
];

// Dynamic: blogs
$blogs = dbFetchAll("SELECT slug, updated_at FROM blogs WHERE status = 'published' ORDER BY published_at DESC");

// Dynamic: projects
$projects = dbFetchAll("SELECT slug, updated_at FROM projects WHERE status = 'published' ORDER BY published_at DESC");

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <?php foreach ($staticPages as $page): ?>
  <url>
    <loc><?= htmlspecialchars($page['loc']) ?></loc>
    <changefreq><?= $page['changefreq'] ?></changefreq>
    <priority><?= $page['priority'] ?></priority>
    <lastmod><?= date('Y-m-d') ?></lastmod>
  </url>
  <?php endforeach; ?>

  <?php foreach ($blogs as $b): ?>
  <url>
    <loc><?= htmlspecialchars("{$base}/?p=blog-details&slug={$b['slug']}") ?></loc>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
    <lastmod><?= date('Y-m-d', strtotime($b['updated_at'] ?? 'now')) ?></lastmod>
  </url>
  <?php endforeach; ?>

  <?php foreach ($projects as $proj): ?>
  <url>
    <loc><?= htmlspecialchars("{$base}/?p=project-details&slug={$proj['slug']}") ?></loc>
    <changefreq>monthly</changefreq>
    <priority>0.75</priority>
    <lastmod><?= date('Y-m-d', strtotime($proj['updated_at'] ?? 'now')) ?></lastmod>
  </url>
  <?php endforeach; ?>
</urlset>