<?php
$url = 'https://tv.nunadrama.store/';
$cacheFile = __DIR__ . '/data.json';
$logFile = __DIR__ . '/scraper.log';
$cacheTime = 3600; // Cache selama 1 jam

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime && !isset($_GET['force'])) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);

if (!$response) {
    file_put_contents($logFile, "[".date("Y-m-d H:i:s")."] Gagal: $err\n", FILE_APPEND);
    http_response_code(500);
    echo json_encode(['error' => 'Gagal mengambil data dari sumber']);
    exit;
}

libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($response);
libxml_clear_errors();

$xpath = new DOMXPath($dom);
$items = $xpath->query("//div[contains(@class, 'film_list-wrap')]/div");

$data = [];
foreach ($items as $item) {
    $titleNode = $xpath->query(".//h3/a", $item)[0] ?? null;
    $imgNode = $xpath->query(".//img", $item)[0] ?? null;

    if ($titleNode && $imgNode) {
        $data[] = [
            'title' => trim($titleNode->nodeValue),
            'link' => $titleNode->getAttribute('href'),
            'image' => $imgNode->getAttribute('data-src'),
        ];
    }
}

if (!empty($data)) {
    file_put_contents($cacheFile, json_encode($data, JSON_PRETTY_PRINT));
    file_put_contents($logFile, "[".date("Y-m-d H:i:s")."] Update sukses: ".count($data)." data\n", FILE_APPEND);
    file_put_contents(__DIR__ . '/last_update.json', json_encode([
        'time' => date('Y-m-d H:i:s')
    ]));
}

header('Content-Type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);