<?php
/*
LEGACY VERSION (retained for reference; session cookie redacted)

<?php
date_default_timezone_set("Asia/Bangkok");
function get_dataa($url) {
  // The old implementation fetched the page using a fixed Cookie header.
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://www.ruay.org/member/result/all',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_HTTPHEADER => array('Cookie: [session cookie removed]')
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  return $response;
}

function remove_empty($array) {
  return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
  return !empty($value) || $value === 0;
}

function Get_ruay($loop, $variable) {
  $loop_time = file_get_contents('system/loop_time_ruay.json');
  $loop_time_json = json_decode($loop_time, true);
  $start = strpos($variable, 'จับยี่กี VIP - รอบที่ '.$loop);
  $start_cut = substr($variable, $start);
  $stop = strpos($start_cut, '<div class="carousel-item ">');
  $sub = substr($start_cut, 0, $stop);
  $FilterHTML = strip_tags(trim($sub));
  $data = explode("\n", $FilterHTML);
  $trimmedArray = array_map('trim', $data);
  $filterData = array();
  foreach ($trimmedArray as $value) {
    if (trim($value) != '') array_push($filterData, $value);
  }
  $result['loop'] = trim($filterData[0]);
  $result['top'] = trim($filterData[2]);
  $result['button'] = trim($filterData[4]);
  $result['time'] = date('Y-m-d H:i:s');
  $result['status'] = true;
  $jsonloop["lottery_loop_name"] = $loop_time_json[$loop];
  $jsonloop["lottery_loop_time"] = $loop;
  $jsonloop["lottery_loop_3unit"] = trim($result['top']);
  $jsonloop["lottery_loop_2unit"] = trim($result['button']);
  $jsonloop["lottery_loop_3unit_vip"] = 'xxx';
  $jsonloop["lottery_loop_2unit_vip"] = 'xx';
  $jsonloop["lottery_loop_3unit_spc"] = 'xxx';
  $jsonloop["lottery_loop_2unit_spc"] = 'xx';
  return $jsonloop;
}

function Get_loop($loop) {
  $loopid = $loop;
  $start = 1;
  $end = 1;
  if($loopid >= 88):
    $end = $loopid;
    $start = $loopid - 87;
  endif;
  $end = $loopid;
  return array('start' => $start, 'end' => $end);
}

function Build_Json($loop) {
  $url = 'https://www.ruay.org/login';
  $variable = get_dataa($url);
  $start = strpos($variable, '<div class="card border-secondary text-center mb-2">');
  $start_cut = substr($variable, $start);
  $stop = strpos($start_cut, '<!-- end carousel-inner -->');
  $sub = substr($start_cut, 0, $stop);
  $item = Get_loop($loop);
  $jsonloop = array();
  for($i = $item['start']; $i <= $item['end']; $i++) {
    $result = Get_ruay($i, $sub);
    array_push($jsonloop, $result);
  }
  return array('jsonloop' => $jsonloop);
}

$Itemloop = $_GET['loop'];
if(isset($Itemloop) and $Itemloop != '') $res = Build_Json($Itemloop);
echo json_encode($res['jsonloop']);
?>
*/

date_default_timezone_set("Asia/Bangkok");

function ruay50_error($status, $message)
{
    http_response_code($status);
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode(array("error" => $message), JSON_UNESCAPED_UNICODE);
    exit;
}

function ruay50_fetch_page()
{
    if (!function_exists("curl_init")) {
        throw new RuntimeException("เซิร์ฟเวอร์ยังไม่ได้เปิดใช้งาน PHP cURL");
    }

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => "https://www.ruay.org/member/result/all",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT => "Mozilla/5.0",
        CURLOPT_HTTPHEADER => array(
            "Accept: text/html,application/xhtml+xml",
            "Priority: u=0, i",
            "Referer: https://www.ruay.org/member/result/all/1791824400000",
            "Cookie: _ga=GA1.2.154239601.1791125909; ruay_dt=8269792914fd85b11f94d7cb75e3e2b9; _gid=GA1.2.899966920.1791956514; alertnews_af8_ai_121026=disable; ruayz=6c3b61af8fe06cc07be30812544f50fe80847b83; csrf_cookie=1ce253bf3725e1aa91e271cadc098c72; ruay_did=8e34b36977d8db508e137109ce6fd3d0"
        )
    ));

    $html = curl_exec($ch);
    if ($html === false) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new RuntimeException("ดึงหน้า Ruay ไม่สำเร็จ: " . $error);
    }

    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status < 200 || $status >= 300) {
        throw new RuntimeException("เว็บ Ruay ตอบกลับ HTTP " . $status);
    }
    if (stripos($html, "rs-ykrow") === false
        && stripos($html, "จับยี่กี VIP") === false) {
        throw new RuntimeException("ไม่พบรายการผลยี่กีในหน้าเว็บ");
    }

    return $html;
}

function ruay50_clean_text($html)
{
    $text = html_entity_decode(strip_tags($html), ENT_QUOTES, "UTF-8");
    return trim(preg_replace("/\\s+/u", " ", $text));
}

