<?php
session_start();
require_once __DIR__.'/lang.php';

/* =======================
CONFIG
======================= */
$TOKEN = "5595d9bb6676da7a9969d5ac5de170e350f4c76b61ab8acd23c003c9805d6d9d";
$cache_time = 300; // 5 menit
$foryou_cache_time = 28000; // rekomendasi

$cache_base = __DIR__.'/cache';

if(!is_dir($cache_base)){
    mkdir($cache_base,0755,true);
}

/* =======================
INPUT
======================= */
$lang   = $_GET['lang'] ?? 'en';
$bookId = intval($_GET['id'] ?? 0);
$ep     = max(1,intval($_GET['ep'] ?? 1));

if(!$bookId){
    die(__('invalid_id'));
}

/* =======================
FUNCTION FETCH EPISODE
======================= */
function fetchEpisode($id,$ep,$lang,$TOKEN){
    
    $url="https://captain.sapimu.au/dramabox/api/v2/watch/$id/$ep?lang=$lang";

    $ch=curl_init();

    curl_setopt_array($ch,[
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_HTTPHEADER=>[
            "Authorization: Bearer $TOKEN",
            "Accept: application/json",
            "User-Agent: Mozilla/5.0",
            "Referer: https://dramaboxdb.com/"
        ],
        CURLOPT_TIMEOUT=>20
    ]);

    $res=curl_exec($ch);

    if(curl_errno($ch)){
        error_log("CURL ERROR: ".curl_error($ch));
    }

    curl_close($ch);

    return $res;
}

/* =======================
CACHE FILM DETAIL
======================= */
$film_cache_dir = "$cache_base/film/$lang";
if(!is_dir($film_cache_dir)) mkdir($film_cache_dir,0755,true);

$film_cache_file = "$film_cache_dir/$bookId.json";

