<?php
// Dynamic sitemap for JP Imobiliária
require_once __DIR__ . '/assets/includes/db.php';

header('Content-Type: application/xml; charset=utf-8');

$base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$base = preg_replace('/\/$/', '', $base); // ensure no trailing slash

$urls = [];

// Static important pages
$staticPages = [
    $base . '/index.php'   => ['changefreq' => 'daily',   'priority' => '1.0'],
    $base . '/imoveis.php' => ['changefreq' => 'hourly',  'priority' => '0.9'],
    $base . '/sobre.php'   => ['changefreq' => 'monthly', 'priority' => '0.4'],
    $base . '/contato.php' => ['changefreq' => 'monthly', 'priority' => '0.4'],
    $base . '/cadastro.php'=> ['changefreq' => 'monthly', 'priority' => '0.6'],
];
foreach ($staticPages as $loc => $meta) {
    $urls[] = [
        'loc' => $loc,
        'lastmod' => date('c'),
        'changefreq' => $meta['changefreq'],
        'priority' => $meta['priority']
    ];
}

// Dynamic: published properties (sem LIMIT fixo - buscar todos publicados)
$sql = "SELECT id_imovel, DATE_FORMAT(data, '%Y-%m-%d') as data_update FROM imoveis WHERE status = ? ORDER BY id_imovel DESC";
$stmt = $link->prepare($sql);
if ($stmt) {
    $status = 'Publicado';
    $stmt->bind_param('s', $status);
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($row = $result->fetch_assoc()) {
        $loc = $base . '/imovel.php?id=' . (int)$row['id_imovel'];
        $lastmod = !empty($row['data_update']) ? date('c', strtotime($row['data_update'])) : date('c');
        $urls[] = [
            'loc' => $loc,
            'lastmod' => $lastmod,
            'changefreq' => 'daily',
            'priority' => '0.8'
        ];
    }
    $stmt->close();
}

// Output XML
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>\n";
    echo "    <loc>" . htmlspecialchars($u['loc'], ENT_QUOTES | ENT_XML1, 'UTF-8') . "</loc>\n";
    if (!empty($u['lastmod'])) echo "    <lastmod>" . htmlspecialchars($u['lastmod'], ENT_QUOTES | ENT_XML1, 'UTF-8') . "</lastmod>\n";
    if (!empty($u['changefreq'])) echo "    <changefreq>" . htmlspecialchars($u['changefreq'], ENT_QUOTES | ENT_XML1, 'UTF-8') . "</changefreq>\n";
    if (!empty($u['priority'])) echo "    <priority>" . htmlspecialchars($u['priority'], ENT_QUOTES | ENT_XML1, 'UTF-8') . "</priority>\n";
    echo "  </url>\n";
}
echo "</urlset>\n";
exit;
?>
