<?php
// sitemap.xml - Dynamic XML Sitemap Generator
// IMPORTANT: This file MUST have NO characters before the opening <?php tag
// Including spaces, newlines, or BOM (Byte Order Mark)

// Turn off all error reporting to prevent any output
error_reporting(0);
ini_set('display_errors', 0);

// Start output buffering to catch any accidental output
ob_start();

// Function to clean any output before XML declaration
function clean_output() {
    // Clean all output buffers
    while (ob_get_level()) {
        ob_end_clean();
    }
    // Start a new clean buffer
    ob_start();
}

// Clean any existing output
clean_output();

// Now include required files
require_once 'config.php';
require_once 'functions.php';

// Set sitemap settings
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
// Remove any trailing slash and add /acet/ if needed (adjust this path)
$base_url = rtrim($base_url, '/');
$base_url .= '/acet/'; // Change this to your correct base path

// Get current date for lastmod
$current_date = date('Y-m-d');

// Function to safely output XML
function outputXML($content) {
    // Remove any BOM or whitespace
    $content = preg_replace('/^\xEF\xBB\xBF/', '', $content); // Remove UTF-8 BOM
    $content = ltrim($content); // Remove leading whitespace
    echo $content;
}

// Clear the buffer again before output
ob_clean();

// Start XML output - ABSOLUTELY NO WHITESPACE BEFORE THIS
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<?xml-stylesheet type="text/xsl" href="sitemap-stylesheet.xsl"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
echo ' xmlns:xhtml="http://www.w3.org/1999/xhtml"';
echo ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"';
echo ' xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";

// ============================================
// 1. STATIC PAGES
// ============================================
$static_pages = [
    // Main pages
    ['loc' => '', 'priority' => '1.0', 'changefreq' => 'daily', 'lastmod' => $current_date],
    ['loc' => 'index.php', 'priority' => '1.0', 'changefreq' => 'daily', 'lastmod' => $current_date],
    ['loc' => 'about.php', 'priority' => '0.8', 'changefreq' => 'monthly', 'lastmod' => $current_date],
    ['loc' => 'programs.php', 'priority' => '0.9', 'changefreq' => 'weekly', 'lastmod' => $current_date],
    ['loc' => 'admissions.php', 'priority' => '0.9', 'changefreq' => 'weekly', 'lastmod' => $current_date],
    ['loc' => 'partnerships.php', 'priority' => '0.7', 'changefreq' => 'monthly', 'lastmod' => $current_date],
    ['loc' => 'news.php', 'priority' => '0.8', 'changefreq' => 'daily', 'lastmod' => $current_date],
    ['loc' => 'events.php', 'priority' => '0.8', 'changefreq' => 'daily', 'lastmod' => $current_date],
    ['loc' => 'contact.php', 'priority' => '0.7', 'changefreq' => 'yearly', 'lastmod' => $current_date],
    
    // Student resources
    ['loc' => 'dashboard.php', 'priority' => '0.6', 'changefreq' => 'weekly', 'lastmod' => $current_date],
    ['loc' => 'library.php', 'priority' => '0.7', 'changefreq' => 'weekly', 'lastmod' => $current_date],
    ['loc' => 'student-handbook.php', 'priority' => '0.7', 'changefreq' => 'monthly', 'lastmod' => $current_date],
    ['loc' => 'academic-calendar.php', 'priority' => '0.8', 'changefreq' => 'weekly', 'lastmod' => $current_date],
    ['loc' => 'career-services.php', 'priority' => '0.8', 'changefreq' => 'weekly', 'lastmod' => $current_date],
    ['loc' => 'accessibility.php', 'priority' => '0.6', 'changefreq' => 'monthly', 'lastmod' => $current_date],
    ['loc' => 'faq.php', 'priority' => '0.6', 'changefreq' => 'monthly', 'lastmod' => $current_date],
    
    // Policy pages
    ['loc' => 'privacy-policy.php', 'priority' => '0.5', 'changefreq' => 'yearly', 'lastmod' => $current_date],
    ['loc' => 'terms-of-service.php', 'priority' => '0.5', 'changefreq' => 'yearly', 'lastmod' => $current_date],
    ['loc' => 'cookie-policy.php', 'priority' => '0.4', 'changefreq' => 'yearly', 'lastmod' => $current_date],
    
    // Sitemap
    ['loc' => 'sitemap.php', 'priority' => '0.6', 'changefreq' => 'monthly', 'lastmod' => $current_date],
];