if(file_exists($film_cache_file) && (time()-filemtime($film_cache_file)) < $cache_time){
    $response = file_get_contents($film_cache_file);
}else{
    $url = "https://captain.sapimu.au/dramabox/api/v1/detail/$bookId?lang=$lang";

    $ch = curl_init($url);
    curl_setopt_array($ch,[
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $TOKEN",
            "Accept: application/json"
        ],
        CURLOPT_TIMEOUT => 20
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    if($response){
        file_put_contents($film_cache_file,$response);
    }
}

$data = json_decode($response,true);
$book = $data['data'] ?? [];

$bookName     = $book['bookName'] ?? '-';
$cover        = $book['bookCover'] ?? '';
$intro        = $book['introduction'] ?? '';
$chapterCount = intval($book['chapterCount'] ?? 0);
$tags         = $book['tags'] ?? [];

$displayCount = max(0,$chapterCount);

/* =======================
CACHE EPISODE
======================= */
$episode_cache_dir="$cache_base/episode/$lang";
if(!is_dir($episode_cache_dir)) mkdir($episode_cache_dir,0755,true);

$episode_cache_file="$episode_cache_dir/{$bookId}_{$ep}.json";

if(file_exists($episode_cache_file) && (time()-filemtime($episode_cache_file)) < $cache_time){
    $response = file_get_contents($episode_cache_file);
}else{
    $response = fetchEpisode($bookId,$ep,$lang,$TOKEN);

    if($response){
        file_put_contents($episode_cache_file,$response);
    }
}

/* =======================
DECODE
======================= */
$data=json_decode($response,true);
$episode=$data['data'] ?? [];

$epTitle   = $episode['chapterName'] ?? "Episode $ep";
$subtitles = $episode['subtitles'] ?? [];

/* =======================
VIDEO URL LOGIC
======================= */
$videoUrl='';

if(!empty($episode['videoUrl'])){
    $videoUrl=$episode['videoUrl'];
}
elseif(!empty($episode['videos'])){
    usort($episode['videos'],fn($a,$b)=>($b['quality']??0)<=>($a['quality']??0));
    foreach($episode['videos'] as $v){
        if(!empty($v['url'])){
            $videoUrl=$v['url'];
            break;
        }
    }
}
elseif(!empty($episode['qualities'])){
    usort($episode['qualities'],fn($a,$b)=>($b['quality']??0)<=>($a['quality']??0));
    foreach($episode['qualities'] as $q){
        if(!empty($q['videoPath'])){
            $videoUrl=$q['videoPath'];
            break;
        }
    }
}

/* =======================
RETRY VIDEO
======================= */
$tries=0;

while(empty($videoUrl) && $tries<3){
    sleep(1);

    $response=fetchEpisode($bookId,$ep,$lang,$TOKEN);
    $data=json_decode($response,true);
    $episode=$data['data'] ?? [];

    if(!empty($episode['videoUrl'])){
        $videoUrl=$episode['videoUrl'];
        break;
    }

    $tries++;
}

/* =======================
RECOMMENDED
======================= */
$foryou_cache_dir="$cache_base/foryou/$lang";
if(!is_dir($foryou_cache_dir)) mkdir($foryou_cache_dir,0755,true);

$foryou_cache_file="$foryou_cache_dir/page1.json";

if(file_exists($foryou_cache_file) && (time()-filemtime($foryou_cache_file))<$foryou_cache_time){
    $foryouResponse=file_get_contents($foryou_cache_file);
}else{
    $url="https://captain.sapimu.au/dramabox/api/v1/foryou/1?lang=$lang";

    $ch=curl_init($url);
    curl_setopt_array($ch,[
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_HTTPHEADER=>[
            "Authorization: Bearer $TOKEN"
        ],
        CURLOPT_TIMEOUT=>20
    ]);

    $foryouResponse=curl_exec($ch);
    curl_close($ch);

    if($foryouResponse){
        file_put_contents($foryou_cache_file,$foryouResponse);
    }
}

$foryouData=json_decode($foryouResponse,true);
$recomList=array_slice($foryouData['data']['list'] ?? [],0,6);

/* =======================
AUTO PURGE CACHE
======================= */
foreach(glob($cache_base.'/*/*/*.json') as $file){
    if(time()-filemtime($file)>86400){
        unlink($file);
    }
}
?>
<!doctype html>
<html lang="<?= $lang ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($bookName) ?> - <?= htmlspecialchars($epTitle) ?></title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{background:#111;color:#fff}
.flex-player{display:flex;gap:1rem;flex-wrap:wrap;}
.player-left{flex:2}
.episode-right{flex:1;max-width:300px}
.video-container{position:relative;padding-bottom:56.25%}
.video-container video{position:absolute;width:100%;height:100%}
</style>
</head>
<body>

<div class="container mt-3">

<h1><?= htmlspecialchars($bookName) ?> - <?= htmlspecialchars($epTitle) ?></h1>

<div class="flex-player">

<div class="player-left">

<?php if($videoUrl): ?>
<div class="video-container">

<video controls autoplay playsinline>
    <source src="proxy.php?url=<?= urlencode($videoUrl); ?>" type="video/mp4">

    <?php foreach($subtitles as $sub): ?>
        <?php if(!empty($sub['url'])): ?>
        <track 
            label="<?= htmlspecialchars($sub['captionLanguage']) ?>" 
            kind="subtitles" 
            srclang="<?= strtolower($sub['captionLanguage']) ?>" 
            src="<?= htmlspecialchars($sub['url']) ?>"
            <?= !empty($sub['isDefault']) ? 'default' : '' ?>
        >
        <?php endif; ?>
    <?php endforeach; ?>
</video>

</div>
<?php else: ?>
<p>Video tidak ditemukan</p>
<?php endif; ?>

</div>

<div class="episode-right">
<?php for($i=1;$i<=$displayCount;$i++): ?>
<a href="?id=<?= $bookId ?>&ep=<?= $i ?>&lang=<?= $lang ?>">
Episode <?= $i ?>
</a><br>
<?php endfor; ?>
</div>

</div>

<h3 class="mt-4">Recommended</h3>

<div class="row">
<?php foreach($recomList as $r): ?>
<div class="col-6 col-md-2">
<a href="?id=<?= $r['bookId'] ?>&ep=1&lang=<?= $lang ?>">
<img src="proxy.php?url=<?= urlencode($r['cover']) ?>" class="img-fluid">
<p><?= htmlspecialchars($r['bookName']) ?></p>
</a>
</div>
<?php endforeach; ?>
</div>

</div>

<script>
// AUTO NEXT
const video = document.querySelector("video");

if(video){
video.addEventListener("ended", function(){
    let next = <?= $ep + 1 ?>;
    let max  = <?= $chapterCount ?>;

    if(next <= max){
        window.location.href = "?id=<?= $bookId ?>&ep=" + next + "&lang=<?= $lang ?>";
    }
});
}
</script>

</body>
</html>