function ruay50_extract_digit_value($html, $placeholder)
{
    $digits = array();
    if (preg_match_all("/<b\\b[^>]*>(.*?)<\\/b>/isu", $html, $matches)) {
        foreach ($matches[1] as $match) {
            $part = ruay50_clean_text($match);
            if ($part !== "") {
                $digits[] = $part;
            }
        }
    }

    $value = count($digits) > 0 ? implode("", $digits) : ruay50_clean_text($html);
    if ($value === "" || preg_match("/^[\\x{002D}\\x{2010}-\\x{2015}\\x{2212}\\x{FE58}\\x{FE63}\\x{FF0D}]+$/u", $value)
        || preg_match("/^รอผล(?:\\s|$)/u", $value)) {
        return $placeholder;
    }

    return $value;
}

function ruay50_parse_rounds($html)
{
    // Current Ruay layout uses rs-ykrow links with one row per Yeekee round.
    $rounds = array();
    $rowPattern = "/<a\\b(?=[^>]*\\brs-ykrow\\b)[^>]*>(.*?)<\\/a>/isu";
    if (preg_match_all($rowPattern, $html, $rows)) {
        foreach ($rows[1] as $row) {
            if (!preg_match("/class=[\"'][^\"']*\\brs-ykrow__no\\b[^\"']*[\"'][^>]*>(\\d+)</u", $row, $roundMatch)) {
                continue;
            }

            $top = "xxx";
            $bottom = "xx";
            if (preg_match("/<small>\\s*3\\s*ตัวบน\\s*<\\/small>.*?<span\\b[^>]*class=[\"'][^\"']*\\bmb-digits\\b[^\"']*[\"'][^>]*>(.*?)<\\/span>/isu", $row, $topMatch)) {
                $top = ruay50_extract_digit_value($topMatch[1], "xxx");
            }
            if (preg_match("/<small>\\s*2\\s*ตัวล่าง\\s*<\\/small>.*?<span\\b[^>]*class=[\"'][^\"']*\\bmb-digits\\b[^\"']*[\"'][^>]*>(.*?)<\\/span>/isu", $row, $bottomMatch)) {
                $bottom = ruay50_extract_digit_value($bottomMatch[1], "xx");
            }

            $rounds[(int)$roundMatch[1]] = array("top" => $top, "bottom" => $bottom);
        }
    }

    if (count($rounds) > 0) {
        return $rounds;
    }

    // Legacy layout fallback.
    $headingPattern = "/จับยี่กี\\s*VIP\\s*-\\s*รอบที่\\s*(\\d+)/u";
    $count = preg_match_all(
        $headingPattern,
        $html,
        $headings,
        PREG_SET_ORDER | PREG_OFFSET_CAPTURE
    );
    if ($count === false || $count === 0) {
        throw new RuntimeException("หาเลขรอบใน HTML ไม่พบ");
    }

    $rounds = array();
    $length = strlen($html);
    $valuePattern = "/<p\\b[^>]*class=[\"'][^\"']*\\bcard-text\\b[^\"']*[\"'][^>]*>(.*?)<\\/p>/isu";

    foreach ($headings as $index => $heading) {
        $round = (int)$heading[1][0];
        $start = $heading[0][1] + strlen($heading[0][0]);
        $end = isset($headings[$index + 1])
            ? $headings[$index + 1][0][1]
            : $length;
        $fragment = substr($html, $start, $end - $start);

        if (preg_match_all($valuePattern, $fragment, $values) && count($values[1]) >= 2) {
            $top = ruay50_clean_text($values[1][0]);
            $bottom = ruay50_clean_text($values[1][1]);
            $rounds[$round] = array(
                "top" => $top !== "" ? $top : "xxx",
                "bottom" => $bottom !== "" ? $bottom : "xx"
            );
        }
    }

    if (count($rounds) === 0) {
        throw new RuntimeException("ไม่พบค่าผลรางวัลใน HTML");
    }

    return $rounds;
}

function ruay50_range($loop)
{
    $loop = (int)$loop;
    if ($loop < 1) {
        $loop = 1;
    }

    return array(
        "start" => $loop >= 88 ? $loop - 87 : 1,
        "end" => $loop
    );
}

try {
    $loop = isset($_GET["loop"]) ? (int)$_GET["loop"] : 1;
    $range = ruay50_range($loop);
    $rounds = ruay50_parse_rounds(ruay50_fetch_page());

    $timePath = __DIR__ . "/system/loop_time_ruay.json";
    if (!is_readable($timePath)) {
        throw new RuntimeException("อ่านไฟล์ system/loop_time_ruay.json ไม่ได้");
    }

    $times = json_decode(file_get_contents($timePath), true);
    if (!is_array($times)) {
        throw new RuntimeException("ไฟล์ system/loop_time_ruay.json มี JSON ไม่ถูกต้อง");
    }

    $output = array();
    for ($i = $range["start"]; $i <= $range["end"]; $i++) {
        if (!isset($rounds[$i])) {
            continue;
        }

        $output[] = array(
            "lottery_loop_name" => isset($times[(string)$i]) ? $times[(string)$i] : "",
            "lottery_loop_time" => $i,
            "lottery_loop_3unit" => $rounds[$i]["top"],
            "lottery_loop_2unit" => $rounds[$i]["bottom"],
            "lottery_loop_3unit_vip" => "xxx",
            "lottery_loop_2unit_vip" => "xx",
            "lottery_loop_3unit_spc" => "xxx",
            "lottery_loop_2unit_spc" => "xx"
        );
    }

    header("Content-Type: application/json; charset=utf-8");
    echo json_encode($output, JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    ruay50_error(500, $e->getMessage());
}
