<?php
/**
 * TRENJ - خريطة الموقع الديناميكية (Sitemap XML)
 * 
 * تولّد XML sitemap يحتوي:
 *  - الصفحات الثابتة (الرئيسية، عن ترنج، اتصل بنا، إلخ)
 *  - جميع الشاليهات النشطة مع lastmod + priority
 * 
 * الاستدعاء: https://trenj.online/sitemap.php
 * أو عبر RewriteRule: /sitemap.xml → sitemap.php
 */

// التقاط أي output عرضي من config.php
ob_start();

require_once __DIR__ . '/includes/config.php';

// إغلاق الجلسة — لا نحتاجها هنا
if (session_status() === PHP_SESSION_ACTIVE) session_write_close();

// تنظيف أي output عرضي (whitespace, BOM, etc.)
ob_end_clean();

// إرسال الـ headers الصحيحة — بعد التنظيف
header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: public, max-age=3600');
header('X-Robots-Tag: noindex');

$siteUrl = rtrim(SITE_URL, '/');
$now = date('Y-m-d');

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">

    <!-- الصفحات الثابتة -->
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/chalets.php</loc>
        <lastmod><?= $now ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/about.php</loc>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/contact.php</loc>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/partners.php</loc>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/search.php</loc>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/terms.php</loc>
        <changefreq>yearly</changefreq>
        <priority>0.3</priority>
    </url>
    <url>
        <loc><?= htmlspecialchars($siteUrl) ?>/privacy.php</loc>
        <changefreq>yearly</changefreq>
        <priority>0.3</priority>
    </url>

<?php
// الشاليهات النشطة
$result = $conn->query("SELECT 
    c.id, c.username, c.name, c.updated_at, c.main_image,
    c.rating, c.total_reviews, c.auto_seo_description,
    COALESCE(c.views, 0) + COALESCE(c.legacy_views, 0) AS total_views
    FROM chalets c 
    WHERE c.status = 'active'
    ORDER BY c.total_reviews DESC, total_views DESC");

while ($c = $result->fetch_assoc()):
    // URL: username إن وُجد، وإلا id
    $chaletUrl = !empty($c['username']) 
        ? $siteUrl . '/' . htmlspecialchars($c['username'])
        : $siteUrl . '/chalet-details.php?id=' . (int)$c['id'];
    
    // lastmod: من updated_at أو اليوم
    $lastmod = !empty($c['updated_at']) ? date('Y-m-d', strtotime($c['updated_at'])) : $now;
    
    // Priority: حسب التقييمات والزيارات
    $reviews = (int)$c['total_reviews'];
    $views = (int)$c['total_views'];
    if ($reviews >= 10) $priority = 0.9;
    elseif ($reviews >= 5) $priority = 0.8;
    elseif ($views >= 100) $priority = 0.7;
    else $priority = 0.6;
    
    // صورة
    $imageUrl = '';
    if (!empty($c['main_image'])) {
        $img = $c['main_image'];
        if (strpos($img, 'http') !== 0) {
            $img = $siteUrl . '/' . ltrim($img, '/');
        }
        $imageUrl = $img;
    }
?>
    <url>
        <loc><?= $chaletUrl ?></loc>
        <lastmod><?= $lastmod ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority><?= number_format($priority, 1) ?></priority>
<?php if (!empty($imageUrl)): ?>
        <image:image>
            <image:loc><?= htmlspecialchars($imageUrl) ?></image:loc>
            <image:title><?= htmlspecialchars($c['name']) ?></image:title>
        </image:image>
<?php endif; ?>
    </url>
<?php endwhile; ?>

</urlset>
<?php exit; // لا شيء بعد الـ XML ?>
