<?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_SSL_VERIFYHOST => 2,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT => "Mozilla/5.0",
        CURLOPT_HTTPHEADER => array(
            "Cookie: _ga=GA1.2.1813037619.1757401665; _gid=GA1.2.880462370.1757401665; _tt_enable_cookie=1; _ttp=01K4PMTK747DBKJHEV2EA02PHW_.tt.1; csrf_cookie=e62c60d33694e131aaa3879381fa761d; ruayz=23di3i8tps2h1ohbopkj6ssn3shg38q5; alertnews14052025=disable; _gat_gtag_UA_157160543_1=1; ttcsid=1757401664743::jn9d--IC_PyodoBbDnoO.1.1757402839508; ttcsid_CE29VOBC77UFHEHJIH7G=1757401664742::W6RqALkQUsOY26jDwytj.1.1757402839755",
            "Accept: text/html,application/xhtml+xml"
        )
    ));

    $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, "จับยี่กี VIP") === false) {
        throw new RuntimeException("ไม่พบข้อมูลจับยี่กี VIP ในหน้าเว็บ");
    }

    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_parse_rounds($html)
{
    $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());
}
