<?php
declare(strict_types=1);
require __DIR__ . '/config/conf.php';
header('Content-Type: application/xml; charset=UTF-8');
$base = rtrim((string) env('APP_URL', 'https://orentify.com'), '/');
$escape = static fn(string $value): string => htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
$stmt = $conn->query("SELECT slug,seo_image,image_paths,date FROM property WHERE listing_status='published' ORDER BY date DESC");
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
echo '<url><loc>'.$escape($base.'/home/').'</loc><changefreq>daily</changefreq><priority>1.0</priority></url>';
foreach ($stmt as $row) {
    $url = $base.'/home/property/'.rawurlencode((string)$row['slug']);
    echo '<url><loc>'.$escape($url).'</loc><lastmod>'.date('c', strtotime((string)$row['date'])).'</lastmod><changefreq>weekly</changefreq><priority>0.8</priority>';
    $images = json_decode((string)$row['image_paths'], true);
    $images = is_array($images) ? $images : [];
    if ($row['seo_image']) array_unshift($images, $row['seo_image']);
    foreach (array_slice(array_unique($images), 0, 20) as $image) echo '<image:image><image:loc>'.$escape($base.'/home/uploads/'.rawurlencode((string)$image)).'</image:loc></image:image>';
    echo '</url>';
}
echo '</urlset>';
