<?php
/**
 * Dynamic XML Sitemap Generator
 * يولّد خريطة الموقع ديناميكياً من قاعدة البيانات
 * Google Search Console يحبها!
 */

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

require_once __DIR__ . '/config/unified-api.php';

$settings = get_unified_settings();
$baseUrl  = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'kaglaw.sa');
$today    = date('Y-m-d');

// جلب الخدمات
$services = [];
try { $services = get_all_services(); } catch (Exception $e) {}

// جلب الصفحات الديناميكية
$pages = [];
try {
    $stmt = $pdo->query("SELECT slug, title, content_type, updated_at FROM pages WHERE show_in_nav = 1 AND slug NOT LIKE 'nav-%' ORDER BY nav_order ASC");
    $pages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// جلب الصفحات القانونية
$legalPages = [];
try {
    $stmt = $pdo->query("SELECT type, last_updated FROM legal_pages WHERE is_active = 1");
    $legalPages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

// جلب صفحات SEO
$seoPages = [];
try {
    $stmt = $pdo->query("SELECT slug, updated_at FROM seo_pages WHERE is_published = 1 ORDER BY id ASC");
    $seoPages = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

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

    <!-- الصفحة الرئيسية -->
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- أقسام الصفحة الرئيسية الثابتة -->
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/#services</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.9</priority>
    </url>
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/#features</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/#contact</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.8</priority>
    </url>

    <!-- الصفحات الديناميكية (فريق، معرض، حجز، إلخ) -->
<?php foreach ($pages as $p):
    $slug = $p['slug'];
    $type = $p['content_type'] ?? 'text';
    $lastmod = !empty($p['updated_at']) ? date('Y-m-d', strtotime($p['updated_at'])) : $today;
    // صفحات team/gallery/booking/cards تظهر كأقسام في الرئيسية
    if (in_array($type, ['team','gallery','booking','cards'])) {
        $loc = $baseUrl . '/#page-' . $slug;
    } else {
        $loc = $baseUrl . '/page.php?slug=' . $slug;
    }
?>
    <url>
        <loc><?php echo htmlspecialchars($loc); ?></loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
    </url>
<?php endforeach; ?>

    <!-- الصفحات القانونية -->
<?php foreach ($legalPages as $lp):
    $lastmod = !empty($lp['last_updated']) ? date('Y-m-d', strtotime($lp['last_updated'])) : $today;
?>
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/legal-page.php?type=<?php echo $lp['type']; ?></loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>yearly</changefreq>
        <priority>0.4</priority>
    </url>
<?php endforeach; ?>

    <!-- صفحات SEO (روابط عربية) -->
<?php foreach ($seoPages as $sp):
    $lastmod = !empty($sp['updated_at']) ? date('Y-m-d', strtotime($sp['updated_at'])) : $today;
?>
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/<?php echo htmlspecialchars($sp['slug']); ?>/</loc>
        <lastmod><?php echo $lastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
<?php endforeach; ?>

    <!-- المدونة القانونية -->
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/blog/</loc>
        <lastmod><?php echo $today; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.9</priority>
    </url>
<?php
$blogPosts = [];
try {
    $blogStmt = $pdo->query("SELECT slug, updated_at, created_at FROM blog_posts WHERE is_published = 1 ORDER BY created_at DESC");
    $blogPosts = $blogStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}
foreach ($blogPosts as $bp):
    $bpLastmod = !empty($bp['updated_at']) ? date('Y-m-d', strtotime($bp['updated_at'])) : date('Y-m-d', strtotime($bp['created_at']));
?>
    <url>
        <loc><?php echo htmlspecialchars($baseUrl); ?>/blog/<?php echo htmlspecialchars($bp['slug']); ?>/</loc>
        <lastmod><?php echo $bpLastmod; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
<?php endforeach; ?>

</urlset>
