<?php
/* ============================================
   sitemap.php - نسخة محصّنة ضد الأخطاء
============================================ */

// تنظيف أي output سابق (بما فيه BOM)
if (ob_get_level()) {
    ob_end_clean();
}
ob_start();

// حذف BOM إذا كان موجوداً
if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
    // بعض البيئات تضيف BOM، نتحقق ونحذفه
}

header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noindex');

$cacheFile = __DIR__ . '/sitemap.cache.xml';
$cacheTime = 3600;

if (isset($_GET['clear'])) {
    @unlink($cacheFile);
}

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
    $cached = file_get_contents($cacheFile);
    // تأكد أن الكاش سليم
    if (strpos($cached, '</urlset>') !== false && 
        substr(trim($cached), -10) === '</urlset>') {
        ob_end_clean();
        readfile($cacheFile);
        exit;
    } else {
        @unlink($cacheFile);  // كاش تالف، احذفه
    }
}

$html = @file_get_contents(__DIR__ . '/audio.html');
if ($html === false) {
    ob_end_clean();
    http_response_code(500);
    echo '<?xml version="1.0" encoding="UTF-8"?><error>audio.html not found</error>';
    exit;
}

// حذف BOM من audio.html إذا كان موجوداً
$html = preg_replace('/^\xEF\xBB\xBF/', '', $html);

function extractSongsArray($html) {
    $startPos = strpos($html, 'const SONGS');
    if ($startPos === false) return null;
    $arrayStart = strpos($html, '[', $startPos);
    if ($arrayStart === false) return null;

    $depth = 0; $inString = false; $stringChar = ''; $escaped = false;
    $len = strlen($html);

    for ($i = $arrayStart; $i < $len; $i++) {
        $c = $html[$i];
        if ($escaped) { $escaped = false; continue; }
        if ($c === '\\') { $escaped = true; continue; }
        if ($inString) { if ($c === $stringChar) $inString = false; continue; }
        if ($c === "'" || $c === '"') { $inString = true; $stringChar = $c; continue; }
        if ($c === '[') $depth++;
        if ($c === ']') { $depth--; if ($depth === 0) return substr($html, $arrayStart, $i - $arrayStart + 1); }
    }
    return null;
}

$jsArray = extractSongsArray($html);
if (!$jsArray) {
    ob_end_clean();
    http_response_code(500);
    echo '<?xml version="1.0" encoding="UTF-8"?><error>SONGS not found</error>';
    exit;
}

function jsToJson($js) {
    $js = str_replace('://', '___PROTO___', $js);
    $js = preg_replace('#//[^\n]*#', '', $js);
    $js = preg_replace('/([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*:/', '$1"$2":', $js);
    $js = str_replace("'", '"', $js);
    $js = preg_replace('/,(\s*[\]}])/', '$1', $js);
    return str_replace('___PROTO___', '://', $js);
}

$songs = json_decode(jsToJson($jsArray), true);
if (!is_array($songs)) {
    ob_end_clean();
    http_response_code(500);
    echo '<?xml version="1.0" encoding="UTF-8"?><error>Parse error</error>';
    exit;
}

$baseUrl = 'https://mazajsh3bi.com';
$today = date('Y-m-d');

$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\n";

// الصفحة الرئيسية
$xml .= "    <url>\n";
$xml .= "        <loc>{$baseUrl}/</loc>\n";
$xml .= "        <lastmod>{$today}</lastmod>\n";
$xml .= "        <changefreq>daily</changefreq>\n";
$xml .= "        <priority>1.0</priority>\n";
$xml .= "        <image:image>\n";
$xml .= "            <image:loc>{$baseUrl}/logo.png</image:loc>\n";
$xml .= "            <image:title>مزاج شعبي - منصة الأغاني المولدة بالذكاء الاصطناعي</image:title>\n";
$xml .= "        </image:image>\n";
$xml .= "    </url>\n\n";

// صفحة الأغاني الصوتية
$xml .= "    <url>\n";
$xml .= "        <loc>{$baseUrl}/audio.html</loc>\n";
$xml .= "        <lastmod>{$today}</lastmod>\n";
$xml .= "        <changefreq>daily</changefreq>\n";
$xml .= "        <priority>0.9</priority>\n";
$xml .= "        <image:image>\n";
$xml .= "            <image:loc>{$baseUrl}/logo.png</image:loc>\n";
$xml .= "            <image:title>الأغاني الصوتية - مزاج شعبي</image:title>\n";
$xml .= "        </image:image>\n";
$xml .= "    </url>\n\n";

// جميع الأغاني
foreach ($songs as $song) {
    $id     = htmlspecialchars($song['id'] ?? '', ENT_XML1);
    $title  = htmlspecialchars($song['songTitle'] ?? '', ENT_XML1);
    $singer = htmlspecialchars($song['singer'] ?? '', ENT_XML1);
    $date   = htmlspecialchars($song['date'] ?? $today, ENT_XML1);
    $image  = $song['singerImage'] ?? '';

    if ($image && strpos($image, 'http') !== 0) {
        $image = $baseUrl . '/' . ltrim($image, '/');
    }
    $image = htmlspecialchars($image, ENT_XML1);

    $xml .= "    <url>\n";
    $xml .= "        <loc>{$baseUrl}/audio.html#song-{$id}</loc>\n";
    $xml .= "        <lastmod>{$date}</lastmod>\n";
    $xml .= "        <changefreq>weekly</changefreq>\n";
    $xml .= "        <priority>0.8</priority>\n";
    if ($image) {
        $xml .= "        <image:image>\n";
        $xml .= "            <image:loc>{$image}</image:loc>\n";
        $xml .= "            <image:title>" . htmlspecialchars("{$singer} - {$title} | مزاج شعبي", ENT_XML1) . "</image:title>\n";
        $xml .= "        </image:image>\n";
    }
    $xml .= "    </url>\n\n";
}

// الصفحات القانونية
$pages = [
    ['url' => '/contact.html', 'priority' => '0.7'],
    ['url' => '/privacy.html', 'priority' => '0.5'],
    ['url' => '/terms.html',   'priority' => '0.5'],
    ['url' => '/dmca.html',    'priority' => '0.5'],
];

foreach ($pages as $p) {
    $xml .= "    <url>\n";
    $xml .= "        <loc>{$baseUrl}{$p['url']}</loc>\n";
    $xml .= "        <lastmod>{$today}</lastmod>\n";
    $xml .= "        <changefreq>monthly</changefreq>\n";
    $xml .= "        <priority>{$p['priority']}</priority>\n";
    $xml .= "    </url>\n\n";
}

$xml .= "</urlset>";   // ⚠️ بدون \n في النهاية

// حفظ الكاش
@file_put_contents($cacheFile, $xml);

// إخراج نظيف
ob_end_clean();
echo $xml;

// ⚠️ لا تضع أي شيء بعد هذا السطر (لا ?> ولا مسافة)