<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/functions.php';

if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/config/database.php';
}

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

echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;

// 1. Static Pages
$staticPages = [
    '',
    'pricing.php',
    'services.php',
    'blog.php',
    'login.php',
    'register.php'
];

foreach ($staticPages as $page) {
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . e(url($page)) . '</loc>' . PHP_EOL;
    echo '    <changefreq>daily</changefreq>' . PHP_EOL;
    echo '    <priority>1.0</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
}

// 2. SEO Landings
$landings = $pdo->query("SELECT slug, created_at FROM seo_landings WHERE status = 'active'")->fetchAll();
foreach ($landings as $l) {
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . e(url('l/' . $l['slug'])) . '</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('Y-m-d', strtotime($l['created_at'])) . '</lastmod>' . PHP_EOL;
    echo '    <changefreq>weekly</changefreq>' . PHP_EOL;
    echo '    <priority>0.8</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
}

// 3. Blog Posts
$posts = $pdo->query("SELECT slug, updated_at FROM blog_posts WHERE status = 'published'")->fetchAll();
foreach ($posts as $p) {
    echo '  <url>' . PHP_EOL;
    echo '    <loc>' . e(url('blog/' . $p['slug'])) . '</loc>' . PHP_EOL;
    echo '    <lastmod>' . date('Y-m-d', strtotime($p['updated_at'])) . '</lastmod>' . PHP_EOL;
    echo '    <changefreq>monthly</changefreq>' . PHP_EOL;
    echo '    <priority>0.6</priority>' . PHP_EOL;
    echo '  </url>' . PHP_EOL;
}

echo '</urlset>';
