<?php
$code = $_GET['code'] ?? '';
if (!$code) exit;

    $cacheDir  = __DIR__ . '/cache/togel';
    $cacheFile = $cacheDir . "/cache_$code.txt";
    
$oldResult = file_exists($cacheFile) ? file_get_contents($cacheFile) : '----';

$url = "https://sengtulus.site/history/result-mobile/" . $code;

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_USERAGENT => 'Mozilla/5.0',
    CURLOPT_TIMEOUT => 5
]);

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

$newResult = $oldResult;

if ($html) {
    if (preg_match('/<td[^>]*>\s*<a[^>]*>(\d{4})<\/a>\s*<\/td>/', $html, $match)) {
        $newResult = $match[1];
    } elseif (preg_match('/<td[^>]*>\s*(\d{4})\s*<\/td>/', $html, $match)) {
        $newResult = $match[1];
    }
}

$updated = false;

if ($newResult !== $oldResult && $newResult !== '----') {
    file_put_contents($cacheFile, $newResult);
    $updated = true;
}

echo json_encode([
    'result' => $newResult,
    'updated' => $updated
]);