<?php
/**
 * Dynamic XML Sitemap with hreflang support
 * Automatically includes all active restaurants, cafes, blogs, OPGs
 * No .htaccess required - direct PHP execution
 */

// Set XML header
header('Content-Type: application/xml; charset=utf-8');

// Database connection
$host = 'localhost';
$dbname = 'makarsk3_makarskagastroguide';
$username = 'makarsk3_mgastro2';
$password = '^Ivlq!n-(LAsH$Dv';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("<!-- Database connection error: " . $e->getMessage() . " -->");
}

// Supported languages
$languages = ['hr', 'en', 'de', 'it', 'pl', 'cs'];
$base_url = 'https://www.makarskagastro.com';

// Helper function to generate language URLs
function getLangUrl($base, $slug, $type, $lang, $base_url) {
    if ($type === 'restaurant') {
        $url = $base_url . '/restaurant.php?slug=' . urlencode($slug);
    } elseif ($type === 'cafe') {
        $url = $base_url . '/cafes.php?slug=' . urlencode($slug);
    } elseif ($type === 'blog') {
        $url = $base_url . '/blog.php?id=' . $slug;
    } elseif ($type === 'opg') {
        $url = $base_url . '/opg.php?id=' . $slug;
    } else {
        return $base_url . '/index.php';
    }
    
    if ($lang !== 'hr') {
        $url .= '&lang=' . $lang;
    }
    return $url;
}

// Helper function to generate hreflang XML
function generateHreflang($urls, $xdefault_url) {
    $output = '';
    foreach ($urls as $hreflang => $url) {
        $output .= '        <xhtml:link rel="alternate" hreflang="' . $hreflang . '" href="' . htmlspecialchars($url) . '"/>' . "\n";
    }
    $output .= '        <xhtml:link rel="alternate" hreflang="x-default" href="' . htmlspecialchars($xdefault_url) . '"/>' . "\n";
    return $output;
}

// Start XML output
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">' . "\n";

// ============================================
// 1. HOMEPAGE (all languages)
// ============================================
$home_urls = [];
foreach ($languages as $lang) {
    $home_urls[$lang] = $base_url . '/index.php' . ($lang !== 'hr' ? '?lang=' . $lang : '');
}
$home_xdefault = $base_url . '/index.php';

echo '    <url>' . "\n";
echo '        <loc>' . htmlspecialchars($base_url . '/index.php') . '</loc>' . "\n";
echo generateHreflang($home_urls, $home_xdefault);
echo '        <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
echo '        <changefreq>daily</changefreq>' . "\n";
echo '        <priority>1.0</priority>' . "\n";
echo '    </url>' . "\n";

// ============================================
// 2. RESTAURANTS
// ============================================
try {
    $stmt = $pdo->query("SELECT id, slug, last_updated FROM restaurants WHERE is_active = 1 AND slug IS NOT NULL AND slug != '' ORDER BY id");
    $restaurants = $stmt->fetchAll();
    
    foreach ($restaurants as $restaurant) {
        $slug = $restaurant['slug'];
        $lastmod = !empty($restaurant['last_updated']) && $restaurant['last_updated'] != '0000-00-00 00:00:00' 
                   ? date('Y-m-d', strtotime($restaurant['last_updated'])) 
                   : date('Y-m-d');
        
        $lang_urls = [];
        foreach ($languages as $lang) {
            $lang_urls[$lang] = getLangUrl($base_url, $slug, 'restaurant', $lang, $base_url);
        }
        $xdefault_url = getLangUrl($base_url, $slug, 'restaurant', 'hr', $base_url);
        
        echo '    <url>' . "\n";
        echo '        <loc>' . htmlspecialchars(getLangUrl($base_url, $slug, 'restaurant', 'hr', $base_url)) . '</loc>' . "\n";
        echo generateHreflang($lang_urls, $xdefault_url);
        echo '        <lastmod>' . $lastmod . '</lastmod>' . "\n";
        echo '        <changefreq>weekly</changefreq>' . "\n";
        echo '        <priority>0.8</priority>' . "\n";
        echo '    </url>' . "\n";
    }
} catch (Exception $e) {
    echo '    <!-- Error loading restaurants: ' . $e->getMessage() . ' -->' . "\n";
}

// ============================================
// 3. CAFES
// ============================================
try {
    $stmt = $pdo->query("SELECT id, slug, last_updated FROM cafes WHERE active = 1 AND slug IS NOT NULL AND slug != '' ORDER BY id");
    $cafes = $stmt->fetchAll();
    
    foreach ($cafes as $cafe) {
        $slug = $cafe['slug'];
        $lastmod = !empty($cafe['last_updated']) && $cafe['last_updated'] != '0000-00-00 00:00:00' 
                   ? date('Y-m-d', strtotime($cafe['last_updated'])) 
                   : date('Y-m-d');
        
        $lang_urls = [];
        foreach ($languages as $lang) {
            $lang_urls[$lang] = getLangUrl($base_url, $slug, 'cafe', $lang, $base_url);
        }
        $xdefault_url = getLangUrl($base_url, $slug, 'cafe', 'hr', $base_url);
        
        echo '    <url>' . "\n";
        echo '        <loc>' . htmlspecialchars(getLangUrl($base_url, $slug, 'cafe', 'hr', $base_url)) . '</loc>' . "\n";
        echo generateHreflang($lang_urls, $xdefault_url);
        echo '        <lastmod>' . $lastmod . '</lastmod>' . "\n";
        echo '        <changefreq>weekly</changefreq>' . "\n";
        echo '        <priority>0.8</priority>' . "\n";
        echo '    </url>' . "\n";
    }
} catch (Exception $e) {
    echo '    <!-- Error loading cafes: ' . $e->getMessage() . ' -->' . "\n";
}

