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

/* =======================
CONFIG
======================= */

$token    = "60443305ff23918eefd00a04e27c5cc8dc7f6e84e21c5ccd4370dcbc0421409f";
$pageSize = 20;

/* =======================
CACHE CONFIG
======================= */

$cache_time = 172800; // 8 jam
$cache_base = __DIR__.'/cache/search';

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

/* =======================
LANG
======================= */

$supported_langs = ['in','en','ja','zhHans','zh','es','de','fr','pt','ar','th','tl','ko','tr'];
$default_lang = 'in';

$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? $default_lang);
$lang = in_array($lang, $supported_langs) ? $lang : $default_lang;

$_SESSION['lang'] = $lang;

/* =======================
CACHE LANG FOLDER
======================= */

$lang_cache = "$cache_base/$lang";

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

/* =======================
INPUT
======================= */

$q    = trim($_GET['q'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));

$is_empty = ($q === '');
$is_ajax  = isset($_GET['ajax']);

/* =======================
DATA DEFAULT
======================= */

$items = [];
$error = '';

/* =======================
API REQUEST + CACHE
======================= */

if (!$is_empty) {

    // ✅ FIX encoding (spasi jadi %20)
    $keyword = rawurlencode($q);
    
    $url = "https://captain.sapimu.au/dramaboxv2/api/search/suggest?keyword=$keyword&lang=in";

    /* CACHE KEY */
    $cache_key  = preg_replace('/[^a-z0-9]/i','_', strtolower($q));
    $cache_file = "$lang_cache/{$cache_key}_{$page}.json";

    if(file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_time){

        $response = file_get_contents($cache_file);

    } else {

        $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);

        // ❌ HANDLE CURL ERROR
        if($response === false){
            $error = "CURL ERROR: " . curl_error($ch);
        }

        curl_close($ch);

        // ✅ simpan cache kalau ada response valid
        if($response && !$error){
            file_put_contents($cache_file,$response);
        }
    }

    // ✅ decode JSON
    if(!$error){
        $data = json_decode($response, true);

        if(!$data){
            $error = "JSON ERROR / INVALID RESPONSE";
        } else {
            $items = $data['data']['data']['suggestList'] ?? [];
        }
    }
}

/* =======================
AUTO PURGE CACHE (24 JAM)
======================= */

foreach(glob(__DIR__.'/cache/search/*/*.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><?= __('search') ?> - <?= htmlspecialchars($q) ?></title>

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

</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">

<h5 class="mb-3">

<?php if($is_empty): ?>

    <?= __('search_prompt') ?>

<?php else: ?>

    <?= __('search_results_for') ?>
    <strong><?= htmlspecialchars($q) ?></strong>

<?php endif; ?>

</h5>


<!-- EMPTY -->

<?php if($is_empty): ?>

<div class="text-center text-secondary py-5">

<div style="font-size:48px">🔍</div>

<p><?= __('enter_keyword') ?></p>

</div>


<!-- NOT FOUND -->

<?php elseif(!$items): ?>

<div class="text-center text-secondary py-5">

<div style="font-size:48px">😕</div>

<p>

<?= __('no_results_for') ?>
<strong><?= htmlspecialchars($q) ?></strong>

</p>

</div>


<!-- RESULT -->

<?php else: ?>

<div class="row g-3" id="resultGrid">

<?php

$limit = 10;
$count = 0;

foreach($items as $row):

if ($count++ >= $limit) break;

?>

<div class="col-6 col-md-4 col-lg-2">

<a class="card bg-black text-white h-100 text-decoration-none border-0 shadow-sm"
   href="/<?= $lang ?>/episode/<?= $row['bookId'] ?>">

<img src="proxy.php?url=<?= urlencode($row['cover']) ?>"
     class="card-img-top"
     loading="lazy">

<div class="card-body p-2">

<div class="card-title small mb-1">

<?= htmlspecialchars($row['bookName']) ?>

</div>

<small class="text-secondary">

<!-- <?= __('views') ?> • <?= htmlspecialchars($row['playCount']) ?> -->

</small>

</div>

</a>

</div>

<?php endforeach; ?>

</div>


<div id="loader"
     class="text-center text-secondary py-4"
     style="display:none">

⏳ <?= __('loading') ?>...

</div>

<?php endif; ?>

</div>


<!-- INFINITE SCROLL -->

<script>

let page = <?= $page ?>;

let loading = false;

let done = false;

async function loadMore(){

if(loading || done) return;

loading = true;

document.getElementById('loader').style.display = 'block';

page++;

const res = await fetch(
`search.php?ajax=1&q=<?= urlencode($q) ?>&lang=<?= $lang ?>&page=${page}`
);

const html = await res.text();

document.getElementById('loader').style.display = 'none';

if(html.trim() === ''){

done = true;

return;

}

document.getElementById('resultGrid')
.insertAdjacentHTML('beforeend', html);

loading = false;

}

window.addEventListener('scroll', () => {

if(window.innerHeight + window.scrollY >= document.body.offsetHeight - 300){

loadMore();

}

});

</script>

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

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

</body>
</html>