<?php
/**
 * Static Sitemap Generator
 * Generate file sitemap.xml yang bisa di-cache
 */
require_once __DIR__ . '/auth.php';

function generateStaticSitemap() {
    $jobs = readJSON(JOB_FILE);
    $panelData = readJSON(PANEL_FILE);
    $settings = $panelData['settings'] ?? [];
    $pages = $panelData['pages'] ?? [];
    
    $siteUrl = rtrim($settings['site_url'] ?? 'http://localhost/project', '/');
    $now = date('Y-m-d\TH:i:sP');
    
    $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . "\n";
    $xml .= '        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . "\n";
    
    // Homepage
    $xml .= "  <url>\n";
    $xml .= "    <loc>{$siteUrl}/</loc>\n";
    $xml .= "    <lastmod>{$now}</lastmod>\n";
    $xml .= "    <changefreq>daily</changefreq>\n";
    $xml .= "    <priority>1.0</priority>\n";
    $xml .= "  </url>\n";
    
    // Static pages
    foreach ($pages as $key => $page) {
        if (($page['status'] ?? '') !== 'published') continue;
        $xml .= "  <url>\n";
        $xml .= "    <loc>{$siteUrl}/index.php?page={$key}</loc>\n";
        $xml .= "    <lastmod>{$now}</lastmod>\n";
        $xml .= "    <changefreq>monthly</changefreq>\n";
        $xml .= "    <priority>0.5</priority>\n";
        $xml .= "  </url>\n";
    }
    
    // Job categories
    foreach (['FULL_TIME', 'PART_TIME', 'CONTRACTOR', 'INTERN', 'REMOTE'] as $type) {
        $xml .= "  <url>\n";
        $xml .= "    <loc>{$siteUrl}/index.php?type={$type}</loc>\n";
        $xml .= "    <lastmod>{$now}</lastmod>\n";
        $xml .= "    <changefreq>daily</changefreq>\n";
        $xml .= "    <priority>0.7</priority>\n";
        $xml .= "  </url>\n";
    }
    
    // Job postings
    foreach ($jobs as $job) {
        if (($job['status'] ?? 'published') !== 'published') continue;
        $slug = $job['slug'] ?? '';
        if (!$slug) continue;
        
        $lastmod = $job['updated_at'] ?? $job['created_at'] ?? $job['datePosted'] ?? date('Y-m-d');
        $views = $job['views'] ?? 0;
        $priority = $views > 100 ? '0.9' : ($views > 50 ? '0.8' : ($views > 10 ? '0.7' : '0.6'));
        
        $posted = strtotime($job['datePosted'] ?? 'now');
        $daysAgo = (time() - $posted) / 86400;
        $changefreq = $daysAgo < 3 ? 'hourly' : ($daysAgo < 14 ? 'daily' : ($daysAgo < 30 ? 'weekly' : 'monthly'));
        
        $xml .= "  <url>\n";
        $xml .= "    <loc>{$siteUrl}/detail.php?slug=" . urlencode($slug) . "</loc>\n";
        $xml .= "    <lastmod>" . date('Y-m-d\TH:i:sP', strtotime($lastmod)) . "</lastmod>\n";
        $xml .= "    <changefreq>{$changefreq}</changefreq>\n";
        $xml .= "    <priority>{$priority}</priority>\n";
        
        if (!empty($settings['logo'])) {
            $logo = htmlspecialchars($settings['logo'], ENT_XML1);
            $company = htmlspecialchars($job['company'] ?? '', ENT_XML1);
            $xml .= "    <image:image>\n";
            $xml .= "      <image:loc>{$siteUrl}/uploads/{$logo}</image:loc>\n";
            $xml .= "      <image:title>{$company} Logo</image:title>\n";
            $xml .= "    </image:image>\n";
        }
        
        $xml .= "  </url>\n";
    }
    
    $xml .= "</urlset>\n";
    
    // Write to file
    $sitemapPath = __DIR__ . '/sitemap.xml';
    file_put_contents($sitemapPath, $xml);
    
    return [
        'path' => $sitemapPath,
        'size' => filesize($sitemapPath),
        'url_count' => substr_count($xml, '<url>'),
        'job_count' => count(array_filter($jobs, fn($j) => ($j['status'] ?? 'published') === 'published'))
    ];
}

// Auto-run jika diakses via browser
if (php_sapi_name() !== 'cli') {
    header('Content-Type: text/plain; charset=utf-8');
    $result = generateStaticSitemap();
    echo "✅ Sitemap Generated Successfully!\n\n";
    echo "📁 File: sitemap.xml\n";
    echo "📊 Size: " . number_format($result['size']) . " bytes\n";
    echo "🔗 Total URLs: {$result['url_count']}\n";
    echo "💼 Jobs: {$result['job_count']}\n";
    echo "🌐 URL: " . ($panelData['settings']['site_url'] ?? 'http://localhost/project') . "/sitemap.xml\n";
}