<?php
/**
 * sitemap.xml - Dynamic XML Sitemap Generator
 * This file should be accessed directly or via index.php?page=sitemap-xml
 */

// If accessed directly
if(basename($_SERVER['PHP_SELF']) === 'sitemap.xml') {
    require_once 'includes/config.php';
    require_once 'includes/functions.php';
}

header('Content-Type: application/xml; charset=utf-8');

$pagesData = loadJsonData('data/pages.json');
$blogs = getBlogs();

$urls = [];

// Static pages
$staticPages = [
    ['/', '1.0', 'daily'],
    ['/about', '0.8', 'monthly'],
    ['/services', '0.9', 'weekly'],
    ['/service-areas', '0.9', 'weekly'],
    ['/gallery', '0.7', 'monthly'],
    ['/financing', '0.6', 'monthly'],
    ['/faqs', '0.7', 'monthly'],
    ['/contact', '0.8', 'monthly'],
    ['/blog', '0.8', 'weekly'],
    ['/privacy-policy', '0.3', 'yearly'],
    ['/terms', '0.3', 'yearly']
];

foreach($staticPages as $page) {
    $urls[] = [
        'loc' => SITE_URL . $page[0],
        'priority' => $page[1],
        'changefreq' => $page[2]
    ];
}

// Service pages
if(isset($pagesData['services'])) {
    foreach($pagesData['services'] as $service) {
        $urls[] = [
            'loc' => SITE_URL . '/service/' . $service['slug'],
            'priority' => '0.9',
            'changefreq' => 'weekly'
        ];
    }
}

// Location pages
if(isset($pagesData['locations'])) {
    foreach($pagesData['locations'] as $location) {
        $urls[] = [
            'loc' => SITE_URL . '/location/' . $location['slug'],
            'priority' => '0.8',
            'changefreq' => 'weekly'
        ];
    }
}

// Blog pages
foreach($blogs as $blog) {
    $urls[] = [
        'loc' => SITE_URL . '/blog/' . $blog['slug'],
        'priority' => '0.6',
        'changefreq' => 'monthly',
        'lastmod' => date('Y-m-d', strtotime($blog['date'] ?? 'now'))
    ];
}

// Output XML
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<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">
    <?php foreach($urls as $url): ?>
    <url>
        <loc><?php echo $url['loc']; ?></loc>
        <priority><?php echo $url['priority']; ?></priority>
        <changefreq><?php echo $url['changefreq']; ?></changefreq>
        <?php if(isset($url['lastmod'])): ?>
            <lastmod><?php echo $url['lastmod']; ?></lastmod>
        <?php endif; ?>
    </url>
    <?php endforeach; ?>
</urlset>