<?php
require_once 'config/database.php';

header('Content-Type: application/xml');

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get all live job postings
    $stmt = $db->prepare("SELECT id, job_title, job_category, created_at FROM job_ads WHERE ad_type = 'job-posting' AND status = 'Live' AND DATE_ADD(created_at, INTERVAL 30 DAY) >= CURDATE() ORDER BY created_at DESC");
    $stmt->execute();
    $jobs = $stmt->fetchAll();
    
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    
    // Add main pages
    echo '<url>';
    echo '<loc>http://' . $_SERVER['HTTP_HOST'] . '/</loc>';
    echo '<changefreq>daily</changefreq>';
    echo '<priority>1.0</priority>';
    echo '</url>';
    
    echo '<url>';
    echo '<loc>http://' . $_SERVER['HTTP_HOST'] . '/jobs.php</loc>';
    echo '<lastmod>' . date('Y-m-d') . '</lastmod>';
    echo '<changefreq>daily</changefreq>';
    echo '<priority>0.9</priority>';
    echo '</url>';
    
    echo '<url>';
    echo '<loc>http://' . $_SERVER['HTTP_HOST'] . '/categories.php</loc>';
    echo '<lastmod>' . date('Y-m-d') . '</lastmod>';
    echo '<changefreq>weekly</changefreq>';
    echo '<priority>0.8</priority>';
    echo '</url>';
    
    // Add job detail pages
    foreach ($jobs as $job) {
        // Generate SEO-friendly URL
        $category = strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $job['job_category']));
        $slug = strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $job['job_title']));
        echo '<url>';
        echo '<loc>http://' . $_SERVER['HTTP_HOST'] . '/jobs/' . $category . '/' . $slug . '</loc>';
        echo '<lastmod>' . date('Y-m-d', strtotime($job['created_at'])) . '</lastmod>';
        echo '<changefreq>weekly</changefreq>';
        echo '<priority>0.8</priority>';
        echo '</url>';
    }
    
    echo '</urlset>';
    
} catch(PDOException $e) {
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    echo '</urlset>';
}
?>
