<?php
/**
 * sitemap.php / sitemap.xml
 * The Scale Journal - XML Sitemap Generator
 * Fixed: XML validation, error handling, output buffering
 */

// Clear any previous output
if (ob_get_level()) {
    ob_end_clean();
}

// Set headers BEFORE any output
header("Content-Type: application/xml; charset=utf-8");
header("X-Robots-Tag: noindex, follow");

// Start fresh output buffer
ob_start();

// Database connection with error handling
try {
    require_once 'db_connect.php';
} catch (Exception $e) {
    // Return empty but valid sitemap on DB error
    outputEmptySitemap("Database connection failed");
    exit;
}

// ============================================================================
// CONFIGURATION
// ============================================================================
const JOURNAL_ISSN = '2992-3727';
const JOURNAL_TITLE = 'The Scale Journal';
const MAX_URLS = 50000;

// ============================================================================
// HELPERS
// ============================================================================

function xmlEscape(string $text): string {
    // Remove invalid XML characters
    $text = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u', '', $text);
    return htmlspecialchars($text ?? '', ENT_XML1 | ENT_QUOTES, 'UTF-8');
}

function w3cDate(string $date): string {
    $timestamp = strtotime($date);
    if ($timestamp === false) {
        $timestamp = time();
    }
    return date('Y-m-d\TH:i:sP', $timestamp);
}

function outputEmptySitemap(string $reason = '') {
    echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
    echo '<!-- Error: ' . xmlEscape($reason) . ' -->' . PHP_EOL;
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL;
    echo '</urlset>' . PHP_EOL;
    ob_end_flush();
}

// ============================================================================
// BUILD SITEMAP
// ============================================================================

$baseUrl = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
$urlCount = 0;

// Start XML output
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
echo '<!-- ' . xmlEscape(JOURNAL_TITLE) . ' Sitemap -->' . PHP_EOL;
echo '<!-- ISSN: ' . JOURNAL_ISSN . ' -->' . PHP_EOL;
echo '<!-- Generated: ' . date('c') . ' -->' . PHP_EOL;
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . PHP_EOL;

// ============================================================================
// 1. STATIC PAGES
// ============================================================================

