<?php
/// file: app/Controllers/SitemapController.php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\JournalPost;
use App\Models\Project;

final class SitemapController extends Controller
{
    public function index(Request $request): Response
    {
        $base = rtrim((string) $this->app->config('app.url', ''), '/');
        $urls = [
            url('/'),
            url('/about'),
            url('/work'),
            url('/services'),
            url('/journal'),
            url('/contact'),
            url('/careers'),
        ];
        foreach (Project::published(500) as $p) {
            $urls[] = url('/work/' . rawurlencode((string) $p['slug']));
        }
        foreach (JournalPost::published(500) as $j) {
            $urls[] = url('/journal/' . rawurlencode((string) $j['slug']));
        }
        $locBase = $base !== '' ? $base : '';
        $xml = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        foreach ($urls as $u) {
            $loc = htmlspecialchars($locBase . $u, ENT_XML1 | ENT_QUOTES, 'UTF-8');
            $xml .= "<url><loc>{$loc}</loc><changefreq>weekly</changefreq><priority>0.7</priority></url>";
        }
        $xml .= '</urlset>';
        return (new Response($xml, 200))->header('Content-Type', 'application/xml; charset=UTF-8');
    }
}
