<?php
declare(strict_types=1);

require_once __DIR__ . '/site-api/estate-server.php';

$origin = estatePublicOrigin();
$urls = [
    '/',
    '/immobili',
    '/chi-siamo',
    '/valutazione',
    '/territorio',
    '/contatti',
];

$page = 1;
$maxPages = 100;

while ($page <= $maxPages) {
    $response = estateServerJson('immobili', [
        'locale' => 'it',
        'per_page' => 48,
        'page' => $page,
        'sort' => 'newest',
    ]);

    if ($response['status'] !== 200 || !is_array($response['body'])) {
        break;
    }

    $items = is_array($response['body']['data'] ?? null) ? $response['body']['data'] : [];
    foreach ($items as $item) {
        $id = (int) ($item['id'] ?? 0);
        if ($id > 0) {
            $urls[] = estatePropertyPath($item);
        }
    }

    $current = (int) ($response['body']['meta']['current_page'] ?? $page);
    $last = (int) ($response['body']['meta']['last_page'] ?? $current);
    if ($current >= $last || !$items) {
        break;
    }
    $page++;
}

header('Content-Type: application/xml; charset=UTF-8');
header('Cache-Control: public, max-age=900');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach (array_values(array_unique($urls)) as $path) {
    echo '  <url><loc>' . htmlspecialchars($origin . $path, ENT_XML1 | ENT_QUOTES, 'UTF-8') . '</loc></url>' . "\n";
}
echo '</urlset>' . "\n";
