<?php
// sitemap.xml - Place this in your root directory
// Make sure the file is saved as sitemap.xml (not .php)

header('Content-Type: application/xml; charset=utf-8');

// Include config WITHOUT session_start and admin check
// We need to bypass the admin authentication for sitemap

// Option 1: Create a separate config for sitemap
// Or Option 2: Modify your existing config to check if it's sitemap request

// Since your config.php has session_start() and admin check,
// we'll create a direct database connection using the same credentials

$base_url = 'https://eual.org';

// Include your database credentials from config.php
// But we won't run the session/admin parts
$config_content = file_get_contents('config.php');
// Extract database credentials using regex or simply require but capture output

// Better approach - include config but suppress errors and handle session
// We'll use output buffering to prevent any output from config.php
ob_start();
include 'config.php';
ob_end_clean();

// Now $pdo should be available from config.php
// But config.php might have session_start() which is fine, just no admin check

// Check if $pdo exists, if not, create connection
if (!isset($pdo)) {
    // Fallback connection - update with your actual database details
    $host = 'localhost';
    $dbname = 'your_database_name';
    $username = 'your_username';
    $password = 'your_password';
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        // If connection fails, output basic sitemap
        echo '<?xml version="1.0" encoding="UTF-8"?>';
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        echo '<url><loc>' . $base_url . '/</loc><priority>1.0</priority></url>';
        echo '</urlset>';
        exit;
    }
}

// Start XML output
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// ============ STATIC PAGES ============
$static_pages = [
    ['loc' => '/', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => '/index.php', 'priority' => '1.0', 'changefreq' => 'daily'],
    ['loc' => '/news.php', 'priority' => '0.9', 'changefreq' => 'daily'],
    ['loc' => '/activities.php', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => '/press.php', 'priority' => '0.7', 'changefreq' => 'weekly'],
    ['loc' => '/video.php', 'priority' => '0.7', 'changefreq' => 'weekly'],
    ['loc' => '/gallery.php', 'priority' => '0.7', 'changefreq' => 'weekly'],
    ['loc' => '/events.php', 'priority' => '0.8', 'changefreq' => 'daily'],
    ['loc' => '/campaigns.php', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => '/opinion.php', 'priority' => '0.8', 'changefreq' => 'weekly'],
    ['loc' => '/communities.php', 'priority' => '0.7', 'changefreq' => 'weekly'],
    ['loc' => '/member-voices.php', 'priority' => '0.8', 'changefreq' => 'daily'],
    ['loc' => '/about.php', 'priority' => '0.6', 'changefreq' => 'monthly'],
    ['loc' => '/contact.php', 'priority' => '0.5', 'changefreq' => 'monthly'],
];

foreach($static_pages as $page) {
    echo '  <url>' . "\n";
    echo '    <loc>' . $base_url . $page['loc'] . '</loc>' . "\n";
    echo '    <changefreq>' . $page['changefreq'] . '</changefreq>' . "\n";
    echo '    <priority>' . $page['priority'] . '</priority>' . "\n";
    echo '  </url>' . "\n";
}

