<?php
/**
 * Dynamische XML Sitemap Generator für gallery.volleyball.lu
 * Generiert eine vollständige Sitemap basierend auf der Datenbank
 */

// Error Reporting für Debugging (in Produktion auskommentieren)
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// Output Buffering starten um saubere XML-Ausgabe zu gewährleisten
ob_start();

// Datenbankverbindung (Anpassen Sie die Credentials)
$host = 'localhost';
$dbname = 'volleyball_gallery';
$username = 'your_username';
$password = 'your_password';

$pdo = null;
$sitemap_content = '';

try {
    // Datenbankverbindung
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb3", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Aktuelle Domain und Datum
    $domain = 'https://gallery.volleyball.lu';
    $currentDate = date('Y-m-d');
    
    // XML in Variable sammeln
    $sitemap_content = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $sitemap_content .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
    $sitemap_content .= '        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n";
    $sitemap_content .= '        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9' . "\n";
    $sitemap_content .= '                           http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n\n";
    
    /**
     * Helper-Funktion für URL-Ausgabe
     */
    function addUrl($loc, $lastmod = null, $changefreq = 'weekly', $priority = '0.5') {
        global $currentDate;
        $lastmod = $lastmod ?: $currentDate;
        
        $url = "    <url>\n";
        $url .= "        <loc>" . htmlspecialchars($loc, ENT_XML1, 'UTF-8') . "</loc>\n";
        $url .= "        <lastmod>$lastmod</lastmod>\n";
        $url .= "        <changefreq>$changefreq</changefreq>\n";
        $url .= "        <priority>$priority</priority>\n";
        $url .= "    </url>\n\n";
        
        return $url;
    }
    
    // === STATISCHE HAUPTSEITEN ===
    $sitemap_content .= "    <!-- === HAUPTSEITEN === -->\n";
    $sitemap_content .= addUrl($domain . '/', $currentDate, 'daily', '1.0');
    $sitemap_content .= addUrl($domain . '/index.php', $currentDate, 'daily', '0.9');
    
    // === KATEGORIEN ===
    $sitemap_content .= "    <!-- === KATEGORIEN === -->\n";
    $categories = [
        'indoor' => ['name' => 'Indoor Volleyball', 'priority' => '0.9'],
        'beach' => ['name' => 'Beach Volleyball', 'priority' => '0.9'],
        'youth' => ['name' => 'Youth Volleyball', 'priority' => '0.8'],
        'team-luxembourg' => ['name' => 'Team Luxembourg', 'priority' => '0.9'],
        'international' => ['name' => 'International', 'priority' => '0.8'],
        'fun-tournaments' => ['name' => 'Fun Tournaments', 'priority' => '0.7'],
        'events' => ['name' => 'Events', 'priority' => '0.6'],
        'novotel-cup' => ['name' => 'Novotel Cup', 'priority' => '0.7'],
        'jpee-gsse' => ['name' => 'JPEE/GSSE', 'priority' => '0.6']
    ];
    
    $years = [2025, 2024, 2023, 2022, 2021, 2020, 2019, 2018, 2017];
    
    foreach ($categories as $catKey => $catData) {
        // Kategorie ohne Jahr
        $sitemap_content .= addUrl($domain . "/index.php?page=category&amp;category=$catKey", $currentDate, 'weekly', $catData['priority']);
        
        // Kategorie mit Jahren
        foreach ($years as $year) {
            $changefreq = ($year == 2025) ? 'daily' : (($year >= 2024) ? 'weekly' : 'monthly');
            $priority = ($year == 2025) ? '0.8' : (($year >= 2024) ? '0.7' : '0.6');
            $sitemap_content .= addUrl($domain . "/index.php?page=category&amp;category=$catKey&amp;year=$year", $currentDate, $changefreq, $priority);
        }
    }
    
    // === ALLE MATCHES/ALBEN AUS DATENBANK ===
    $sitemap_content .= "    <!-- === ALLE MATCH-ALBEN === -->\n";
    $match_count = 0;
    
    try {
        // Alle Matches mit Details abrufen
        $stmt = $pdo->prepare("
            SELECT 
                m.id,
                m.event_date,
                m.category,
                m.freetext,
                ca.short_name as teamA_name,
                cb.short_name as teamB_name,
                l.short_name as league_name,
                (SELECT COUNT(*) FROM uploads u WHERE u.gallery_id = m.id) as photo_count
            FROM matches m
            LEFT JOIN clubs ca ON m.teamA = ca.id
            LEFT JOIN clubs cb ON m.teamB = cb.id
            LEFT JOIN leagues l ON m.league = l.id
            WHERE m.id IS NOT NULL
            ORDER BY m.event_date DESC, m.id DESC
        ");
        
        $stmt->execute();
        $matches = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($matches as $match) {
            $match_count++;
            
            // Priorität basierend auf Datum und Foto-Anzahl
            $matchDate = DateTime::createFromFormat('Y-m-d', $match['event_date']);
            if ($matchDate) {
                $now = new DateTime();
                $daysDiff = $now->diff($matchDate)->days;
                
                if ($daysDiff <= 30) {
                    $priority = '0.8';
                    $changefreq = 'daily';
                } elseif ($daysDiff <= 365) {
                    $priority = '0.7';
                    $changefreq = 'weekly';
                } else {
                    $priority = '0.6';
                    $changefreq = 'monthly';
                }
                
                // Höhere Priorität für Matches mit vielen Fotos
                if ($match['photo_count'] > 100) {
                    $priority = min(1.0, (float)$priority + 0.1);
                }
                
                // Match-Album URL
                $albumUrl = $domain . "/index.php?page=thumbnails&amp;album=" . $match['id'];
                $sitemap_content .= addUrl($albumUrl, $match['event_date'], $changefreq, $priority);
            }
        }
        
        $sitemap_content .= "    <!-- Anzahl Match-Alben: $match_count -->\n\n";
        
    } catch(PDOException $e) {
        $sitemap_content .= "    <!-- Fehler beim Laden der Matches: " . htmlspecialchars($e->getMessage()) . " -->\n\n";
    }
    
    // === ALLE FOTOGRAFEN ===
    $sitemap_content .= "    <!-- === FOTOGRAFEN === -->\n";
    $photographer_count = 0;
    
    try {
        $stmt = $pdo->prepare("
            SELECT DISTINCT photographer, COUNT(*) as photo_count
            FROM uploads 
            WHERE photographer != '' AND photographer IS NOT NULL
            GROUP BY photographer
            ORDER BY photo_count DESC
            LIMIT 50
        ");
        
        $stmt->execute();
        $photographers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($photographers as $photographer) {
            $photographer_count++;
            $photographerSlug = urlencode(strtolower(str_replace([' ', '.', '-'], ['_', '_', '_'], $photographer['photographer'])));
            $priority = ($photographer['photo_count'] > 500) ? '0.7' : '0.6';
            
            $sitemap_content .= addUrl($domain . "/index.php?page=photographer&amp;name=$photographerSlug", $currentDate, 'weekly', $priority);
        }
        
        $sitemap_content .= "    <!-- Anzahl Fotografen: $photographer_count -->\n\n";
        
    } catch(PDOException $e) {
        $sitemap_content .= "    <!-- Fehler beim Laden der Fotografen: " . htmlspecialchars($e->getMessage()) . " -->\n\n";
    }
    
    // === ALLE VEREINE ===
    $sitemap_content .= "    <!-- === VEREINE === -->\n";
    $club_count = 0;
    
    try {
        $stmt = $pdo->prepare("
            SELECT c.id, c.short_name, c.long_name, c.country,
                   (SELECT COUNT(*) FROM matches m1 WHERE m1.teamA = c.id) +
                   (SELECT COUNT(*) FROM matches m2 WHERE m2.teamB = c.id) as match_count
            FROM clubs c
            HAVING match_count > 0
            ORDER BY match_count DESC, c.short_name
            LIMIT 100
        ");
        
        $stmt->execute();
        $clubs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        foreach ($clubs as $club) {
            $club_count++;
            $clubSlug = urlencode(strtolower(str_replace([' ', '.', '-'], ['_', '_', '_'], $club['short_name'])));
            $priority = ($club['match_count'] > 10) ? '0.7' : '0.6';
            
            $sitemap_content .= addUrl($domain . "/index.php?page=club&amp;id=" . $club['id'], $currentDate, 'monthly', $priority);
        }
        
        $sitemap_content .= "    <!-- Anzahl Vereine: $club_count -->\n\n";
        
    } catch(PDOException $e) {
        $sitemap_content .= "    <!-- Fehler beim Laden der Vereine: " . htmlspecialchars($e->getMessage()) . " -->\n\n";
    }
    
    // === NAVIGATION & SYSTEM-SEITEN ===
    $sitemap_content .= "    <!-- === NAVIGATION & SYSTEM === -->\n";
    $systemPages = [
        'albums' => ['priority' => '0.9', 'changefreq' => 'daily'],
        'photos' => ['priority' => '0.9', 'changefreq' => 'daily'],
        'latest' => ['priority' => '0.8', 'changefreq' => 'hourly'],
        'popular' => ['priority' => '0.8', 'changefreq' => 'daily'],
        'search' => ['priority' => '0.7', 'changefreq' => 'weekly'],
        'tags' => ['priority' => '0.7', 'changefreq' => 'weekly'],
        'photographers' => ['priority' => '0.8', 'changefreq' => 'weekly'],
        'clubs' => ['priority' => '0.8', 'changefreq' => 'weekly'],
        'leagues' => ['priority' => '0.7', 'changefreq' => 'monthly'],
        'shop' => ['priority' => '0.8', 'changefreq' => 'weekly'],
        'upload' => ['priority' => '0.6', 'changefreq' => 'monthly'],
        'login' => ['priority' => '0.4', 'changefreq' => 'monthly'],
        'register' => ['priority' => '0.4', 'changefreq' => 'monthly'],
        'contact' => ['priority' => '0.6', 'changefreq' => 'monthly'],
        'statistics' => ['priority' => '0.6', 'changefreq' => 'daily'],
        'help' => ['priority' => '0.4', 'changefreq' => 'monthly'],
        'privacy' => ['priority' => '0.4', 'changefreq' => 'yearly'],
        'sitemap' => ['priority' => '0.3', 'changefreq' => 'weekly']
    ];
    
    foreach ($systemPages as $page => $config) {
        $sitemap_content .= addUrl($domain . "/index.php?page=$page", $currentDate, $config['changefreq'], $config['priority']);
    }
    
    // === STATISTIKEN ===
    $sitemap_content .= "    <!-- === SITEMAP STATISTIKEN === -->\n";
    try {
        $stats = [
            'matches' => $pdo->query("SELECT COUNT(*) FROM matches")->fetchColumn(),
            'uploads' => $pdo->query("SELECT COUNT(*) FROM uploads")->fetchColumn(),
            'clubs' => $pdo->query("SELECT COUNT(*) FROM clubs")->fetchColumn(),
            'users' => $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn()
        ];
        
        $sitemap_content .= "    <!-- \n";
        $sitemap_content .= "    Sitemap generiert am: $currentDate\n";
        $sitemap_content .= "    Matches: {$stats['matches']}\n";
        $sitemap_content .= "    Uploads: {$stats['uploads']}\n";
        $sitemap_content .= "    Vereine: {$stats['clubs']}\n";
        $sitemap_content .= "    Benutzer: {$stats['users']}\n";
        $sitemap_content .= "    URLs in Sitemap: " . substr_count($sitemap_content, '<url>') . "\n";
        $sitemap_content .= "    -->\n\n";
        
    } catch(PDOException $e) {
        $sitemap_content .= "    <!-- Fehler beim Laden der Statistiken: " . htmlspecialchars($e->getMessage()) . " -->\n\n";
    }
    
    // XML Footer
    $sitemap_content .= "</urlset>";
    
} catch(Exception $e) {
    // Bei jedem Fehler eine Minimal-Sitemap ausgeben
    $sitemap_content = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $sitemap_content .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    $sitemap_content .= "    <!-- Fehler beim Generieren der Sitemap: " . htmlspecialchars($e->getMessage()) . " -->\n";
    $sitemap_content .= "    <url>\n";
    $sitemap_content .= "        <loc>https://gallery.volleyball.lu/</loc>\n";
    $sitemap_content .= "        <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    $sitemap_content .= "        <changefreq>daily</changefreq>\n";
    $sitemap_content .= "        <priority>1.0</priority>\n";
    $sitemap_content .= "    </url>\n";
    $sitemap_content .= "</urlset>";
} finally {
    // Datenbankverbindung schließen
    if ($pdo) {
        $pdo = null;
    }
}

// Output Buffer leeren
ob_end_clean();

// Content-Type für XML setzen und Inhalt ausgeben
header('Content-Type: application/xml; charset=utf-8');
echo $sitemap_content;
?>