<?php
header('Content-Type: application/xml; charset=UTF-8');

require_once 'config/config.php';

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

$base = 'https://nexirotech.com';

// Enhanced page structure with SEO-optimized priorities and frequencies
$pages = [
    ['url' => '/', 'priority' => '1.0', 'freq' => 'weekly', 'importance' => 'highest'],
    ['url' => '/services', 'priority' => '0.9', 'freq' => 'weekly', 'importance' => 'high'],
    ['url' => '/blog', 'priority' => '0.8', 'freq' => 'daily', 'importance' => 'high'],
    ['url' => '/portfolio', 'priority' => '0.7', 'freq' => 'weekly', 'importance' => 'medium'],
    ['url' => '/about', 'priority' => '0.6', 'freq' => 'monthly', 'importance' => 'medium'],
    ['url' => '/contact', 'priority' => '0.6', 'freq' => 'monthly', 'importance' => 'medium'],
];

// Additional SEO-important pages
$seoPages = [
    ['url' => '/privacy-policy', 'priority' => '0.4', 'freq' => 'yearly'],
    ['url' => '/terms-of-service', 'priority' => '0.4', 'freq' => 'yearly'],
    ['url' => '/sitemap', 'priority' => '0.3', 'freq' => 'monthly'],
];

$pages = array_merge($pages, $seoPages);