foreach ($static_pages as $page) {
    $url = $base_url . $page['loc'];
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
    echo "    <lastmod>" . $page['lastmod'] . "</lastmod>\n";
    echo "    <changefreq>" . $page['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $page['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// ============================================
// 2. DYNAMIC CONTENT WITH ERROR HANDLING
// ============================================
try {
    // Check database connection
    if (!$conn || $conn->connect_error) {
        throw new Exception("Database connection failed");
    }
    
    // ============================================
    // PROGRAMS
    // ============================================
    try {
        $programs_table = $conn->query("SHOW TABLES LIKE 'programs'");
        if ($programs_table && $programs_table->num_rows > 0) {
            $programs_query = "SELECT id, title, slug, updated_at FROM programs WHERE status = 'active' OR status IS NULL";
            $programs = $conn->query($programs_query);
            
            if ($programs && $programs->num_rows > 0) {
                while ($program = $programs->fetch_assoc()) {
                    $slug = !empty($program['slug']) ? $program['slug'] : 'program-details.php?id=' . $program['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'program.php?slug=' . $slug);
                    $lastmod = !empty($program['updated_at']) ? date('Y-m-d', strtotime($program['updated_at'])) : $current_date;
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>weekly</changefreq>\n";
                    echo "    <priority>0.8</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }
    
    // ============================================
    // SHORT COURSES
    // ============================================
    try {
        $short_courses_table = $conn->query("SHOW TABLES LIKE 'short_courses'");
        if ($short_courses_table && $short_courses_table->num_rows > 0) {
            $courses_query = "SELECT id, title, slug, updated_at FROM short_courses WHERE status = 'active'";
            $courses = $conn->query($courses_query);
            
            if ($courses && $courses->num_rows > 0) {
                while ($course = $courses->fetch_assoc()) {
                    $slug = !empty($course['slug']) ? $course['slug'] : 'short-course-details.php?id=' . $course['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'short-course.php?slug=' . $slug);
                    $lastmod = !empty($course['updated_at']) ? date('Y-m-d', strtotime($course['updated_at'])) : $current_date;
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>weekly</changefreq>\n";
                    echo "    <priority>0.8</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }
    
    // ============================================
    // PROFESSIONAL COURSES
    // ============================================
    try {
        $professional_courses_table = $conn->query("SHOW TABLES LIKE 'professional_courses'");
        if ($professional_courses_table && $professional_courses_table->num_rows > 0) {
            $courses_query = "SELECT id, title, slug, updated_at FROM professional_courses WHERE status = 'active'";
            $courses = $conn->query($courses_query);
            
            if ($courses && $courses->num_rows > 0) {
                while ($course = $courses->fetch_assoc()) {
                    $slug = !empty($course['slug']) ? $course['slug'] : 'professional-course-details.php?id=' . $course['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'professional-course.php?slug=' . $slug);
                    $lastmod = !empty($course['updated_at']) ? date('Y-m-d', strtotime($course['updated_at'])) : $current_date;
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>weekly</changefreq>\n";
                    echo "    <priority>0.8</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }
    
    // ============================================
    // NEWS ARTICLES
    // ============================================
    try {
        // Check for news_articles table first, then fallback to news
        $news_table = $conn->query("SHOW TABLES LIKE 'news_articles'");
        $table_name = 'news_articles';
        
        if (!$news_table || $news_table->num_rows == 0) {
            $news_table = $conn->query("SHOW TABLES LIKE 'news'");
            $table_name = 'news';
        }
        
        if ($news_table && $news_table->num_rows > 0) {
            $news_query = "SELECT id, title, slug, published_date, updated_at FROM $table_name WHERE status = 'published' ORDER BY published_date DESC LIMIT 500";
            $news = $conn->query($news_query);
            
            if ($news && $news->num_rows > 0) {
                while ($article = $news->fetch_assoc()) {
                    $slug = !empty($article['slug']) ? $article['slug'] : 'news-details.php?id=' . $article['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'news.php?slug=' . $slug);
                    $lastmod = !empty($article['updated_at']) ? date('Y-m-d', strtotime($article['updated_at'])) : (!empty($article['published_date']) ? date('Y-m-d', strtotime($article['published_date'])) : $current_date);
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>monthly</changefreq>\n";
                    echo "    <priority>0.7</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }
    
    // ============================================
    // EVENTS
    // ============================================
    try {
        $events_table = $conn->query("SHOW TABLES LIKE 'events'");
        if ($events_table && $events_table->num_rows > 0) {
            $events_query = "SELECT id, title, slug, start_date, updated_at FROM events WHERE status IN ('upcoming', 'ongoing', 'published') ORDER BY start_date DESC LIMIT 500";
            $events = $conn->query($events_query);
            
            if ($events && $events->num_rows > 0) {
                while ($event = $events->fetch_assoc()) {
                    $slug = !empty($event['slug']) ? $event['slug'] : 'event-details.php?id=' . $event['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'event.php?slug=' . $slug);
                    $lastmod = !empty($event['updated_at']) ? date('Y-m-d', strtotime($event['updated_at'])) : (!empty($event['start_date']) ? date('Y-m-d', strtotime($event['start_date'])) : $current_date);
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>weekly</changefreq>\n";
                    echo "    <priority>0.7</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }
    
    // ============================================
    // CAREER JOBS
    // ============================================
    try {
        $jobs_table = $conn->query("SHOW TABLES LIKE 'career_jobs'");
        if ($jobs_table && $jobs_table->num_rows > 0) {
            $jobs_query = "SELECT id, title, slug, created_at, updated_at FROM career_jobs WHERE status = 'published' ORDER BY created_at DESC LIMIT 200";
            $jobs = $conn->query($jobs_query);
            
            if ($jobs && $jobs->num_rows > 0) {
                while ($job = $jobs->fetch_assoc()) {
                    $slug = !empty($job['slug']) ? $job['slug'] : 'job-details.php?id=' . $job['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'job.php?slug=' . $slug);
                    $lastmod = !empty($job['updated_at']) ? date('Y-m-d', strtotime($job['updated_at'])) : (!empty($job['created_at']) ? date('Y-m-d', strtotime($job['created_at'])) : $current_date);
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>weekly</changefreq>\n";
                    echo "    <priority>0.7</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }
    
    // ============================================
    // INTERNSHIPS
    // ============================================
    try {
        $internships_table = $conn->query("SHOW TABLES LIKE 'career_internships'");
        if ($internships_table && $internships_table->num_rows > 0) {
            $internships_query = "SELECT id, title, slug, created_at, updated_at FROM career_internships WHERE status = 'open' ORDER BY created_at DESC LIMIT 200";
            $internships = $conn->query($internships_query);
            
            if ($internships && $internships->num_rows > 0) {
                while ($internship = $internships->fetch_assoc()) {
                    $slug = !empty($internship['slug']) ? $internship['slug'] : 'internship-details.php?id=' . $internship['id'];
                    $url = $base_url . (strpos($slug, '.php') !== false ? $slug : 'internship.php?slug=' . $slug);
                    $lastmod = !empty($internship['updated_at']) ? date('Y-m-d', strtotime($internship['updated_at'])) : (!empty($internship['created_at']) ? date('Y-m-d', strtotime($internship['created_at'])) : $current_date);
                    
                    echo "  <url>\n";
                    echo "    <loc>" . htmlspecialchars($url) . "</loc>\n";
                    echo "    <lastmod>" . $lastmod . "</lastmod>\n";
                    echo "    <changefreq>weekly</changefreq>\n";
                    echo "    <priority>0.7</priority>\n";
                    echo "  </url>\n";
                }
            }
        }
    } catch (Exception $e) {
        // Silently continue
    }

} catch (Exception $e) {
    // If database fails, just output static pages
    // No error output - silently continue
}

// Close urlset
echo '</urlset>';

// Get the buffer content
$content = ob_get_clean();

// Remove any BOM and leading/trailing whitespace
$content = preg_replace('/^\xEF\xBB\xBF/', '', $content); // Remove UTF-8 BOM
$content = ltrim($content); // Remove leading whitespace
$content = rtrim($content); // Remove trailing whitespace

// Ensure the content starts with <?xml
if (strpos($content, '<?xml') !== 0) {
    // Something went wrong - output a minimal valid sitemap
    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    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";
    echo '  </url>' . "\n";
    echo '</urlset>' . "\n";
    exit;
}

// Set proper content type
header('Content-Type: application/xml; charset=utf-8');

// Output the clean content
echo $content;
?>