<?php
declare(strict_types=1);
header('Content-Type: application/xml; charset=UTF-8');
require_once __DIR__ . '/database/db_catalog.php';

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

try {
    $pdo = skippertje_catalog_pdo();
    $sql = "SELECT bs.path, GREATEST(COALESCE(b.updated_at, b.created_at), COALESCE(bs.updated_at, bs.created_at)) AS lastmod
            FROM boat_slugs bs
            INNER JOIN boats b ON b.id = bs.boat_id
            WHERE bs.is_canonical = 1
              AND bs.is_active = 1
              AND b.status = 'active'
            ORDER BY bs.path ASC";
    $rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC) ?: [];
    foreach ($rows as $row) {
        $loc = 'https://skippertje.com' . (string)$row['path'];
        $lastmod = !empty($row['lastmod']) ? date('Y-m-d', strtotime((string)$row['lastmod'])) : gmdate('Y-m-d');
        echo "  <url>\n";
        echo '    <loc>' . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
        echo '    <lastmod>' . htmlspecialchars($lastmod, ENT_XML1) . "</lastmod>\n";
        echo "    <changefreq>daily</changefreq>\n";
        echo "    <priority>0.7</priority>\n";
        echo "  </url>\n";
    }
} catch (Throwable $e) {
    // leave valid empty sitemap on failure
}

echo "</urlset>\n";
