<?php
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");

/* ========= METHOD CHECK ========= */
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode([
        "code"=>11,
        "msg"=>"Method not allowed",
        "msgCode"=>12,
        "serviceNowTime"=>$now
    ]);
    exit;
}

/* ========= INPUT ========= */
$body = json_decode(file_get_contents("php://input"), true);
if (!$body) {
    echo json_encode(["code"=>7,"msg"=>"Invalid JSON"]);
    exit;
}

/* ========= JWT ========= */
$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","msgCode"=>2]);
    exit;
}

$userId = intval($jwt['payload']['id']);

/* ========= PAGINATION ========= */
$pageNo   = intval($body['pageNo'] ?? 1);
$pageSize = intval($body['pageSize'] ?? 10);
$typeId   = intval($body['typeId'] ?? 0);
$offset   = ($pageNo - 1) * $pageSize;

/* ========= QUERY ========= */
$gameFilter = ($typeId > 0) ? "AND game_type = $typeId" : "";
$sql = "
SELECT 
    id,
    issue_number,
    game_type,
    bet_type,
    bet_amount,
    bet_count,
    bet_total,
    number,
    colour,
    win_amount,
    result_status,
    settled,
    created_at
FROM wingo_results
WHERE user_id = $userId $gameFilter
ORDER BY id DESC
LIMIT $pageSize OFFSET $offset
";

$q = $conn->query($sql);

$list = [];
$i = 0;

while ($row = $q->fetch_assoc()) {

    $betId     = intval($row['id']);
    $isSettled = intval($row['settled']);
    $status    = $row['result_status'];

    /* ===== ON-THE-FLY SETTLEMENT ===== */
    /* If this bet has not been settled yet, try to settle it now */
    if ($isSettled == 0 || empty($status)) {
        $issueNumber = $row['issue_number'];
        $betGameType = intval($row['game_type']);
        $gtFilter = ($betGameType > 0) ? "AND game_type = $betGameType" : "";

        // Look up the official drawn result for this issue
        $resSql = "SELECT number, colour FROM wingo_results 
                   WHERE issue_number='$issueNumber' AND user_id IS NULL $gtFilter LIMIT 1";
        $resQ = $conn->query($resSql);

        if ($resQ && $resQ->num_rows > 0) {
            $official = $resQ->fetch_assoc();
            $winningNumber = intval($official['number']);
            $winningColour = $official['colour'];
            $bigSmall = ($winningNumber >= 5) ? "big" : "small";
            $evenOdd  = ($winningNumber % 2 == 0) ? "even" : "odd";

            $betType = $row['bet_type'];
            $amount  = floatval($row['bet_amount']);
            $count   = intval($row['bet_count']);
            $isWin   = false;

            // Check win conditions
            if (is_numeric($betType) && intval($betType) >= 0 && intval($betType) <= 9 && intval($betType) === $winningNumber) $isWin = true;
            if ($betType == "13" && $bigSmall == "big") $isWin = true;
            if ($betType == "14" && $bigSmall == "small") $isWin = true;
            if ($betType == "10" && $evenOdd == "even") $isWin = true;
            if ($betType == "11" && $evenOdd == "odd")  $isWin = true;
            if ($betType == "12" && ($winningNumber == 0 || $winningNumber == 5)) $isWin = true;

            // Calculate multiplier
            $multiplier = 1.96;
            if (is_numeric($betType) && intval($betType) >= 0 && intval($betType) <= 9) {
                $multiplier = 9.0;
            } else if ($betType == "12") {
                $multiplier = 4.5;
            } else if ($betType == "10" || $betType == "11") {
                if ($winningNumber == 0 || $winningNumber == 5) {
                    $multiplier = 1.5;
                } else {
                    $multiplier = 1.96;
                }
            } else {
                $multiplier = 1.96;
            }

            $winAmount = $isWin ? ($amount * $count * 0.98 * $multiplier) : 0; // 2% tax deducted
            $status = $isWin ? "gagner" : "perte";

            // Update the bet in DB
            $conn->query("UPDATE wingo_results SET result_status = '$status', win_amount = '$winAmount', number = '$winningNumber', colour = '$winningColour', settled = 1, updated_at = NOW() WHERE id = $betId");

            // Credit the user's balance if they won
            if ($isWin && $winAmount > 0) {
                $conn->query("UPDATE shonu_kaichila SET motta = motta + $winAmount WHERE balakedara = $userId");
            }

            // Update local vars for display
            $row['number'] = $winningNumber;
            $row['colour'] = $winningColour;
            $row['win_amount'] = $winAmount;
            $row['result_status'] = $status;
            $isSettled = 1;
        }
    }

    /* ===== Bet Type Name ===== */
    $selectType = $row['bet_type'];
    if ($selectType == 13) $selectType = 'big';
    elseif ($selectType == 14) $selectType = 'small';
    elseif ($selectType == 10) $selectType = 'red';
    elseif ($selectType == 11) $selectType = 'green';
    elseif ($selectType == 12) $selectType = 'violet';

    /* ===== Amount ===== */
    $amount    = floatval($row['bet_amount']);
    $betCount  = intval($row['bet_count']);
    $totalBet = $amount * $betCount;

    if (floatval($row['bet_total']) > 0) {
        $totalBet = floatval($row['bet_total']);
    }

    $status = $row['result_status'];

    /* ===== DEFAULT (PENDING) ===== */
    $state        = 2;        // pending
    $profitAmount = 0;
    $number       = null;
    $colour       = null;

    /* ===== WIN ===== */
    if ($status === 'gagner') {
        $state        = 1; // green
        $profitAmount = floatval($row['win_amount']);
        $number       = $row['number'];
        $colour       = $row['colour'];
    }

    /* ===== LOSS ===== */
    elseif ($status === 'perte') {
        $state        = 0; // red
        $profitAmount = $totalBet;
        $number       = $row['number'];
        $colour       = $row['colour'];
    }

    $list[] = [
        "orderNumber"  => $i++,
        "issueNumber"  => $row['issue_number'],
        "amount"       => $amount,
        "betCount"     => $betCount,
        "realAmount"   => $totalBet,
        "number"       => $number,
        "selectType"   => $selectType,
        "state"        => $state,              // 2=pending,1=win,0=loss
        "profitAmount" => $state == 2 ? null : number_format($profitAmount, 2, '.', ''),
        "colour"       => $colour,
        "addTime"      => $row['created_at']
    ];
}

/* ========= COUNT ========= */
$cq = $conn->query("SELECT COUNT(*) c FROM wingo_results WHERE user_id=$userId $gameFilter");
$total = $cq->fetch_assoc()['c'];

echo json_encode([
    "code"=>0,
    "msg"=>"Succeed",
    "msgCode"=>0,
    "serviceNowTime"=>$now,
    "data"=>[
        "list"=>$list,
        "pageNo"=>$pageNo,
        "totalPage"=>ceil($total/$pageSize),
        "totalCount"=>$total
    ]
], JSON_PRETTY_PRINT);

exit;
?>
