<?php
require_once 'includes/db.php';

// Set headers to output XML
header("Content-Type: application/xml; charset=utf-8");

$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!-- Home Page -->
    <url>
        <loc><?php echo $base_url; ?>/index.php</loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- About Us Page -->
    <?php if (isset($settings['menu_about_visible']) && $settings['menu_about_visible'] == 1): ?>
    <url>
        <loc><?php echo $base_url; ?>/about.php</loc>
        <changefreq>monthly</changefreq>
        <priority>0.8</priority>
    </url>
    <?php endif; ?>

    <!-- Products Page -->
    <?php if (isset($settings['menu_products_visible']) && $settings['menu_products_visible'] == 1): ?>
    <url>
        <loc><?php echo $base_url; ?>/products.php</loc>
        <changefreq>weekly</changefreq>
        <priority>0.9</priority>
    </url>
    
    <!-- Dynamic Product Details -->
    <?php 
    try {
        $stmt = $pdo->query("SELECT id FROM products ORDER BY id DESC");
        while ($prod = $stmt->fetch()) {
            ?>
            <url>
                <loc><?php echo $base_url; ?>/product-detail.php?id=<?php echo $prod['id']; ?></loc>
                <changefreq>weekly</changefreq>
                <priority>0.7</priority>
            </url>
            <?php
        }
    } catch (Exception $e) {}
    ?>
    <?php endif; ?>

    <!-- Gallery Page -->
    <?php if (isset($settings['menu_gallery_visible']) && $settings['menu_gallery_visible'] == 1): ?>
    <url>
        <loc><?php echo $base_url; ?>/gallery.php</loc>
        <changefreq>weekly</changefreq>
        <priority>0.6</priority>
    </url>
    <?php endif; ?>

    <!-- Blog Page -->
    <?php if (isset($settings['menu_blog_visible']) && $settings['menu_blog_visible'] == 1): ?>
    <url>
        <loc><?php echo $base_url; ?>/blog.php</loc>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    
    <!-- Dynamic Blog Details -->
    <?php 
    try {
        $stmt = $pdo->query("SELECT slug FROM articles ORDER BY id DESC");
        while ($art = $stmt->fetch()) {
            ?>
            <url>
                <loc><?php echo $base_url; ?>/blog-detail.php?slug=<?php echo urlencode($art['slug']); ?></loc>
                <changefreq>weekly</changefreq>
                <priority>0.7</priority>
            </url>
            <?php
        }
    } catch (Exception $e) {}
    ?>
    <?php endif; ?>

    <!-- Contact Page -->
    <?php if (isset($settings['menu_contact_visible']) && $settings['menu_contact_visible'] == 1): ?>
    <url>
        <loc><?php echo $base_url; ?>/contact.php</loc>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
    <?php endif; ?>
</urlset>
