<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

function fetch_html(string $url, array $headers = []): string
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Scraper/1.0)',
        CURLOPT_HTTPHEADER => $headers,
    ]);

    $html = curl_exec($ch);
    if ($html === false) {
        throw new Exception("cURL error: " . curl_error($ch));
    }

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

    if ($code >= 400) {
        throw new Exception("HTTP error: $code");
    }
    return $html;
}

function parse_lottery_rows(string $html): array
{
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML('<meta charset="utf-8">' . $html);
    libxml_clear_errors();

    $xp = new DOMXPath($dom);

    $rows = $xp->query("//tr[contains(concat(' ', normalize-space(@class), ' '), ' lottery-list ')]");

    $out = [];

    foreach ($rows as $row) {
        $td1 = $xp->query("./td[1]", $row)->item(0);
        $td2 = $xp->query("./td[2]", $row)->item(0);
        $td3 = $xp->query("./td[3]", $row)->item(0);
        $td4 = $xp->query("./td[4]", $row)->item(0);

        if (!$td1 || !$td2 || !$td3 || !$td4) continue;

        $spanNode = $xp->query(".//span", $td1)->item(0);
        $pasaran = trim($spanNode ? $spanNode->textContent : $td1->textContent);

        $lines = array_values(array_filter(array_map('trim', preg_split("/\r\n|\n|\r/", $td2->textContent))));
        $hari = $lines[0] ?? '';
        $tanggal = $lines[1] ?? '';

        $jam_raw = trim(preg_replace('/\s+/', ' ', $td3->textContent));
        preg_match('/Tutup:\s*([0-9:]+).*Buka:\s*([0-9:]+)/i', $jam_raw, $m);
        $tutup = $m[1] ?? '';
        $buka  = $m[2] ?? '';

        $digits = [];
        foreach ($xp->query(".//table//div", $td4) as $d) {
            $val = trim($d->textContent);
            if ($val !== '') $digits[] = $val;
        }
        $hasil = implode('', $digits);

        $out[] = [
            'pasaran' => $pasaran,
            'hari'    => $hari,
            'tanggal' => $tanggal,
            'tutup'   => $tutup,
            'buka'    => $buka,
            'hasil'   => $hasil,
        ];
    }

    return $out;
}

try {
    $html = fetch_html("https://kipashokijule.com/togel");

    $data = parse_lottery_rows($html);

    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => true, 'data' => $data], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
