<?php
require_once 'lang.php';

/* =======================
CONFIG
======================= */
$page  = max(1,(int)($_GET['page'] ?? 1));
$size  = 12;
$token = "60443305ff23918eefd00a04e27c5cc8dc7f6e84e21c5ccd4370dcbc0421409f";

/* =======================
CACHE CONFIG
======================= */
$cache_time = 172800; // 8 jam
$cache_base = __DIR__.'/cache';

/* buat folder cache jika belum ada */
if(!is_dir($cache_base)){
    mkdir($cache_base,0755,true);
}

/* buat folder bahasa */
$lang_cache = $cache_base.'/'.$lang;
if(!is_dir($lang_cache)){
    mkdir($lang_cache,0755,true);
}

/* nama file cache */
$cache_file = $lang_cache."/home_{$page}.json";

/* nama file cache */
$cache_file = $lang_cache."/home_{$page}.json";

/* =======================
LOAD CACHE / API (V2)
======================= */
if(file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_time){

    $response = file_get_contents($cache_file);

}else{
    $url = "https://captain.sapimu.au/dramaboxv4/api/home?page=$page&size=$size&lang=$lang";

    $ch = curl_init();

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

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        die("cURL Error: " . curl_error($ch));
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if($httpCode !== 200){
        die("API Error: HTTP $httpCode");
    }

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

/* =======================
DECODE JSON
======================= */
$data = json_decode($response,true);
$items = $data['data']['data']['classifyBookList']['records'] ?? [];

$total = $data['data']['data']['classifyBookList']['total'] ?? 0;
$total_pages = $total > 0 ? ceil($total / $size) : 50;
/* =======================
SEO
======================= */
$seo_data = [
    'en' => [
        'title' => 'Watch Latest Dramas Online | Full Episodes',
        'description' => 'Watch the latest drama series online with full episodes. Enjoy Korean, Japanese, Chinese, and other dramas in HD quality.',
        'keywords' => 'drama online, watch drama, korean drama, japanese drama, full episodes, chinese drama'
    ],
    'in' => [
        'title' => 'Nonton Drama Terbaru Online | Semua Episode',
        'description' => 'Nonton drama terbaru online dengan semua episode. Nikmati drama Korea, Jepang, China, dan lainnya dalam kualitas HD.',
        'keywords' => 'drama online, nonton drama, drama korea, drama jepang, drama china, semua episode'
    ],
    'es' => [
        'title' => 'Ver las Últimas Series Online | Episodios Completos',
        'description' => 'Mira las últimas series dramáticas en línea con episodios completos. Disfruta dramas coreanos, japoneses, chinos y más en HD.',
        'keywords' => 'drama online, ver drama, drama coreano, drama japonés, drama chino, episodios completos'
    ],
    'fr' => [
        'title' => 'Regarder les Dernières Séries en Ligne | Épisodes Complets',
        'description' => 'Regardez les dernières séries dramatiques en ligne avec tous les épisodes. Profitez des dramas coréens, japonais, chinois et autres en HD.',
        'keywords' => 'drama en ligne, regarder drama, drama coréen, drama japonais, drama chinois, épisodes complets'
    ],
    'pt' => [
        'title' => 'Assistir Últimos Dramas Online | Episódios Completos',
        'description' => 'Assista às últimas séries dramáticas online com episódios completos. Aproveite dramas coreanos, japoneses, chineses e outros em HD.',
        'keywords' => 'drama online, assistir drama, drama coreano, drama japonês, drama chinês, episódios completos'
    ],
    'de' => [
        'title' => 'Neueste Dramen Online Sehen | Ganze Episoden',
        'description' => 'Sehen Sie die neuesten Dramaserien online mit allen Episoden. Genießen Sie koreanische, japanische, chinesische und andere Dramen in HD.',
        'keywords' => 'drama online, drama ansehen, koreanisches drama, japanisches drama, chinesisches drama, ganze episoden'
    ],
    'ar' => [
        'title' => 'مشاهدة أحدث الدراما عبر الإنترنت | جميع الحلقات',
        'description' => 'شاهد أحدث المسلسلات الدرامية عبر الإنترنت مع جميع الحلقات. استمتع بالدراما الكورية واليابانية والصينية وغيرها بجودة HD.',
        'keywords' => 'دراما على الإنترنت, مشاهدة دراما, دراما كورية, دراما يابانية, دراما صينية, جميع الحلقات'
    ],
    'th' => [
        'title' => 'ดูละครล่าสุดออนไลน์ | ทุกตอน',
        'description' => 'ดูละครล่าสุดออนไลน์พร้อมทุกตอน เพลิดเพลินกับละครเกาหลี ญี่ปุ่น จีน และอื่น ๆ ในคุณภาพ HD',
        'keywords' => 'ละครออนไลน์, ดูละคร, ละครเกาหลี, ละครญี่ปุ่น, ละครจีน, ทุกตอน'
    ],
    'ko' => [
        'title' => '최신 드라마 온라인 시청 | 전체 에피소드',
        'description' => '최신 드라마 시리즈를 온라인으로 전체 에피소드와 함께 시청하세요. 한국, 일본, 중국 드라마를 HD로 즐기세요.',
        'keywords' => '온라인 드라마, 드라마 보기, 한국 드라마, 일본 드라마, 중국 드라마, 전체 에피소드'
    ],
    'zh-Hans' => [
        'title' => '在线观看最新电视剧 | 完整剧集',
        'description' => '在线观看最新电视剧的完整剧集。欣赏韩剧、日剧、中国剧等高清内容。',
        'keywords' => '在线视频, 电视剧, 韩剧, 日剧, 中剧, 完整剧集'
    ],
    'zh-Hant' => [
        'title' => '線上觀看最新電視劇 | 完整劇集',
        'description' => '線上觀看最新電視劇的完整劇集。欣賞韓劇、日劇、中國劇等高清內容。',
        'keywords' => '線上電視劇, 觀看劇集, 韓劇, 日劇, 中國劇, 完整劇集'
    ],
    'tr' => [
        'title' => 'En Son Dizileri Online İzle | Tüm Bölümler',
        'description' => 'En son drama dizilerini online olarak tüm bölümleriyle izleyin. Kore, Japon, Çin ve diğer dizileri HD kalitesinde keyfini çıkarın.',
        'keywords' => 'drama online, dizi izle, kore dizisi, japon dizisi, çin dizisi, tüm bölümler'
    ],
    'fil' => [
        'title' => 'Panoorin ang Pinakabagong Drama Online | Buong Episodes',
        'description' => 'Panoorin ang pinakabagong drama online na may buong episodes. Tangkilikin ang Korean, Japanese, Chinese at iba pang drama sa HD.',
        'keywords' => 'drama online, panoorin drama, korean drama, japanese drama, chinese drama, buong episodes'
    ],
    'ja' => [
        'title' => '最新ドラマをオンラインで視聴 | 全話',
        'description' => '最新のドラマシリーズをオンラインで全話視聴できます。韓国、日本、中国のドラマをHDで楽しもう。',
        'keywords' => 'ドラマオンライン, ドラマ視聴, 韓国ドラマ, 日本ドラマ, 中国ドラマ, 全話'
    ]
];

// Ambil SEO per bahasa
$lang = $_GET['lang'] ?? 'en';
$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'];

/* =======================
HELPERS
======================= */
function slugify($text){
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/','-',$text);
    $text = trim($text,'-');
    return $text;
}

function current_url(){
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' 
                 || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    return $protocol . $_SERVER['HTTP_HOST'] . $_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="<?= current_url() ?>">

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

<style>
body {
    background: #111;           /* gelap nyaman untuk mata */
    color: #f0f0f0;            /* teks terang & jelas */
    font-family: system-ui, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
}

a {
    text-decoration: none;      /* hilangkan garis bawah */
    color: #1e90ff;             /* link terlihat jelas */
    transition: color 0.2s;
}

a:hover, a:focus {
    color: #63b3ed;             /* hover lebih lembut */
}

.drama-card {
    background: #1c1c1c;        /* card lebih terang dari background */
    border-radius: 10px;
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
    height: 100%;
}

.drama-card:hover {
    transform: scale(1.03);
    box-shadow: 0 4px 12px rgba(0,0,0,0.5);
}

.drama-card img {
    width: 100%;
    aspect-ratio: 2/3;
    object-fit: cover;
    display: block;
}

.title {
    font-size: 0.85rem;
    line-height: 1.2;
    height: 36px;
    overflow: hidden;
}

.episode {
    font-size: 0.75rem;
    color: #aaa;
}

[dir="rtl"] {
    direction: rtl;
    text-align: right;
}

/* Tambahan responsif hover pada touch device */
@media (hover: none) {
    .drama-card:hover {
        transform: none;
        box-shadow: none;
    }
}
</style>
</head>

<body class="bg-dark text-light">

<?php include 'navbar.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>


<!-- ADS -->
<?php include 'ads.php'; ?>

<div class="container mt-3">

<h1 class="visually-hidden"><?= htmlspecialchars($seo_title) ?></h1>

<!-- GRID -->
<div class="row g-3">

<?php if($items): foreach($items as $i => $row): ?>
<div class="col-6 col-sm-4 col-md-3 col-lg-2">
<article class="drama-card text-decoration-none text-white d-block" itemscope itemtype="https://schema.org/TVSeries">
<a href="/<?= $lang ?>/episode/<?= $row['bookId'] ?>">
<img src="proxy.php?url=<?= urlencode($row['coverWap']) ?>" 
     loading="lazy" 
     alt="<?= htmlspecialchars($row['bookName']) ?>" 
     itemprop="image"><div class="p-2">
<h2 class="title" itemprop="name"><?= htmlspecialchars($row['bookName']) ?></h2>
<p class="episode" itemprop="numberOfEpisodes"><?= (int)$row['chapterCount'] ?> <?= __('episode') ?></p>
<?php if(!empty($row['genres'])): ?>
<div class="genre mb-1 text-secondary" itemprop="genre"><?= implode(", ", $row['genres']) ?></div>
<?php endif; ?>
</div>
</a>
</article>
</div>
<?php endforeach; else: ?>
<p class="text-center text-secondary mt-5"><?= __('no_data') ?></p>
<?php endif; ?>

</div>

<!-- PAGINATION -->
<?php if($total_pages > 1): ?>
<nav class="mt-4">
<ul class="pagination pagination-sm justify-content-center">
<?php if($page > 1): ?>
<li class="page-item"><a class="page-link bg-dark text-light border-secondary" href="<?= url_with_lang('', ['page'=>$page-1]) ?>">« <?= __('prev') ?></a></li>
<?php endif; ?>

<?php
$start = max(1,$page-3);
$end   = min($total_pages,$page+3);
for($i=$start;$i<=$end;$i++):
?>
<li class="page-item <?= $i==$page?'active':'' ?>">
<a class="page-link bg-dark text-light border-secondary" href="<?= url_with_lang('', ['page'=>$i]) ?>"><?= $i ?></a>
</li>
<?php endfor; ?>

<?php if($page < $total_pages): ?>
<li class="page-item"><a class="page-link bg-dark text-light border-secondary" href="<?= url_with_lang('', ['page'=>$page+1]) ?>"><?= __('next') ?> »</a></li>
<?php endif; ?>
</ul>
</nav>

<!-- SEO rel prev/next -->
<?php if($page>1): ?><link rel="prev" href="<?= url_with_lang('', ['page'=>$page-1]) ?>"><?php endif; ?>
<?php if($page<$total_pages): ?><link rel="next" href="<?= url_with_lang('', ['page'=>$page+1]) ?>"><?php endif; ?>

<?php endif; ?>

</div>

<?php include 'footer.php'; ?>

<!-- JSON-LD Structured Data -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "ItemList",
  "itemListElement": [
    <?php foreach($items as $i => $row): ?>
    {
      "@type": "TVSeries",
      "position": <?= $i+1 ?>,
      "name": "<?= addslashes($row['bookName']) ?>",
      "url": "<?= "https://".$_SERVER['HTTP_HOST']."/$lang/episode/".slugify($row['bookName'])."-".$row['bookId'] ?>",
      "image": "<?= $row['coverWap'] ?>",
      "numberOfEpisodes": <?= (int)$row['chapterCount'] ?>
    }<?= $i < count($items)-1 ? "," : "" ?>
    <?php endforeach; ?>
  ]
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>