<?php
/**
 * AJOUAMAI IMMO-BUSINESS — Dynamic Sitemap Generator
 * Outputs XML sitemap with all pages + published properties
 */
require_once __DIR__ . '/includes/config.php';

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

$baseUrl = 'https://aib-immobilier.ma';
$today = date('Y-m-d');

// Static pages
$staticPages = [
    ['url' => '/',                   'priority' => '1.0', 'freq' => 'weekly'],
    ['url' => '/pages/properties',   'priority' => '0.9', 'freq' => 'daily'],
    ['url' => '/pages/articles',     'priority' => '0.8', 'freq' => 'weekly'],
    ['url' => '/pages/about',        'priority' => '0.8', 'freq' => 'monthly'],
    ['url' => '/pages/services',     'priority' => '0.8', 'freq' => 'monthly'],
    ['url' => '/pages/estimation',   'priority' => '0.8', 'freq' => 'monthly'],
    ['url' => '/pages/rdv',          'priority' => '0.7', 'freq' => 'monthly'],
    ['url' => '/pages/contact',      'priority' => '0.7', 'freq' => 'monthly'],
];

// Dynamic properties
$properties = [];
try {
    $db = getDB();
    $properties = $db->query("SELECT slug, updated_at FROM properties WHERE status IN ('vente','location') ORDER BY updated_at DESC")->fetchAll();
} catch (Exception $e) {}

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

foreach ($staticPages as $page) {
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($baseUrl . $page['url']) . "</loc>\n";
    echo "    <lastmod>{$today}</lastmod>\n";
    echo "    <changefreq>{$page['freq']}</changefreq>\n";
    echo "    <priority>{$page['priority']}</priority>\n";
    echo "  </url>\n";
}

foreach ($properties as $prop) {
    $lastMod = isset($prop['updated_at']) ? substr($prop['updated_at'], 0, 10) : $today;
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($baseUrl . '/pages/property/' . $prop['slug']) . "</loc>\n";
    echo "    <lastmod>{$lastMod}</lastmod>\n";
    echo "    <changefreq>weekly</changefreq>\n";
    echo "    <priority>0.7</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>';
