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

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

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

/* =======================
CONFIG
======================= */
$TOKEN = "60443305ff23918eefd00a04e27c5cc8dc7f6e84e21c5ccd4370dcbc0421409f";
$cache_time = 3600;
$cache_base = __DIR__.'/cache';

/* =======================
HELPER CURL + CACHE
======================= */
function fetchWithCache($url, $cache_file, $TOKEN, $cache_time){
    if(file_exists($cache_file) && (time()-filemtime($cache_file)) < $cache_time){
        return file_get_contents($cache_file);
    }

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

    $res = curl_exec($ch);
    if (curl_errno($ch)) die("cURL Error: " . curl_error($ch));
    curl_close($ch);

    if($res) file_put_contents($cache_file, $res);
    return $res;
}

/* =======================
WATCH DATA
======================= */
$cache_dir = "$cache_base/watch/$lang";
if(!is_dir($cache_dir)) mkdir($cache_dir,0755,true);

$cache_file = "$cache_dir/{$bookId}.json";
$watchUrl = "https://captain.sapimu.au/dramaboxtempek/api/drama/$bookId/episodes?lang=$lang";

$response = fetchWithCache($watchUrl, $cache_file, $TOKEN, $cache_time);
$data = json_decode($response, true);
/* =======================
BOOK INFO
======================= */
$book = $data['data'] ?? [];

$bookName     = $book['bookName'] ?? __('film');
$cover        = $book['cover'] ?? '';
$intro        = $book['description'] ?? '';
$tags         = $book['tags'] ?? [];
$chapterCount = intval($book['totalEpisodes'] ?? 0);
$displayCount = max(0, $chapterCount - 1);

/* =======================
EPISODE
======================= */
$episodevid = $data['episodes'] ?? [];
$currentEpisode = null;

foreach ($episodevid as $item) {
    if (($item['episode'] ?? 0) == $ep) {
        $currentEpisode = $item;
        break;
    }
}

if (!$currentEpisode) {
    foreach ($episodevid as $item) {
        if (($item['episode'] ?? 0) == 1) {
            $currentEpisode = $item;
            $ep = 1;
            break;
        }
    }
}

if (!$currentEpisode && !empty($episodevid)) {
    $currentEpisode = $episodevid[0];
    $ep = $currentEpisode['episode'] ?? 1;
}

/* =======================
AMBIL VIDEO URL (FIX)
======================= */
$videoUrl = $currentEpisode['url'] ?? '';
$eps = $currentEpisode['episode'] ?? '';
$epTitle = $currentEpisode['chapterName'] ?? __('episode') . " $eps";

/* =======================
RETRY JIKA VIDEO KOSONG
======================= */
if (empty($videoUrl)) {
    @unlink($cache_file);

    $response = fetchWithCache($watchUrl, $cache_file, $TOKEN, 0);
    $data = json_decode($response, true);

    $episodevid = $data['data']['episodes'] ?? [];

    foreach ($episodevid as $item) {
        if (($item['episode'] ?? 0) == $ep) {

            // ✅ langsung pakai 'url'
            $videoUrl = $item['url'] ?? '';

            break;
        }
    }
}


