<?php
// preview.xml - Store tabanli RSS feed
require_once __DIR__ . '/config.local.php';
require_once __DIR__ . '/includes/constants.php';
require_once __DIR__ . '/includes/totp.php';
require_once __DIR__ . '/includes/data.php';

date_default_timezone_set('Europe/Istanbul');

$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$source = isset($_GET['source']) ? trim($_GET['source']) : '';
$perPage = 30;
$allowedSources = ['openanime', 'animecix', 'animeprax', 'tranimeizle', 'anizium', 'animim'];

// Phase 25-W3: Birlesik feed public — TOTP gate kaldirildi, tum 6 kaynak merge ile son N episode.
// Cache 5dk Cache-Control header (CDN/proxy yuk korumasi).
header('Cache-Control: public, max-age=300');
if ($source === '' || $source === 'all') {
    $source = '';
} elseif (!in_array($source, $allowedSources)) {
    renderEmptyRss('Gezefcstore', 'Gecersiz kaynak: ' . htmlspecialchars($source));
}

function renderEmptyRss($title, $description) {
    header('Content-Type: application/rss+xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    echo '<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel>';
    echo '<title>' . htmlspecialchars($title, ENT_XML1, 'UTF-8') . '</title>';
    echo '<description>' . htmlspecialchars($description, ENT_XML1, 'UTF-8') . '</description>';
    echo '</channel></rss>';
    exit;
}

$store = getEpisodes();

if (isset($_GET['purge'])) {
    header('Content-Type: text/plain; charset=utf-8');
    if (empty($store)) {
        echo "Store yok veya bos.";
    } else {
        echo "Store purge bu akista desteklenmiyor. Kayit sayisi: " . count($store);
    }
    exit;
}

if (isset($_GET['debug'])) {
    header('Content-Type: text/plain; charset=utf-8');
    echo "=== Preview XML Debug ===\n\n";
    echo "Source: " . ($source !== '' ? $source : 'all') . "\n";
    echo "Page: " . $page . "\n";
    echo "Store Var Mi: " . (file_exists(STORE_FILE) ? 'evet' : 'hayir') . "\n";
    echo "Kayit Sayisi: " . count($store) . "\n";
    if (file_exists(STORE_FILE)) {
        echo "Store Boyut: " . number_format(filesize(STORE_FILE)) . " byte\n";
        echo "Son Guncelleme: " . date('Y-m-d H:i:s', filemtime(STORE_FILE)) . "\n";
    }
    exit;
}

if (empty($store)) {
    renderEmptyRss('Gezefcstore - Veri Bekleniyor', 'Crawler henuz calismadi');
}

$filtered = [];
foreach ($store as $key => $ep) {
    if (!is_array($ep)) continue;
    // Backfilled bolumler RSS'te gosterilmez
    if (!empty($ep['_backfilled'])) continue;

    $epSource = $ep['source'] ?? '';
    if ($source === '' || $epSource === $source) {
        $filtered[$key] = $ep;
    }
}

uasort($filtered, function($a, $b) {
    return ($b['createdAt'] ?? 0) - ($a['createdAt'] ?? 0);
});

$episodes = array_slice(array_values($filtered), ($page - 1) * $perPage, $perPage);

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

// Poster fallback: mal_lookup.json poster cache'i
$malLookupFile = __DIR__ . '/mal_lookup.json';
$malPosters = [];
if (file_exists($malLookupFile)) {
    $malData = json_decode(file_get_contents($malLookupFile), true);
    if (is_array($malData) && isset($malData['posters'])) {
        $malPosters = $malData['posters'];
    }
}

$sourceLabels = [
    'openanime' => ['label' => 'OpenAnime', 'url' => 'https://openani.me'],
    'animecix'  => ['label' => 'AnimeCix',  'url' => 'https://animecix.net'],
    'animeprax' => ['label' => 'AnimePraX', 'url' => 'https://animeprax.com'],
    'tranimeizle' => ['label' => 'TRanimeizle', 'url' => 'https://tranimeizle.io'],
    'anizium' => ['label' => 'Anizium', 'url' => 'https://anizium.co'],
];

$items = '';
foreach ($episodes as $ep) {
    $title = htmlspecialchars($ep['title'] ?? 'Bilinmeyen', ENT_XML1, 'UTF-8');
    $season = $ep['season'] ?? null;
    $episode = $ep['episode'] ?? null;
    $slug = $ep['slug'] ?? '';
    $avatar = $ep['avatar'] ?? '';
    $createdAt = (int) ($ep['createdAt'] ?? 0);

    // Fansub isimlerini topla (baslik + description icin)
    $allFansubNames = [];
    foreach (($ep['sourceData']['fansubs'] ?? []) as $fansub) {
        if (!empty($fansub['name'])) $allFansubNames[$fansub['name']] = true;
    }
    $fansubList = array_keys($allFansubNames);

    // Kompakt baslik: Anime Adi S1 B10
    $itemTitle = $title;
    if ($season) $itemTitle .= ' S' . $season;
    if ($episode) $itemTitle .= ' B' . $episode;

    $sd = $ep['sourceData'] ?? [];
    $link = $sd['sourceUrl'] ?? $sd['url'] ?? '';
    if ($link === '') {
      $link = 'https://openani.me/anime/' . $slug;
      if ($season && $episode) $link .= '/' . $season . '/' . $episode;
    }

    $pubDate = '';
    if ($createdAt) {
        $pubDate = '<pubDate>' . gmdate('D, d M Y H:i:s +0000', $createdAt) . '</pubDate>';
    }

    // Poster: avatar varsa kullan, yoksa mal_lookup fallback
    $posterUrl = $avatar;
    if (!$posterUrl && !empty($ep['malID']) && isset($malPosters[(string)$ep['malID']])) {
        $posterUrl = $malPosters[(string)$ep['malID']];
    }

    // Kaynak bilgisi
    $epSource = $ep['source'] ?? '';
    $srcLabel = isset($sourceLabels[$epSource]) ? $sourceLabels[$epSource]['label'] : $epSource;
    $srcUrl = isset($sourceLabels[$epSource]) ? $sourceLabels[$epSource]['url'] : '';

    // Temiz description: sadece anime adi + sezon/bolum
    $descText = $ep['title'] ?? 'Bilinmeyen';
    if ($season && $episode) $descText .= ' - Sezon ' . $season . ' Bölüm ' . $episode;
    elseif ($episode) $descText .= ' - Bölüm ' . $episode;

    // Kaynak: <source url="...">Label</source> (standart RSS 2.0)
    $sourceElement = '';
    if ($srcLabel) {
        $sourceElement = '      <source>' . htmlspecialchars($srcLabel, ENT_XML1, 'UTF-8') . '</source>
';
    }

    // Fansub: tek <category> elementi
    $categoryElement = '';
    if ($fansubList) {
        $categoryElement = '      <category>' . htmlspecialchars(implode(', ', $fansubList), ENT_XML1, 'UTF-8') . '</category>
';
    }

    // Poster: <media:thumbnail> elementi
    $mediaThumbnail = '';
    if ($posterUrl) {
        $mediaThumbnail = '      <media:thumbnail url="' . htmlspecialchars($posterUrl, ENT_XML1, 'UTF-8') . '" />';
    }

    $guid = ($slug ?: 'unknown') . '&' . ($season ?: 0) . '&' . ($episode ?: 0);

    $items .= '    <item>
      <title>' . htmlspecialchars($itemTitle, ENT_XML1, 'UTF-8') . '</title>
' . $sourceElement . '      <link>' . htmlspecialchars($link, ENT_XML1, 'UTF-8') . '</link>
      <guid isPermaLink="false">' . htmlspecialchars($guid, ENT_XML1, 'UTF-8') . '</guid>
      <description>' . htmlspecialchars($descText, ENT_XML1, 'UTF-8') . '</description>
      ' . $pubDate . '
' . $categoryElement . ($mediaThumbnail ? $mediaThumbnail . '
' : '') . '    </item>
';
}

$channelTitle = 'izleani.me - Son Bölümler';
$channelLink = 'https://izleani.me';
if ($source !== '' && isset($sourceLabels[$source])) {
    $channelTitle .= ' (' . $sourceLabels[$source]['label'] . ')';
    $channelLink = $sourceLabels[$source]['url'];
}

$selfLink = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/preview.xml';
$query = http_build_query(array_filter([
    'source' => $source !== '' ? $source : null,
    'page' => $page > 1 ? $page : null,
]));
if ($query !== '') $selfLink .= '?' . $query;

// Pagination: sonraki sayfa linki
$hasNextPage = count($filtered) > $page * $perPage;
$nextLink = '';
if ($hasNextPage) {
    $nextQuery = http_build_query(array_filter([
        'source' => $source !== '' ? $source : null,
        'page' => $page + 1,
    ]));
    $nextLink = 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/preview.xml?' . $nextQuery;
}

echo '<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
  <channel>
    <title>' . htmlspecialchars($channelTitle, ENT_XML1, 'UTF-8') . '</title>
    <link>' . htmlspecialchars($channelLink, ENT_XML1, 'UTF-8') . '</link>
    <description>izleani.me store tabanlı son bölümler RSS çıktısı</description>
    <language>tr</language>
    <ttl>10</ttl>
    <lastBuildDate>' . gmdate('D, d M Y H:i:s +0000') . '</lastBuildDate>
    <generator>izleani.me/preview.xml</generator>
    <atom:link href="' . htmlspecialchars($selfLink, ENT_XML1, 'UTF-8') . '" rel="self" type="application/rss+xml"/>'
. ($hasNextPage ? '
    <atom:link href="' . htmlspecialchars($nextLink, ENT_XML1, 'UTF-8') . '" rel="next" type="application/rss+xml"/>' : '')
. '
' . $items . '  </channel>
</rss>';