// Fetch blogs with SEO optimization
$blogs = [];
if ($conn && !$conn->connect_error) {
    // Get only high-quality, published blogs with SEO metadata
    $r = $conn->query("
        SELECT slug, updated_at, created_at, 
               views, seo_score, is_featured 
        FROM blogs 
        WHERE status = 1 
          AND (publish_date <= NOW() OR publish_date IS NULL)
        ORDER BY 
            is_featured DESC,
            views DESC,
            updated_at DESC
    ");
    
    if ($r) {
        while ($b = $r->fetch_assoc()) {
            // Dynamic priority based on engagement metrics
            $priority = '0.6'; // Default
            if (!empty($b['is_featured'])) {
                $priority = '0.8';
            } elseif (!empty($b['views']) && $b['views'] > 1000) {
                $priority = '0.7';
            } elseif (!empty($b['seo_score']) && $b['seo_score'] > 80) {
                $priority = '0.65';
            }
            
            // Dynamic frequency based on update recency
            $freq = 'monthly';
            $lastmod = !empty($b['updated_at']) ? $b['updated_at'] : $b['created_at'];
            $daysSinceUpdate = (time() - strtotime($lastmod)) / (60 * 60 * 24);
            
            if ($daysSinceUpdate < 7) {
                $freq = 'weekly';
            } elseif ($daysSinceUpdate < 30) {
                $freq = 'monthly';
            } else {
                $freq = 'yearly';
            }
            
            $blogs[] = [
                'url' => '/blog/' . $b['slug'], // SEO-friendly URL structure
                'date' => $lastmod,
                'priority' => $priority,
                'freq' => $freq
            ];
        }
    }
}

// Fetch service pages dynamically if you have a services table
$services = [];
if ($conn && !$conn->connect_error) {
    $r = $conn->query("
        SELECT slug, updated_at, name, popularity 
        FROM services 
        WHERE status = 1 AND show_in_sitemap = 1
        ORDER BY popularity DESC
    ");
    
    if ($r) {
        while ($s = $r->fetch_assoc()) {
            $priority = '0.8';
            if (!empty($s['popularity']) && $s['popularity'] > 50) {
                $priority = '0.85';
            }
            
            $services[] = [
                'url' => '/services/' . $s['slug'],
                'date' => $s['updated_at'] ?? date('Y-m-d'),
                'priority' => $priority,
                'freq' => 'weekly'
            ];
        }
    }
}

// Fetch portfolio/project pages
$portfolios = [];
if ($conn && !$conn->connect_error) {
    $r = $conn->query("
        SELECT slug, updated_at, title, client_name 
        FROM portfolio 
        WHERE status = 1 
        ORDER BY updated_at DESC 
        LIMIT 100
    ");
    
    if ($r) {
        while ($p = $r->fetch_assoc()) {
            $portfolios[] = [
                'url' => '/portfolio/' . $p['slug'],
                'date' => $p['updated_at'] ?? date('Y-m-d'),
                'priority' => '0.65',
                'freq' => 'monthly'
            ];
        }
    }
}

// Add category/tag pages if you have them
$categories = [];
if ($conn && !$conn->connect_error) {
    $r = $conn->query("
        SELECT slug, COUNT(*) as post_count 
        FROM blog_categories bc
        JOIN blog_category_relations bcr ON bc.id = bcr.category_id
        GROUP BY bc.id
        HAVING post_count > 0
        ORDER BY post_count DESC
        LIMIT 20
    ");
    
    if ($r) {
        while ($c = $r->fetch_assoc()) {
            $priority = min(0.7, 0.5 + ($c['post_count'] * 0.01));
            $categories[] = [
                'url' => '/blog/category/' . $c['slug'],
                'date' => date('Y-m-d'),
                'priority' => number_format($priority, 2),
                'freq' => 'weekly'
            ];
        }
    }
}

// XML output with proper formatting
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<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">' . "\n";

// Add main pages
foreach ($pages as $p) {
    echo '    <url>' . "\n";
    echo '        <loc>' . $base . htmlspecialchars($p['url']) . '</loc>' . "\n";
    echo '        <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
    echo '        <changefreq>' . $p['freq'] . '</changefreq>' . "\n";
    echo '        <priority>' . $p['priority'] . '</priority>' . "\n";
    echo '    </url>' . "\n";
}

// Add service pages
foreach ($services as $s) {
    echo '    <url>' . "\n";
    echo '        <loc>' . $base . htmlspecialchars($s['url']) . '</loc>' . "\n";
    echo '        <lastmod>' . date('Y-m-d', strtotime($s['date'])) . '</lastmod>' . "\n";
    echo '        <changefreq>' . $s['freq'] . '</changefreq>' . "\n";
    echo '        <priority>' . $s['priority'] . '</priority>' . "\n";
    echo '    </url>' . "\n";
}

// Add blog pages
foreach ($blogs as $b) {
    echo '    <url>' . "\n";
    echo '        <loc>' . $base . htmlspecialchars($b['url']) . '</loc>' . "\n";
    echo '        <lastmod>' . date('Y-m-d', strtotime($b['date'])) . '</lastmod>' . "\n";
    echo '        <changefreq>' . $b['freq'] . '</changefreq>' . "\n";
    echo '        <priority>' . $b['priority'] . '</priority>' . "\n";
    echo '    </url>' . "\n";
}

// Add portfolio pages
foreach ($portfolios as $p) {
    echo '    <url>' . "\n";
    echo '        <loc>' . $base . htmlspecialchars($p['url']) . '</loc>' . "\n";
    echo '        <lastmod>' . date('Y-m-d', strtotime($p['date'])) . '</lastmod>' . "\n";
    echo '        <changefreq>' . $p['freq'] . '</changefreq>' . "\n";
    echo '        <priority>' . $p['priority'] . '</priority>' . "\n";
    echo '    </url>' . "\n";
}

// Add category pages
foreach ($categories as $c) {
    echo '    <url>' . "\n";
    echo '        <loc>' . $base . htmlspecialchars($c['url']) . '</loc>' . "\n";
    echo '        <lastmod>' . date('Y-m-d', strtotime($c['date'])) . '</lastmod>' . "\n";
    echo '        <changefreq>' . $c['freq'] . '</changefreq>' . "\n";
    echo '        <priority>' . $c['priority'] . '</priority>' . "\n";
    echo '    </url>' . "\n";
}

echo '</urlset>';

if ($conn) $conn->close();

// Optional: Log sitemap generation for monitoring
error_log("Sitemap generated at " . date('Y-m-d H:i:s') . " with " . 
          (count($pages) + count($services) + count($blogs) + count($portfolios) + count($categories)) . " URLs");
?>