/* =======================
AUTO PURGE CACHE
======================= */
foreach(glob($cache_base.'/*/*/*.json') as $file){
    if(time()-filemtime($file) > 86400){
        unlink($file);
    }
}
/* =======================
SEO MULTI-LANG
======================= */
$seo_data = [
    'en'=>['title'=>"$bookName – $epTitle | Watch Drama Online",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, drama online, watch episode, full episode"],
    'in'=>['title'=>"$bookName – $epTitle | Nonton Drama Online",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, drama online, nonton episode, semua episode"],
    'es'=>['title'=>"$bookName – $epTitle | Ver Drama Online",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, drama online, ver episodio, episodios completos"],
    'fr'=>['title'=>"$bookName – $epTitle | Regarder Drama en Ligne",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, drama en ligne, regarder épisode, épisodes complets"],
    'pt'=>['title'=>"$bookName – $epTitle | Assistir Drama Online",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, drama online, assistir episódio, episódios completos"],
    'de'=>['title'=>"$bookName – $epTitle | Drama Online Sehen",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, drama online, episode ansehen, ganze episoden"],
    'ar'=>['title'=>"$bookName – $epTitle | مشاهدة الدراما",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, دراما على الإنترنت, مشاهدة حلقة"],
    'ko'=>['title'=>"$bookName – $epTitle | 최신 드라마 보기",'description'=>substr(strip_tags($intro),0,160),'keywords'=>"$bookName, 온라인 드라마, 전체 에피소드"]
];
$seo_title = $seo_data[$lang]['title'] ?? $seo_data['en']['title'];
$seo_desc  = $seo_data[$lang]['description'] ?? $seo_data['en']['description'];
$seo_keys  = $seo_data[$lang]['keywords'] ?? $seo_data['en']['keywords'];

/* =======================
HREFLANG
======================= */
$languages = array_keys($seo_data);
$current_url_path = $_SERVER['REQUEST_URI'];
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $lang==='ar'?'rtl':'ltr' ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= htmlspecialchars($seo_title) ?></title>
<meta name="description" content="<?= htmlspecialchars($seo_desc) ?>">
<meta name="keywords" content="<?= htmlspecialchars($seo_keys) ?>">
<meta name="robots" content="index, follow">
<link rel="canonical" href="<?= "https://".$_SERVER['HTTP_HOST'].$current_url_path ?>">

<?php
// Hreflang
foreach($languages as $l){
    $hreflang_url = preg_replace('#^/([a-z-]+)/#', "/$l/", $current_url_path);
    echo '<link rel="alternate" hreflang="'.$l.'" href="https://'.$_SERVER['HTTP_HOST'].$hreflang_url.'" />'.PHP_EOL;
}
echo '<link rel="alternate" hreflang="x-default" href="https://'.$_SERVER['HTTP_HOST'].'/en/" />'.PHP_EOL;
?>

<!-- Open Graph -->
<meta property="og:title" content="<?= htmlspecialchars($seo_title) ?>" />
<meta property="og:description" content="<?= htmlspecialchars($seo_desc) ?>" />
<meta property="og:type" content="video.episode" />
<meta property="og:image" content="<?= $cover ?>" />
<meta property="og:url" content="<?= "https://".$_SERVER['HTTP_HOST'].$current_url_path ?>" />
<meta property="og:site_name" content="<?= $_SERVER['HTTP_HOST'] ?>" />

<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="<?= htmlspecialchars($seo_title) ?>" />
<meta name="twitter:description" content="<?= htmlspecialchars($seo_desc) ?>" />
<meta name="twitter:image" content="<?= $cover ?>" />

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{background:#111;color:#fff;font-family:Segoe UI,Tahoma,sans-serif;line-height:1.6;}
a{text-decoration:none;color:inherit;transition:.2s;}
a:hover{color:#dc3545;}
[dir="rtl"]{direction:rtl;text-align:right;}
.flex-player{display:flex;gap:1rem;flex-wrap:wrap;}
.player-left{flex:2;min-width:300px;}
.episode-right{flex:1;min-width:250px;max-width:300px;background:#111;border-radius:10px;padding:10px;max-height:450px;overflow-y:auto;}
.episode-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(50px,1fr));gap:5px;}
.episode-btn{background:#222;border:1px solid #555;color:#fff;padding:.35rem 0;border-radius:4px;font-size:.85rem;}
.episode-btn.active{background:#dc3545;border-color:#dc3545;}
.video-container{position:relative;padding-bottom:56.25%;background:#111;border-radius:10px;}
.video-container video{position:absolute;width:100%;height:100%;border-radius:10px;}
.info-film{text-align:center;}
.info-film img{max-width:300px;border-radius:10px;}
.recom-card{background:#111;border-radius:8px;text-align:center;border:1px solid #222;}
.recom-card:hover{transform:scale(1.05);}
@media(max-width:767px){.flex-player{flex-direction:column;}.episode-right{max-width:100%;}}
</style>
</head>
<body class="bg-dark text-light">
<?php include 'navbar.php'; ?>
<?php include 'ads.php'; ?>
<!-- SEARCH BODY -->
<center>
    <style>
        .search-wrapper {
    display: flex;
    justify-content: center;
    margin: 20px 0;
}

.search-box {
    display: flex;
    align-items: center;
    background: #111;
    border-radius: 30px;
    padding: 5px 10px;
    max-width: 350px;
    width: 100%;
    border: 1px solid #333;
    transition: 0.3s;
}

.search-box:focus-within {
    border-color: #e50914;
    box-shadow: 0 0 8px rgba(229,9,20,0.5);
}

.search-box input {
    flex: 1;
    border: none;
    background: transparent;
    color: #fff;
    font-size: 14px;
    padding: 8px;
    outline: none;
}

.search-box input::placeholder {
    color: #aaa;
}

.search-box button {
    border: none;
    background: #e50914;
    color: #fff;
    border-radius: 50%;
    width: 34px;
    height: 34px;
    cursor: pointer;
    transition: 0.3s;
}

.search-box button:hover {
    transform: scale(1.1);
    background: #ff1e1e;
}
    </style>
    <div class="search-wrapper">
        <form class="search-box"
              action="<?= '/' . htmlspecialchars($lang) . '/search' ?>"
              method="get">
    
            <input type="hidden" name="lang" value="<?= htmlspecialchars($lang) ?>">
    
            <input type="search"
                   name="q"
                   placeholder="<?= __('nav_search') ?>"
                   value="<?= htmlspecialchars($_GET['q'] ?? '') ?>"
                   autocomplete="off"
                   required>
    
            <button type="submit">🔍</button>
        </form>
    </div>
</center>

<div class="container mt-3">
<h1 class="fw-bold"><?= htmlspecialchars($bookName) ?> – <?= __('episode');?> <?= htmlspecialchars($eps) ?></h1>

<div class="flex-player">
    <div class="player-left mb-3">
        <?php if($videoUrl): ?>
        <div class="video-container mb-2">
            <video 
    src="proxy.php?url=<?= urlencode($videoUrl); ?>" 
    controls 
    playsinline 
    webkit-playsinline
    preload="metadata"
>
            <?php foreach($episode['subtitles'] ?? [] as $sub): ?>
                <?php if(!empty($sub['url'])): ?>
                    <track label="<?= $sub['captionLanguage'] ?>" kind="subtitles" srclang="<?= $sub['captionLanguage'] ?>" src="<?= $sub['url'] ?>" <?= $sub['isDefault']?'default':'' ?>>
                <?php endif; ?>
            <?php endforeach; ?>
            </video>
        </div>
        <?php else: ?>
        <p class="text-center text-secondary"><?= __('video_unavailable') ?></p>
        <?php endif; ?>
    </div>

    <?php if($displayCount > 0): ?>
    <div class="episode-right mb-3 mt-5">
        <h5><?= __('episodes') ?></h5>
        <div class="episode-grid">
        <?php for($i=1;$i<=$displayCount;$i++): ?>
            <a href="/<?= $lang ?>/episode/<?= $bookId ?>/<?= $i ?>" class="episode-btn <?= $i===$ep?'active':'' ?>">
                <center><?= $i ?></center>
            </a>
        <?php endfor; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<div class="info-film mt-3">
    <img src="proxy.php?url=<?= urlencode($cover) ?>" class="img-fluid shadow mb-2">
    <h3><?= htmlspecialchars($bookName) ?></h3>
    <p class="text-secondary"><?= $chapterCount ?> <?= __('episode') ?></p>
    <p><?= nl2br(htmlspecialchars($intro)) ?></p>
    <?php foreach($tags as $t): ?>
        <span class="badge bg-secondary"><?= htmlspecialchars($t) ?></span>
    <?php endforeach; ?>
</div>

<?php if($recomList): ?>
<h5 class="mt-4"><?= __('recommended') ?></h5>
<div class="row g-3">
<?php foreach($recomList as $r): ?>
<div class="col-6 col-md-4 col-lg-2">
    <a href="/<?= $lang ?>/episode/<?= $r['bookId'] ?>/1" class="card bg-black text-white h-100 text-decoration-none">
        <img src="proxy.php?url=<?= urlencode($r['bookCover']) ?>" class="card-img-top">
        <div class="card-body p-2 small"><?= htmlspecialchars($r['bookName']) ?></div>
    </a>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>

<?php include 'footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- JSON-LD Structured Data -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "TVEpisode",
  "name": "<?= addslashes($epTitle) ?>",
  "episodeNumber": <?= $ep ?>,
  "partOfSeries": {
    "@type": "TVSeries",
    "name": "<?= addslashes($bookName) ?>",
    "image": "<?= $cover ?>"
  },
  "description": "<?= addslashes($intro) ?>",
  "url": "<?= "https://".$_SERVER['HTTP_HOST'].$current_url_path ?>",
  "thumbnailUrl": "<?= $cover ?>"
}
</script>
</body>
</html>