$staticPages = [
    ['url' => '/index.php', 'priority' => '1.0', 'changefreq' => 'weekly'],
    ['url' => '/journal.php', 'priority' => '0.9', 'changefreq' => 'daily'],
    ['url' => '/conference-proceedings.php', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['url' => '/current-issue.php', 'priority' => '0.9', 'changefreq' => 'weekly'],
    ['url' => '/submission.php', 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['url' => '/about.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['url' => '/editorial-board.php', 'priority' => '0.6', 'changefreq' => 'monthly'],
    ['url' => '/guidelines.php', 'priority' => '0.6', 'changefreq' => 'monthly'],
    ['url' => '/contact.php', 'priority' => '0.5', 'changefreq' => 'yearly'],
];

foreach ($staticPages as $page) {
    if ($urlCount >= MAX_URLS) break;
    
    echo "  <url>\n";
    echo "    <loc>" . xmlEscape($baseUrl . $page['url']) . "</loc>\n";
    echo "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
    echo "    <changefreq>" . $page['changefreq'] . "</changefreq>\n";
    echo "    <priority>" . $page['priority'] . "</priority>\n";
    echo "  </url>\n";
    
    $urlCount++;
}

// ============================================================================
// 2. JOURNAL ARTICLES
// ============================================================================

try {
    $stmt = $pdo->query("
        SELECT id, article_title, created_at, updated_at, pdf_path 
        FROM journal_articles 
        WHERE article_title IS NOT NULL 
          AND article_title != ''
          AND article_title != 'All Author(s) and Co-author(s)'
        ORDER BY created_at DESC 
        LIMIT " . (MAX_URLS - $urlCount - 1000)
    );

    while ($row = $stmt->fetch()) {
        if ($urlCount >= MAX_URLS) break;
        
        $articleUrl = $baseUrl . '/view-article.php?id=' . (int)$row['id'];
        $lastMod = w3cDate($row['updated_at'] ?? $row['created_at']);
        
        echo "  <url>\n";
        echo "    <loc>" . xmlEscape($articleUrl) . "</loc>\n";
        echo "    <lastmod>" . $lastMod . "</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>1.0</priority>\n";
        echo "    <image:image>\n";
        echo "      <image:loc>" . xmlEscape($baseUrl . '/assets/img/journal-cover.png') . "</image:loc>\n";
        echo "      <image:title>" . xmlEscape($row['article_title']) . "</image:title>\n";
        echo "    </image:image>\n";
        echo "  </url>\n";
        
        // PDF URL
        if (!empty($row['pdf_path']) && $row['pdf_path'] !== 'uploads') {
            if ($urlCount >= MAX_URLS) break;
            
            $pdfUrl = $baseUrl . '/' . ltrim($row['pdf_path'], '/');
            
            echo "  <url>\n";
            echo "    <loc>" . xmlEscape($pdfUrl) . "</loc>\n";
            echo "    <lastmod>" . $lastMod . "</lastmod>\n";
            echo "    <changefreq>never</changefreq>\n";
            echo "    <priority>0.9</priority>\n";
            echo "  </url>\n";
            
            $urlCount++;
        }
        
        $urlCount++;
    }
} catch (PDOException $e) {
    echo "<!-- Journal articles error: " . xmlEscape($e->getMessage()) . " -->\n";
}

// ============================================================================
// 3. CONFERENCE PROCEEDINGS
// ============================================================================

try {
    // Grouped conferences
    $confStmt = $pdo->query("
        SELECT DISTINCT conference_name, MAX(created_at) as last_mod
        FROM conference_articles 
        WHERE conference_name IS NOT NULL 
          AND conference_name != ''
          AND conference_name != 'All Author(s) and Co-author(s)'
          AND title IS NOT NULL
          AND title != ''
        GROUP BY conference_name
        ORDER BY last_mod DESC
        LIMIT 100
    ");
    
    while ($conf = $confStmt->fetch()) {
        if ($urlCount >= MAX_URLS) break;
        
        $confUrl = $baseUrl . '/conference-proceedings.php?conf=' . urlencode($conf['conference_name']);
        
        echo "  <url>\n";
        echo "    <loc>" . xmlEscape($confUrl) . "</loc>\n";
        echo "    <lastmod>" . w3cDate($conf['last_mod']) . "</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.8</priority>\n";
        echo "  </url>\n";
        
        $urlCount++;
    }
    
    // Individual conference articles
    $confArticleStmt = $pdo->query("
        SELECT id, title, conference_name, pdf_link, created_at, updated_at
        FROM conference_articles 
        WHERE title IS NOT NULL 
          AND title != ''
          AND title != 'All Author(s) and Co-author(s)'
        ORDER BY created_at DESC
        LIMIT " . (MAX_URLS - $urlCount - 500)
    ");
    
    while ($article = $confArticleStmt->fetch()) {
        if ($urlCount >= MAX_URLS) break;
        
        $articleUrl = $baseUrl . '/view-article.php?id=' . (int)$article['id'] . '&type=conference';
        $lastMod = w3cDate($article['updated_at'] ?? $article['created_at']);
        
        echo "  <url>\n";
        echo "    <loc>" . xmlEscape($articleUrl) . "</loc>\n";
        echo "    <lastmod>" . $lastMod . "</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.9</priority>\n";
        echo "  </url>\n";
        
        // Conference PDF
        if (!empty($article['pdf_link']) && $article['pdf_link'] !== 'uploads') {
            if ($urlCount >= MAX_URLS) break;
            
            $pdfUrl = $baseUrl . '/' . ltrim($article['pdf_link'], '/');
            
            echo "  <url>\n";
            echo "    <loc>" . xmlEscape($pdfUrl) . "</loc>\n";
            echo "    <lastmod>" . $lastMod . "</lastmod>\n";
            echo "    <changefreq>never</changefreq>\n";
            echo "    <priority>0.8</priority>\n";
            echo "  </url>\n";
            
            $urlCount++;
        }
        
        $urlCount++;
    }
    
} catch (PDOException $e) {
    echo "<!-- Conference error: " . xmlEscape($e->getMessage()) . " -->\n";
}

// ============================================================================
// 4. COLLECTIONS (Optional)
// ============================================================================

try {
    $collStmt = $pdo->query("
        SELECT id, collection_title, created_at, updated_at
        FROM collections 
        WHERE is_published = 1 OR is_published IS NULL
        ORDER BY created_at DESC
        LIMIT 50
    ");
    
    while ($coll = $collStmt->fetch()) {
        if ($urlCount >= MAX_URLS) break;
        
        $collUrl = $baseUrl . '/view-collection.php?id=' . (int)$coll['id'];
        $lastMod = w3cDate($coll['updated_at'] ?? $coll['created_at']);
        
        echo "  <url>\n";
        echo "    <loc>" . xmlEscape($collUrl) . "</loc>\n";
        echo "    <lastmod>" . $lastMod . "</lastmod>\n";
        echo "    <changefreq>monthly</changefreq>\n";
        echo "    <priority>0.8</priority>\n";
        echo "  </url>\n";
        
        $urlCount++;
    }
} catch (PDOException $e) {
    // Collections table doesn't exist - skip silently
    echo "<!-- Collections not available -->\n";
}

// Close XML
echo '</urlset>' . PHP_EOL;

// Log and flush
error_log("Sitemap: $urlCount URLs");
ob_end_flush();