<?php
// GetNoaverageEmerdList.php - FINAL VERSION (Only API → wingo_results)

ini_set('display_errors', 0);
error_reporting(E_ALL);

include "../../conn.php";
include "../../functions2.php";

header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");

date_default_timezone_set("Asia/Kolkata");
$now = date("Y-m-d H:i:s");

// type mapping
$TYPE_MAP = [
    4 => "WinGo_30S/GetHistoryIssuePage.json",
    1 => "WinGo_1M/GetHistoryIssuePage.json",
    2 => "WinGo_3M/GetHistoryIssuePage.json",
    3 => "WinGo_5M/GetHistoryIssuePage.json",
];

// Input
$body = file_get_contents("php://input");
$post = json_decode($body, true);

if (!$post) {
    echo json_encode(["code"=>500,"msg"=>"Invalid JSON Body"]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode(["code"=>11,"msg"=>"Method not allowed"]);
    exit;
}

// Required params
$required = ['language','random','signature','timestamp','typeId'];
foreach ($required as $r) {
    if (!isset($post[$r])) {
        echo json_encode(["code"=>7,"msg"=>"Missing param: $r"]);
        exit;
    }
}

$language = intval($post['language']);
$pageNo   = intval($post['pageNo'] ?? 1);
$pageSize = intval($post['pageSize'] ?? 10);
$random   = (string)$post['random'];
$typeId   = intval($post['typeId']);

if (!isset($TYPE_MAP[$typeId])) $typeId = 1;

// verify signature
$signArr = [
    "language"=>$language,
    "pageNo"=>$pageNo,
    "pageSize"=>$pageSize,
    "random"=>$random,
    "typeId"=>$typeId
];

$calcSign = strtoupper(md5(json_encode($signArr, JSON_UNESCAPED_UNICODE)));
if ($calcSign !== strtoupper($post['signature'])) {
    echo json_encode(["code"=>5,"msg"=>"Wrong signature"]);
    exit;
}

// JWT AUTH
$auth = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$token = explode(" ", $auth)[1] ?? '';
$jwt = json_decode(is_jwt_valid($token), true);

if (!$jwt || $jwt['status'] !== 'Success') {
    echo json_encode(["code"=>4,"msg"=>"No operation permission"]);
    exit;
}

// remote API
$REMOTE_BASE = "https://draw.ar-lottery01.com/WinGo";
$endpoint = $TYPE_MAP[$typeId];

$remoteUrl = "$REMOTE_BASE/$endpoint?ts=" . (int)(microtime(true)*1000);

// --- PROXY CONFIG ---
// CHANGE THIS TO YOUR VPS IP WHERE YOU HOSTED vps_proxy.php
$VPS_PROXY = "http://club44.us.cc/wingoapi/vps_proxy.php"; 
// --------------------

$proxyUrl = $VPS_PROXY . "?url=" . urlencode($remoteUrl);

$ch = curl_init($proxyUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// No need for strict SSL or UserAgent here since it's connecting to your own VPS
$raw = curl_exec($ch);
curl_close($ch);
if (!$raw) {
    echo json_encode(["code"=>500,"msg"=>"API Error"]);
    exit;
}

$data = json_decode($raw, true);
if (!isset($data["data"]["list"])) {
    echo json_encode(["code"=>500,"msg"=>"Invalid API Structure"]);
    exit;
}

$list = $data["data"]["list"];

// ──── 1-PERIOD DELAY ────
// Skip the first item (real current period result) so the displayed
// history starts from the previous period, matching the delayed
// issueNumber returned by GetGameIssue.php
if (count($list) > 1) {
    array_shift($list);  // remove index 0 (real current)
}

// prepare save stmt
try {
    $stmt = $conn->prepare("
        INSERT INTO wingo_results (issue_number, game_type, number, colour, premium, raw_json)
        VALUES (?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
            number=VALUES(number),
            colour=VALUES(colour),
            premium=VALUES(premium),
            raw_json=VALUES(raw_json),
            updated_at=NOW()
    ");

    if ($stmt) {
        foreach ($list as $row) {
            $issue   = $row["issueNumber"];
            $number  = $row["number"];
            $colour  = $row["colour"] ?? "";
            $premium = $row["premium"] ?? "0";
            $rawJson = json_encode($row);

            $stmt->bind_param(
                "ssisss",
                $issue,
                $typeId,
                $number,
                $colour,
                $premium,
                $rawJson
            );

            $stmt->execute();
        }
    }
} catch (Throwable $e) {
    // Silently handle DB table errors so that we still return valid JSON
    error_log("Wingo Sync DB Error: " . $e->getMessage());
}

echo json_encode([
    "code"=>0,
    "msg"=>"Succeed",
    "msgCode"=>0,
    "serviceNowTime"=>$now,
    "data"=>[
        "list"=>$list
    ]
], JSON_PRETTY_PRINT);

exit;
?>
