<?php
/**
 * Dramabox Ultimate Sitemap Generator
 * - Scan semua film (multilang + page)
 * - Cache film & episode
 * - Generate XML sitemap split
 * - Auto lastmod + image:image
 * - Ping Google
 */

set_time_limit(0);

$TOKEN = "51c8ba5e0954141b0e2c0594c2e16be6379f05d2d57630c1713b944bbc6f98ab";
$base = "https://".$_SERVER['HTTP_HOST'];
$cacheDir = __DIR__."/cache/";
$sitemapDir = __DIR__."/public/";
if(!is_dir($cacheDir)) mkdir($cacheDir,0755,true);
if(!is_dir($sitemapDir)) mkdir($sitemapDir,0755,true);

$langs = ['in','en','es','pt','fr','de','tr','ar','ko','ja','zh','th','vi','id','ms'];
$maxPages = 50; // per lang
$limitPerSitemap = 50000; // max URL per XML

$allFilms = [];

// =======================
// GET ALL FILMS
// =======================
foreach($langs as $lang){
    echo "Scanning lang: $lang\n";
    for($page=1;$page<=$maxPages;$page++){
        $url = "https://captain.sapimu.au/dramabox/api/v1/foryou/$page?lang=$lang";
        $ch = curl_init($url);
        curl_setopt_array($ch,[
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ["Authorization: Bearer $TOKEN"],
            CURLOPT_TIMEOUT => 20
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($res,true);
        $list = $data['data']['list'] ?? [];
        if(!$list) break;

        foreach($list as $f){
            $id = $f['bookId'];
            $allFilms[$lang][$id] = $f;

            // cache film JSON
            $filmCacheDir = $cacheDir."film/$lang/";
            if(!is_dir($filmCacheDir)) mkdir($filmCacheDir,0755,true);
            $filmCacheFile = $filmCacheDir."$id.json";
            file_put_contents($filmCacheFile,json_encode($f));

            // cache episodes
            $epDir = $cacheDir."episode/$lang/";
            if(!is_dir($epDir)) mkdir($epDir,0755,true);
            $chapterCount = intval($f['chapterCount'] ?? 0);
            for($i=1;$i<=$chapterCount;$i++){
                $epFile = $epDir."{$id}_{$i}.json";
                if(file_exists($epFile) && time()-filemtime($epFile)<3600) continue;
                $epUrl = "https://captain.sapimu.au/dramabox/api/v1/watch/$id/$i?lang=$lang&direction=1";
                $ch2 = curl_init($epUrl);
                curl_setopt_array($ch2,[
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_HTTPHEADER => ["Authorization: Bearer $TOKEN"],
                    CURLOPT_TIMEOUT => 20
                ]);
                $epRes = curl_exec($ch2);
                curl_close($ch2);
                if($epRes) file_put_contents($epFile,$epRes);
            }
        }

        echo "Lang $lang page $page done\n";
    }
}

// =======================
// GENERATE SITEMAP
// =======================
$episodeSitemapIndex = 1;
$episodeCount = 0;
$episodeXML = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';

$filmXML = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';

foreach($allFilms as $lang=>$list){
    foreach($list as $id=>$f){
        $loc = "$base/$lang/film/$id";
        $lastmod = date("c");
        $image = htmlspecialchars($f['cover'] ?? '');
        $filmXML .= "<url><loc>$loc</loc><lastmod>$lastmod</lastmod>";
        if($image) $filmXML .= "<image:image><image:loc>$image</image:loc></image:image>";
        $filmXML .= "<changefreq>weekly</changefreq><priority>0.8</priority></url>";

        $chapterCount = intval($f['chapterCount'] ?? 0);
        for($i=1;$i<=$chapterCount;$i++){
            $locEp = "$base/$lang/episode/$id/$i";
            $epFile = $cacheDir."episode/$lang/{$id}_{$i}.json";
            $epData = @json_decode(file_get_contents($epFile),true);
            $lastmodEp = date("c", file_exists($epFile)?filemtime($epFile):time());
            $imgEp = htmlspecialchars($f['cover'] ?? '');
            $episodeXML .= "<url><loc>$locEp</loc><lastmod>$lastmodEp</lastmod>";
            if($imgEp) $episodeXML .= "<image:image><image:loc>$imgEp</image:loc></image:image>";
            $episodeXML .= "<changefreq>monthly</changefreq><priority>0.7</priority></url>";
            $episodeCount++;

            if($episodeCount >= $limitPerSitemap){
                $episodeXML .= '</urlset>';
                file_put_contents($sitemapDir."episode_$episodeSitemapIndex.xml",$episodeXML);
                $episodeSitemapIndex++;
                $episodeCount = 0;
                $episodeXML = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
            }
        }
    }
}

// simpan sisa episode
if($episodeCount>0){
    $episodeXML .= '</urlset>';
    file_put_contents($sitemapDir."episode_$episodeSitemapIndex.xml",$episodeXML);
}

// simpan film sitemap
$filmXML .= '</urlset>';
file_put_contents($sitemapDir."films.xml",$filmXML);

// =======================
// GENERATE INDEX
// =======================
$indexXML = '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
$indexXML .= "<sitemap><loc>$base/sitemap/films.xml</loc></sitemap>";
for($i=1;$i<=$episodeSitemapIndex;$i++){
    $indexXML .= "<sitemap><loc>$base/sitemap/episode_$i.xml</loc></sitemap>";
}
$indexXML .= '</sitemapindex>';
file_put_contents($sitemapDir."index.xml",$indexXML);

// =======================
// PING GOOGLE
// =======================
@file_get_contents("https://www.google.com/ping?sitemap=$base/sitemap/index.xml");

echo "✅ Sitemap & cache generated successfully!\n";