<?php
/*
LEGACY VERSION (retained for reference; cookie value intentionally omitted)

<?php
error_reporting(0);
header('Content-type: application/json');
date_default_timezone_set("Asia/Bangkok");

function get_dataa($url) {
  $curl = curl_init();
  curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    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: huay=[cookie value removed];'
    ),
  ));
  $response = curl_exec($curl);
  curl_close($curl);
  return $response;
}

function FilterData($loop){
  $variableee = get_dataa('https://www.lottovip.com/member/result/all');
  $item = _loop($loop);
  $result = [];
  $jsonloop = [];
  $resultVIP = [];
  $loop_time = file_get_contents('system/loop_id.json');
  $loop_time_json = json_decode($loop_time, true);
  for($i = $item['start']; $i <= $item['end']; $i++){
    $start = strpos($variableee, 'จับยี่กี VIP - รอบที่ '.$i.' ');
    $start_cut = substr($variableee, $start);
    if($i == 88){
      $stop = strpos($start_cut, '</section>');
    }else{
      $stop = strpos($start_cut, 'จับยี่กี VIP - รอบที่ '.($i+1).' ');
    }
    $sub = substr($start_cut, 0, $stop);
    $start = strpos($sub, '3ตัวบน');
    $start_cut = substr($sub, $start);
    $stop = strpos($start_cut, '<div class="card text-center w-50 border-card-right m-0">');
    $sub3 = substr($start_cut, 0, $stop);
    $start = strpos($sub3, '<p class="card-text">');
    $start_cut = substr($sub3, $start);
    $stop = strpos($start_cut, '</p>');
    $sub3 = substr($start_cut, 0, $stop);
    $result[$i][0] = str_replace('<p class="card-text">', '', $sub3);
    $start = strpos($sub, '2ตัวล่าง');
    $start_cut = substr($sub, $start);
    if($i == 88){
      $stop = strpos($start_cut, 'tab-pane');
    }else{
      $stop = strpos($start_cut, '<div class="carousel-item ">');
    }
    $sub2 = substr($start_cut, 0, $stop);
    $start = strpos($sub2, '<p class="card-text">');
    $start_cut = substr($sub2, $start);
    $stop = strpos($start_cut, '</p>');
    $sub2 = substr($start_cut, 0, $stop);
    $result[$i][1] = str_replace('<p class="card-text">', '', $sub2);
    array_push($jsonloop, [
      "lottery_loop_name" => $loop_time_json[$i],
      "lottery_loop_time" => $i,
      "lottery_loop_3unit" => $result[$i][0],
      "lottery_loop_2unit" => $result[$i][1],
      "lottery_loop_3unit_vip" => 'xxx',
      "lottery_loop_2unit_vip" => 'xx',
      "lottery_loop_3unit_spc" => 'xxx',
      "lottery_loop_2unit_spc" => 'xx'
    ]);
  }
  return ['loop' => $jsonloop];
}

function _loop($loop){
  $loopid = $loop;
  $start = 1;
  $end = 1;
  if($loopid >= 30){
    $end = $loopid;
    $start = $loopid - 29;
  }
  $end = $loopid;
  return ['start' => $start, 'end' => $end];
}

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

date_default_timezone_set("Asia/Bangkok");

function lv50_json_response($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 lv50_fetch_page()
{
    if (!function_exists("curl_init")) {
        throw new RuntimeException("เซิร์ฟเวอร์ยังไม่ได้เปิดใช้งาน PHP cURL");
    }

    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => "https://www.lottovip.com/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: huay=50e7b4d32878f50d5d97ffd2b92a1c17",
            "Accept: text/html,application/xhtml+xml"
        )
    ));

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

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

    if ($status < 200 || $status >= 300) {
        throw new RuntimeException("เว็บ Lottovip ตอบกลับ HTTP " . $status);
    }

    if (stripos($html, "จับยี่กี VIP") === false) {
        throw new RuntimeException("ไม่พบข้อมูลจับยี่กี VIP ในหน้าเว็บ (อาจถูกส่งไปหน้าเข้าสู่ระบบ)");
    }

    return $html;
}

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

function lv50_parse_rounds($html)
{
    $headingPattern = "/จับยี่กี\\s*VIP\\s*-\\s*รอบที่\\s*(\\d+)/u";
    $headingCount = preg_match_all(
        $headingPattern,
        $html,
        $headings,
        PREG_SET_ORDER | PREG_OFFSET_CAPTURE
    );

    if ($headingCount === false || $headingCount === 0) {
        throw new RuntimeException("หาเลขรอบใน HTML ไม่พบ");
    }

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

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

        if (!preg_match_all($valuePattern, $section, $valueMatches) || count($valueMatches[1]) < 2) {
            continue;
        }

        $threeTop = lv50_text($valueMatches[1][0]);
        $twoBottom = lv50_text($valueMatches[1][1]);

        // The page repeats the same carousel for responsive layouts; later copies have identical values.
        $rounds[$roundNumber] = array(
            "threeTop" => $threeTop !== "" ? $threeTop : "xxx",
            "twoBottom" => $twoBottom !== "" ? $twoBottom : "xx"
        );
    }

    if (count($rounds) === 0) {
        throw new RuntimeException("รอบมีอยู่ แต่ไม่พบค่าเลข 3 ตัวบน / 2 ตัวล่างใน HTML");
    }

    return $rounds;
}

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

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

try {
    $loop = isset($_GET["loop"]) ? (int)$_GET["loop"] : 1;
    $range = lv50_loop_range($loop);
    $rounds = lv50_parse_rounds(lv50_fetch_page());

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

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

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

        $output[] = array(
            "lottery_loop_name" => isset($loopTime[(string)$i]) ? $loopTime[(string)$i] : "",
            "lottery_loop_time" => $i,
            "lottery_loop_3unit" => $rounds[$i]["threeTop"],
            "lottery_loop_2unit" => $rounds[$i]["twoBottom"],
            "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) {
    lv50_json_response(500, $e->getMessage());
}
