<?php
// Setze den include_path
chdir(dirname(__FILE__) . '/..');
set_include_path(get_include_path() . PATH_SEPARATOR . '.');

include_once 'core/main.class.php';
include_once 'core/cache.class.php';

class SitemapGenerator {
    private $db;
    private $base_url = 'https://intelectra.de';
    private $output_file;
    private $url_count = 0;
    
    public function __construct($base_object) {
        $this->db = $base_object->db;
        $this->output_file = getcwd() . '/sitemap.xml.gz';
    }
    
    public function generate($verbose = false) {
        $xml = new XMLWriter();
        $xml->openMemory();
        $xml->setIndent(true);
        $xml->startDocument('1.0', 'UTF-8');
        
        // Start sitemap
        $xml->startElement('urlset');
        $xml->writeAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
        
        // Startseite
        $this->addUrl($xml, $this->base_url, '1.0', 'daily', null, $verbose);
        
        // Statische Seiten
        $static_pages = [
            '/kontakt' => ['0.7', 'monthly'],
            '/impressum' => ['0.3', 'yearly'],
            '/agb' => ['0.3', 'yearly'],
            '/datenschutz' => ['0.3', 'yearly'],
            '/versand' => ['0.5', 'monthly'],
            '/ueber-uns' => ['0.6', 'monthly'],
            '/warenkorb' => ['0.4', 'monthly'],
            '/mein-konto' => ['0.4', 'monthly']
        ];
        
        foreach ($static_pages as $page => $settings) {
            $this->addUrl($xml, $this->base_url . $page, $settings[0], $settings[1], null, $verbose);
        }
        
        // Kategorien
        $sql = "SELECT id, url_text FROM item_groups WHERE active = 1";
        $result = $this->db->query($sql);
        if ($result) {
            while ($row = $result->fetch_object()) {
                $url = $this->base_url . '/' . $row->url_text;
                $this->addUrl($xml, $url, '0.8', 'weekly', null, $verbose);
            }
        }
        
        // Artikel
        $sql = "SELECT i.id, i.name, i.url_text, i.last_update 
                FROM items i 
                WHERE i.active = 1 
                AND i.visible = 1";
        
        $result = $this->db->query($sql);
        if ($result) {
            while ($row = $result->fetch_object()) {
                $url = $this->base_url . '/' . $row->url_text . '-' . $row->id . '.html';
                $lastmod = date('Y-m-d', strtotime($row->last_update));
                $this->addUrl($xml, $url, '0.6', 'weekly', $lastmod, $verbose);
            }
        }
        
        // Hersteller
        $sql = "SELECT id, url_text FROM vendor WHERE active = 1";
        $result = $this->db->query($sql);
        if ($result) {
            while ($row = $result->fetch_object()) {
                $url = $this->base_url . '/hersteller/' . $row->url_text;
                $this->addUrl($xml, $url, '0.7', 'weekly', null, $verbose);
            }
        }
        
        // End sitemap
        $xml->endElement();
        
        // Komprimiere und speichere
        $content = $xml->outputMemory();
        $compressed = gzencode($content, 9);
        
        // Speichere Dateien
        file_put_contents($this->output_file, $compressed);
        file_put_contents(str_replace('.gz', '', $this->output_file), $content);
        
        if ($verbose) {
            echo "\nGesamtzahl der URLs in der Sitemap: " . $this->url_count . "\n";
            echo "Sitemap wurde gespeichert unter:\n";
            echo "- " . $this->output_file . "\n";
            echo "- " . str_replace('.gz', '', $this->output_file) . "\n";
        }
        
        return true;
    }
    
    private function addUrl($xml, $loc, $priority = '0.5', $changefreq = 'weekly', $lastmod = null, $verbose = false) {
        $xml->startElement('url');
        $xml->writeElement('loc', $loc);
        if ($lastmod) {
            $xml->writeElement('lastmod', $lastmod);
        }
        $xml->writeElement('changefreq', $changefreq);
        $xml->writeElement('priority', $priority);
        $xml->endElement();
        
        if ($verbose) {
            echo "URL hinzugefügt: " . $loc . "\n";
        }
        $this->url_count++;
    }
}

// Führe die Generierung aus
try {
    // Erstelle base_object mit korrekter Konfiguration
    $base_object = new Main(['config_file' => 'config/config.php']);
    $generator = new SitemapGenerator($base_object);
    // Setze verbose=true für detaillierte Ausgabe
    if ($generator->generate(true)) {
        echo "\nSitemap wurde erfolgreich generiert.\n";
    }
} catch (Exception $e) {
    echo "Fehler bei der Sitemap-Generierung: " . $e->getMessage() . "\n";
} 