<?php
/**
 * Dynamic Sitemap XML Generator
 * Auto-generates sitemap.xml from database entries
 */

class SitemapGenerator {
    private $db;
    private $base_url;
    
    public function __construct($db, $base_url = null) {
        $this->db = $db;
        $this->base_url = $base_url ?? ('https://' . $_SERVER['HTTP_HOST']);
    }
    
    /**
     * Generate complete sitemap
     */
    public function generateSitemap() {
        $urls = [];
        
        // Add products
        $urls = array_merge($urls, $this->getProductUrls());
        
        // Add blogs
        $urls = array_merge($urls, $this->getBlogUrls());
        
        // Add static pages
        $urls = array_merge($urls, $this->getStaticPages());
        
        return $this->createSitemapXML($urls);
    }
    
    /**
     * Get product URLs
     */
    private function getProductUrls() {
        $urls = [];
        
        $query = "SELECT id, updated_at FROM products WHERE status = 'active' ORDER BY updated_at DESC LIMIT 50000";
        $result = $this->db->query($query);
        
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $urls[] = [
                    'loc' => $this->base_url . '/product.php?id=' . $row['id'],
                    'lastmod' => date('Y-m-d', strtotime($row['updated_at'])),
                    'changefreq' => 'weekly',
                    'priority' => '0.8'
                ];
            }
        }
        
        return $urls;
    }
    
    /**
     * Get blog URLs
     */
    private function getBlogUrls() {
        $urls = [];
        
        $query = "SELECT id, updated_at FROM blogs WHERE status = 'published' ORDER BY updated_at DESC LIMIT 50000";
        $result = $this->db->query($query);
        
        if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $urls[] = [
                    'loc' => $this->base_url . '/blog.php?id=' . $row['id'],
                    'lastmod' => date('Y-m-d', strtotime($row['updated_at'])),
                    'changefreq' => 'monthly',
                    'priority' => '0.7'
                ];
            }
        }
        
        return $urls;
    }
    
    /**
     * Get static pages
     */
    private function getStaticPages() {
        return [
            [
                'loc' => $this->base_url . '/index.php',
                'lastmod' => date('Y-m-d'),
                'changefreq' => 'daily',
                'priority' => '1.0'
            ],
            [
                'loc' => $this->base_url . '/about.php',
                'lastmod' => date('Y-m-d'),
                'changefreq' => 'monthly',
                'priority' => '0.8'
            ],
            [
                'loc' => $this->base_url . '/contact.php',
                'lastmod' => date('Y-m-d'),
                'changefreq' => 'monthly',
                'priority' => '0.7'
            ],
            [
                'loc' => $this->base_url . '/blogs.php',
                'lastmod' => date('Y-m-d'),
                'changefreq' => 'weekly',
                'priority' => '0.8'
            ]
        ];
    }
    
    /**
     * Create XML sitemap
     */
    private function createSitemapXML($urls) {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
        
        foreach ($urls as $url) {
            $xml .= '  <url>' . PHP_EOL;
            $xml .= '    <loc>' . htmlspecialchars($url['loc'], ENT_XML1, 'UTF-8') . '</loc>' . PHP_EOL;
            
            if (isset($url['lastmod'])) {
                $xml .= '    <lastmod>' . $url['lastmod'] . '</lastmod>' . PHP_EOL;
            }
            
            if (isset($url['changefreq'])) {
                $xml .= '    <changefreq>' . $url['changefreq'] . '</changefreq>' . PHP_EOL;
            }
            
            if (isset($url['priority'])) {
                $xml .= '    <priority>' . $url['priority'] . '</priority>' . PHP_EOL;
            }
            
            $xml .= '  </url>' . PHP_EOL;
        }
        
        $xml .= '</urlset>';
        
        return $xml;
    }
    
    /**
     * Save sitemap to file
     */
    public function saveSitemap($filepath = null) {
        $filepath = $filepath ?? $this->base_url . '/../sitemap.xml';
        $sitemap = $this->generateSitemap();
        
        return file_put_contents($filepath, $sitemap) !== false;
    }
}

// Handle sitemap generation request
if (isset($_GET['generate_sitemap'])) {
    require_once 'db_config.php';
    
    $db_config = [
        'host' => 'localhost',
        'user' => 'root',
        'password' => '',
        'database' => 'login-table'
    ];
    
    $db = new mysqli(
        $db_config['host'],
        $db_config['user'],
        $db_config['password'],
        $db_config['database']
    );
    
    if ($db->connect_error) {
        header('HTTP/1.0 404 Not Found');
        exit('Database connection failed');
    }
    
    $generator = new SitemapGenerator($db);
    
    // Save to file
    $sitemap_path = __DIR__ . '/sitemap.xml';
    if ($generator->saveSitemap($sitemap_path)) {
        echo json_encode(['success' => true, 'message' => 'Sitemap generated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save sitemap']);
    }
    exit;
}

// Return sitemap XML
if (basename($_SERVER['REQUEST_URI']) === 'sitemap.xml' || 
    preg_match('/sitemap\.xml/', $_SERVER['REQUEST_URI'])) {
    
    require_once 'db_config.php';
    
    $db_config = [
        'host' => 'localhost',
        'user' => 'root',
        'password' => '',
        'database' => 'login-table'
    ];
    
    $db = new mysqli(
        $db_config['host'],
        $db_config['user'],
        $db_config['password'],
        $db_config['database']
    );
    
    if ($db->connect_error) {
        header('HTTP/1.0 404 Not Found');
        exit('Not Found');
    }
    
    $generator = new SitemapGenerator($db);
    
    header('Content-Type: application/xml; charset=UTF-8');
    header('Cache-Control: max-age=86400');
    
    echo $generator->generateSitemap();
    exit;
}
?>