// ============ NEWS POSTS ============
try {
    // Check which tables exist
    $tables_to_check = ['home_posts', 'news_posts', 'press_posts', 'activities_posts', 'opinion_posts', 'communities_posts'];
    
    foreach($tables_to_check as $table) {
        $stmt = $pdo->query("SHOW TABLES LIKE '$table'");
        if($stmt->rowCount() > 0) {
            $stmt = $pdo->query("SELECT id, created_at, updated_at FROM $table ORDER BY created_at DESC LIMIT 1000");
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $type = str_replace('_posts', '', $table);
                $lastmod = date('Y-m-d', strtotime($row['updated_at'] ?? $row['created_at']));
                
                echo '  <url>' . "\n";
                if($table == 'activities_posts') {
                    echo '    <loc>' . $base_url . '/activity-details.php?id=' . $row['id'] . '</loc>' . "\n";
                } elseif($table == 'opinion_posts') {
                    echo '    <loc>' . $base_url . '/opinion-details.php?id=' . $row['id'] . '</loc>' . "\n";
                } elseif($table == 'communities_posts') {
                    echo '    <loc>' . $base_url . '/community-details.php?id=' . $row['id'] . '</loc>' . "\n";
                } else {
                    echo '    <loc>' . $base_url . '/news-details.php?id=' . $row['id'] . '&type=' . $type . '</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 skip table errors
}

// ============ EVENTS ============
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'events'");
    if($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, created_at, updated_at FROM events WHERE status != 'cancelled' ORDER BY created_at DESC LIMIT 1000");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo '  <url>' . "\n";
            echo '    <loc>' . $base_url . '/event-details.php?id=' . $row['id'] . '</loc>' . "\n";
            echo '    <lastmod>' . date('Y-m-d', strtotime($row['updated_at'] ?? $row['created_at'])) . '</lastmod>' . "\n";
            echo '    <changefreq>weekly</changefreq>' . "\n";
            echo '    <priority>0.7</priority>' . "\n";
            echo '  </url>' . "\n";
        }
    }
} catch(Exception $e) {}

// ============ CAMPAIGNS ============
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'campaigns'");
    if($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, created_at, updated_at FROM campaigns WHERE status IN ('active', 'urgent') ORDER BY created_at DESC LIMIT 1000");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo '  <url>' . "\n";
            echo '    <loc>' . $base_url . '/campaign-details.php?id=' . $row['id'] . '</loc>' . "\n";
            echo '    <lastmod>' . date('Y-m-d', strtotime($row['updated_at'] ?? $row['created_at'])) . '</lastmod>' . "\n";
            echo '    <changefreq>weekly</changefreq>' . "\n";
            echo '    <priority>0.7</priority>' . "\n";
            echo '  </url>' . "\n";
        }
    }
} catch(Exception $e) {}

// ============ MEMBER VOICES (PUBLISHED ONLY) ============
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'member_voices'");
    if($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, published_at, created_at, updated_at FROM member_voices WHERE status = 'published' ORDER BY published_at DESC LIMIT 1000");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $lastmod = date('Y-m-d', strtotime($row['published_at'] ?? $row['updated_at'] ?? $row['created_at']));
            echo '  <url>' . "\n";
            echo '    <loc>' . $base_url . '/member-voice.php?id=' . $row['id'] . '</loc>' . "\n";
            echo '    <lastmod>' . $lastmod . '</lastmod>' . "\n";
            echo '    <changefreq>weekly</changefreq>' . "\n";
            echo '    <priority>0.7</priority>' . "\n";
            echo '  </url>' . "\n";
        }
    }
} catch(Exception $e) {}

// ============ GALLERY ALBUMS ============
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'gallery_albums'");
    if($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, created_at, updated_at FROM gallery_albums ORDER BY created_at DESC LIMIT 1000");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo '  <url>' . "\n";
            echo '    <loc>' . $base_url . '/gallery-album.php?id=' . $row['id'] . '</loc>' . "\n";
            echo '    <lastmod>' . date('Y-m-d', strtotime($row['updated_at'] ?? $row['created_at'])) . '</lastmod>' . "\n";
            echo '    <changefreq>monthly</changefreq>' . "\n";
            echo '    <priority>0.5</priority>' . "\n";
            echo '  </url>' . "\n";
        }
    }
} catch(Exception $e) {}

// ============ VIDEO POSTS ============
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'video_posts'");
    if($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, created_at, updated_at FROM video_posts ORDER BY created_at DESC LIMIT 1000");
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo '  <url>' . "\n";
            echo '    <loc>' . $base_url . '/video-details.php?id=' . $row['id'] . '</loc>' . "\n";
            echo '    <lastmod>' . date('Y-m-d', strtotime($row['updated_at'] ?? $row['created_at'])) . '</lastmod>' . "\n";
            echo '    <changefreq>monthly</changefreq>' . "\n";
            echo '    <priority>0.6</priority>' . "\n";
            echo '  </url>' . "\n";
        }
    }
} catch(Exception $e) {}

echo '</urlset>';
?>