<?php
/**
 * Dynamic XML Sitemap Generator for Shubank
 * Generates a comprehensive sitemap including static pages, blog posts, and images
 */

// Set content type to XML
header('Content-Type: application/xml; charset=utf-8');

// Include required files
require_once 'config.php';
require_once 'admin/blog-functions.php';

// Get base URL dynamically
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$domain = $_SERVER['HTTP_HOST'];
$base_url = $protocol . $domain . rtrim(dirname($_SERVER['REQUEST_URI']), '/');

// Remove any trailing slashes
$base_url = rtrim($base_url, '/');

$current_date = date('Y-m-d');

// Start XML output
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
echo '        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . "\n";

// Static pages configuration
$static_pages = [
    '' => ['priority' => '1.0', 'changefreq' => 'daily'], // Homepage
    'about.php' => ['priority' => '0.8', 'changefreq' => 'monthly'],
    'contact.php' => ['priority' => '0.7', 'changefreq' => 'monthly'],
    'blogs.php' => ['priority' => '0.9', 'changefreq' => 'daily'],
    'dashboard.php' => ['priority' => '0.7', 'changefreq' => 'weekly'],
    'rate-timing.php' => ['priority' => '0.6', 'changefreq' => 'weekly'],
    'results.php' => ['priority' => '0.7', 'changefreq' => 'daily'],
    'users.php' => ['priority' => '0.5', 'changefreq' => 'weekly'],
    'login.php' => ['priority' => '0.4', 'changefreq' => 'monthly'],
    'forgot.php' => ['priority' => '0.3', 'changefreq' => 'monthly'],
    'thankyou.php' => ['priority' => '0.5', 'changefreq' => 'monthly'],
    'terms-conditions.php' => ['priority' => '0.4', 'changefreq' => 'monthly'],
    'privacy-policy.php' => ['priority' => '0.4', 'changefreq' => 'monthly']
];

// Add static pages to sitemap
foreach ($static_pages as $page => $settings) {
    $page_url = $base_url . ($page ? '/' . $page : '/');
    $file_path = $page ? $page : 'index.php';
    $last_modified = file_exists($file_path) ? date('Y-m-d', filemtime($file_path)) : $current_date;
    
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($page_url) . "</loc>\n";
    echo "    <lastmod>" . $last_modified . "</lastmod>\n";
    echo "    <changefreq>" . $settings['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $settings['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// Add dynamic blog posts
try {
    if (isset($link) && $link) {
        $all_blogs = getAllBlogs($link);
        $published_blogs = array_filter($all_blogs, function($blog) {
            return $blog['status'] === 'published';
        });
        
        foreach ($published_blogs as $blog) {
            $blog_url = $base_url . '/blog/' . $blog['slug'];
            $last_modified = $blog['updated_at'] ? date('Y-m-d', strtotime($blog['updated_at'])) : date('Y-m-d', strtotime($blog['created_at']));
            
            echo "  <url>\n";
            echo "    <loc>" . htmlspecialchars($blog_url) . "</loc>\n";
            echo "    <lastmod>" . $last_modified . "</lastmod>\n";
            echo "    <changefreq>weekly</changefreq>\n";
            echo "    <priority>0.8</priority>\n";
            echo "  </url>\n";
        }
    }
} catch (Exception $e) {
    // Silently handle blog loading errors
    error_log("Sitemap blog error: " . $e->getMessage());
}

// Add homepage with images
echo "  <url>\n";
echo "    <loc>" . htmlspecialchars($base_url . '/') . "</loc>\n";
echo "    <lastmod>" . $current_date . "</lastmod>\n";
echo "    <changefreq>daily</changefreq>\n";
echo "    <priority>1.0</priority>\n";

// Add image information if images exist
$images_to_include = [
    'images/shubank-banner.png' => 'Shubank - India\'s Most Trusted Matka Platform',
    'images/hero-bg.png' => 'Shubank Hero Background',
    'images/shubank-hero-banner.png' => 'Shubank Hero Banner'
];

foreach ($images_to_include as $image_path => $image_title) {
    if (file_exists($image_path)) {
        echo "    <image:image>\n";
        echo "      <image:loc>" . htmlspecialchars($base_url . '/' . $image_path) . "</image:loc>\n";
        echo "      <image:title>" . htmlspecialchars($image_title) . "</image:title>\n";
        echo "      <image:caption>" . htmlspecialchars($image_title) . "</image:caption>\n";
        echo "    </image:image>\n";
    }
}

echo "  </url>\n";

// Close XML sitemap
echo "</urlset>\n";

// Optional: Log sitemap generation
try {
    if (isset($link) && $link) {
        // Create log table if it doesn't exist
        $create_log_table = "CREATE TABLE IF NOT EXISTS sitemap_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            total_urls INT DEFAULT 0,
            UNIQUE KEY unique_date (DATE(generated_at))
        )";
        mysqli_query($link, $create_log_table);
        
        // Count total URLs
        $total_static = count($static_pages);
        $total_blogs = isset($published_blogs) ? count($published_blogs) : 0;
        $total_urls = $total_static + $total_blogs;
        
        // Log the generation
        $log_query = "INSERT INTO sitemap_logs (generated_at, total_urls) VALUES (NOW(), ?) 
                      ON DUPLICATE KEY UPDATE generated_at = NOW(), total_urls = ?";
        $stmt = mysqli_prepare($link, $log_query);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "ii", $total_urls, $total_urls);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
        }
    }
} catch (Exception $e) {
    // Silently handle logging errors
    error_log("Sitemap logging error: " . $e->getMessage());
}
?>