<?php
/**
 * PivvaTech - Dynamic Sitemap Generator
 * Version: 1.0
 * URL: /sitemap.xml
 */

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

require_once 'layouts/functions.php';

$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'];
$base_url = $protocol . $host . '/pivvatech';

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

  <!-- Main Pages -->
  <url>
    <loc><?= $base_url ?>/</loc>
    <lastmod><?= date('Y-m-d') ?></lastmod>
    <changefreq>weekly</changefreq>
    <priority>1.0</priority>
  </url>

  <url>
    <loc><?= $base_url ?>/services</loc>
    <lastmod><?= date('Y-m-d') ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.9</priority>
  </url>

  <url>
    <loc><?= $base_url ?>/blog</loc>
    <lastmod><?= date('Y-m-d') ?></lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
  </url>

  <url>
    <loc><?= $base_url ?>/contact</loc>
    <lastmod><?= date('Y-m-d') ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
  </url>

  <!-- Blog Posts -->
  <?php
  $pdo = getDbConnection();
  $stmt = $pdo->query("SELECT id, updated_at FROM blog_posts WHERE status = 'published' ORDER BY created_at DESC");
  $posts = $stmt->fetchAll();
  
  foreach ($posts as $post):
  ?>
  <url>
    <loc><?= $base_url ?>/post.php?id=<?= $post['id'] ?></loc>
    <lastmod><?= date('Y-m-d', strtotime($post['updated_at'] ?? $post['created_at'])) ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.6</priority>
  </url>
  <?php endforeach; ?>

</urlset>