// ============================================
// 4. BLOGS (if table exists)
// ============================================
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'blogs'");
    if ($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, slug, created_at FROM blogs WHERE is_active = 1 ORDER BY id");
        $blogs = $stmt->fetchAll();
        
        foreach ($blogs as $blog) {
            $slug = $blog['slug'] ?? $blog['id'];
            $lastmod = !empty($blog['created_at']) && $blog['created_at'] != '0000-00-00 00:00:00' 
                       ? date('Y-m-d', strtotime($blog['created_at'])) 
                       : date('Y-m-d');
            
            $lang_urls = [];
            foreach ($languages as $lang) {
                $lang_urls[$lang] = getLangUrl($base_url, $slug, 'blog', $lang, $base_url);
            }
            $xdefault_url = getLangUrl($base_url, $slug, 'blog', 'hr', $base_url);
            
            echo '    <url>' . "\n";
            echo '        <loc>' . htmlspecialchars(getLangUrl($base_url, $slug, 'blog', 'hr', $base_url)) . '</loc>' . "\n";
            echo generateHreflang($lang_urls, $xdefault_url);
            echo '        <lastmod>' . $lastmod . '</lastmod>' . "\n";
            echo '        <changefreq>weekly</changefreq>' . "\n";
            echo '        <priority>0.7</priority>' . "\n";
            echo '    </url>' . "\n";
        }
    }
} catch (Exception $e) {
    // Blog table may not exist - skip silently
}

// ============================================
// 5. OPGs (if table exists)
// ============================================
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'opgs'");
    if ($stmt->rowCount() > 0) {
        $stmt = $pdo->query("SELECT id, slug, updated_at FROM opgs WHERE is_active = 1 ORDER BY id");
        $opgs = $stmt->fetchAll();
        
        foreach ($opgs as $opg) {
            $slug = $opg['slug'] ?? $opg['id'];
            $lastmod = !empty($opg['updated_at']) && $opg['updated_at'] != '0000-00-00 00:00:00' 
                       ? date('Y-m-d', strtotime($opg['updated_at'])) 
                       : date('Y-m-d');
            
            $lang_urls = [];
            foreach ($languages as $lang) {
                $lang_urls[$lang] = getLangUrl($base_url, $slug, 'opg', $lang, $base_url);
            }
            $xdefault_url = getLangUrl($base_url, $slug, 'opg', 'hr', $base_url);
            
            echo '    <url>' . "\n";
            echo '        <loc>' . htmlspecialchars(getLangUrl($base_url, $slug, 'opg', 'hr', $base_url)) . '</loc>' . "\n";
            echo generateHreflang($lang_urls, $xdefault_url);
            echo '        <lastmod>' . $lastmod . '</lastmod>' . "\n";
            echo '        <changefreq>weekly</changefreq>' . "\n";
            echo '        <priority>0.7</priority>' . "\n";
            echo '    </url>' . "\n";
        }
    }
} catch (Exception $e) {
    // OPG table may not exist - skip silently
}

// ============================================
// 6. STATIC PAGES (all languages)
// ============================================
$static_pages = [
    'restaurants-list' => ['changefreq' => 'daily', 'priority' => '0.8'],
    'cafes-list' => ['changefreq' => 'daily', 'priority' => '0.8'],
    'price-search' => ['changefreq' => 'daily', 'priority' => '0.7'],
    'budget' => ['changefreq' => 'weekly', 'priority' => '0.6'],
    'near' => ['changefreq' => 'weekly', 'priority' => '0.6'],
    'group' => ['changefreq' => 'weekly', 'priority' => '0.6'],
    'contact' => ['changefreq' => 'monthly', 'priority' => '0.5'],
    'privacy' => ['changefreq' => 'monthly', 'priority' => '0.3'],
    'terms' => ['changefreq' => 'monthly', 'priority' => '0.3'],
    'impressum' => ['changefreq' => 'monthly', 'priority' => '0.3']
];

foreach ($static_pages as $page => $settings) {
    $lang_urls = [];
    foreach ($languages as $lang) {
        $lang_urls[$lang] = $base_url . '/' . $page . '.php' . ($lang !== 'hr' ? '?lang=' . $lang : '');
    }
    $xdefault_url = $base_url . '/' . $page . '.php';
    
    echo '    <url>' . "\n";
    echo '        <loc>' . htmlspecialchars($base_url . '/' . $page . '.php') . '</loc>' . "\n";
    echo generateHreflang($lang_urls, $xdefault_url);
    echo '        <lastmod>' . date('Y-m-d') . '</lastmod>' . "\n";
    echo '        <changefreq>' . $settings['changefreq'] . '</changefreq>' . "\n";
    echo '        <priority>' . $settings['priority'] . '</priority>' . "\n";
    echo '    </url>' . "\n";
}

// Close urlset
echo '</urlset>';