<?php
header('Content-Type: application/xml; charset=utf-8');

$projectsFile = 'projects.json';
$blogsFile = 'blogs.json';

$projects = file_exists($projectsFile) ? json_decode(file_get_contents($projectsFile), true) : [];
$blogs = file_exists($blogsFile) ? json_decode(file_get_contents($blogsFile), true) : [];

if (!is_array($projects)) $projects = [];
if (!is_array($blogs)) $blogs = [];

// Cập nhật base URL chính xác
$baseUrl = 'https://innhatnguyet.com/';
$currentDate = 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">
    
    <!-- Homepage - Priority cao nhất -->
    <url>
        <loc><?php echo $baseUrl; ?></loc>
        <lastmod><?php echo $currentDate; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>1.0</priority>
    </url>
    
    <!-- Services Section -->
    <url>
        <loc><?php echo $baseUrl; ?>#services</loc>
        <lastmod><?php echo $currentDate; ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.9</priority>
    </url>
    
    <!-- Projects Section -->
    <url>
        <loc><?php echo $baseUrl; ?>#projects</loc>
        <lastmod><?php echo $currentDate; ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>
    
    <!-- Contact Section -->
    <url>
        <loc><?php echo $baseUrl; ?>#contact</loc>
        <lastmod><?php echo $currentDate; ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.7</priority>
    </url>
    
    <!-- Blog page - Priority cao -->
    <url>
        <loc><?php echo $baseUrl; ?>blog.php</loc>
        <lastmod><?php echo $currentDate; ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    
    <!-- Individual blog posts với image sitemap -->
    <?php foreach ($blogs as $blog): ?>
    <url>
        <loc><?php echo $baseUrl . htmlspecialchars($blog['file']); ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($blog['created_at'] ?? date('Y-m-d'))); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
        <?php if (!empty($blog['image'])): ?>
        <image:image>
            <image:loc><?php echo $baseUrl . htmlspecialchars($blog['image']); ?></image:loc>
            <image:title><?php echo htmlspecialchars($blog['title'] ?? 'Blog Image'); ?></image:title>
        </image:image>
        <?php endif; ?>
    </url>
    <?php endforeach; ?>
    
    <!-- Static assets quan trọng -->
    <url>
        <loc><?php echo $baseUrl; ?>logo.png</loc>
        <lastmod><?php echo date('Y-m-d', filemtime('logo.png')); ?></lastmod>
        <changefreq>yearly</changefreq>
        <priority>0.3</priority>
    </url>
    
</urlset>
