<?php
declare(strict_types=1);
require __DIR__ . '/config.php';
header('Content-Type: application/xml; charset=utf-8');

$urls = [];
$add = function (string $loc, string $lastmod = '', string $freq = 'monthly', string $prio = '0.7') use (&$urls) {
    $urls[] = ['loc' => $loc, 'lastmod' => $lastmod, 'freq' => $freq, 'prio' => $prio];
};

$add(abs_url(), date('Y-m-d'), 'weekly', '1.0');
$add(abs_url('about'), '', 'monthly', '0.8');
$add(abs_url('services'), '', 'weekly', '0.9');
$add(abs_url('contact'), '', 'monthly', '0.8');
$add(abs_url('book'), '', 'monthly', '0.9');

foreach (services_all(true) as $s) $add(abs_url('services', (string)$s['slug']), '', 'monthly', '0.8');

if (setting_bool('feature_conditions', true)) {
    $add(abs_url('conditions'), '', 'monthly', '0.8');
    foreach (conditions_all(true) as $c) $add(abs_url('conditions', (string)$c['slug']), '', 'monthly', '0.7');
}
if (setting_bool('feature_team', true)) {
    $add(abs_url('team'), '', 'monthly', '0.7');
    foreach (team_all(true) as $m) $add(abs_url('team', (string)$m['slug']), '', 'monthly', '0.6');
}
if (setting_bool('feature_blog', true)) {
    $add(abs_url('blog'), date('Y-m-d'), 'weekly', '0.8');
    foreach (posts_published() as $p) {
        $add(abs_url('blog', (string)$p['slug']),
             date('Y-m-d', strtotime((string)($p['updated_at'] ?: $p['published_at'] ?: $p['created_at'])) ?: time()),
             'monthly', '0.7');
    }
}
if (setting_bool('feature_gallery', true))      $add(abs_url('gallery'), '', 'monthly', '0.5');
if (setting_bool('feature_testimonials', true)) $add(abs_url('testimonials'), '', 'monthly', '0.6');
if (setting_bool('feature_faq', true))          $add(abs_url('faq'), '', 'monthly', '0.7');
if (setting_bool('feature_pricing', true))      $add(abs_url('pricing'), '', 'monthly', '0.7');

foreach (q('SELECT slug, updated_at FROM pages WHERE enabled=1') as $p) {
    $add(abs_url('page', (string)$p['slug']), $p['updated_at'] ? date('Y-m-d', strtotime((string)$p['updated_at'])) : '', 'yearly', '0.3');
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($urls as $u) {
    echo '  <url><loc>' . e($u['loc']) . '</loc>';
    if ($u['lastmod']) echo '<lastmod>' . e($u['lastmod']) . '</lastmod>';
    echo '<changefreq>' . e($u['freq']) . '</changefreq><priority>' . e($u['prio']) . '</priority></url>' . "\n";
}
echo '</urlset>';
