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

try {

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

    if (!$post) {
        throw new Exception("Invalid JSON body");
    }

    $required = [
        "amount","betCount","gameType","issuenumber",
        "selectType","signature","language","random",
        "timestamp","typeId"
    ];

    foreach ($required as $r) {
        if (!isset($post[$r])) {
            throw new Exception("Missing param: $r");
        }
    }

    $amount      = floatval($post['amount']);
    $betCount    = intval($post['betCount']);
    $gameType    = intval($post['gameType']);
    $issue       = trim($post['issuenumber']);
    $typeId      = intval($post['typeId']);
    $selectType  = intval($post['selectType']);
    $random      = $post['random'];
    $language    = $post['language'];

    // signature verify
    $signStr = json_encode([
        "amount"=>$amount,
        "betCount"=>$betCount,
        "gameType"=>$gameType,
        "issuenumber"=>$issue,
        "language"=>$language,
        "random"=>$random,
        "selectType"=>$selectType,
        "typeId"=>$typeId
    ], JSON_UNESCAPED_UNICODE);

    if (strtoupper(md5($signStr)) !== strtoupper($post["signature"])) {
        throw new Exception("Wrong signature");
    }

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

    if (!$jwt || $jwt["status"] !== "Success") {
        throw new Exception("No operation permission");
    }

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

    // check balance
    $q = $conn->query("SELECT motta FROM shonu_kaichila WHERE balakedara = $userId");
    if (!$q) throw new Exception("Balance query failed");

    $bal = $q->fetch_assoc();
    $balance = floatval($bal["motta"]);

    $totalBet = $amount * $betCount;
    if ($balance < $totalBet) {
        echo json_encode(["code"=>1,"msg"=>"Balance is not enough"]);
        exit;
    }

    // BEGIN TRANSACTION
    $conn->begin_transaction();

    // generate unique order id (THIS IS THE KEY FIX)
    $orderId = uniqid("BET_", true);

    // save bet → wingo_results (MULTIPLE BETS ALLOWED)
    $stmt = $conn->prepare("
        INSERT INTO wingo_results
        (issue_number, order_id, game_type, user_id, bet_type,
         bet_amount, bet_count, bet_total, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");

    $stmt->bind_param(
        "ssiiiidi",
        $issue,
        $orderId,
        $typeId,
        $userId,
        $selectType,
        $amount,
        $betCount,
        $totalBet
    );

    if (!$stmt->execute()) {
        throw new Exception("Bet insert failed: ".$stmt->error);
    }

    // deduct balance
    $newBalance = $balance - $totalBet;
    $upd = $conn->query("
        UPDATE shonu_kaichila 
        SET motta = $newBalance, rebet = rebet + $totalBet 
        WHERE balakedara = $userId
    ");

    if (!$upd) {
        throw new Exception("Balance update failed");
    }

    // UPDATE VIP AND REBATE COMMISSION
    $byabaharkarta = $userId;
    $totalamount = $totalBet;
    include "commission.php";
    include "vip.php";

    // COMMIT
    $conn->commit();

    echo json_encode([
        "code"=>0,
        "msg"=>"Succeed",
        "msgCode"=>0,
        "serviceNowTime"=>$now,
        "orderId"=>$orderId
    ]);
    exit;

} catch (Throwable $e) {

    if ($conn && $conn->errno) {
        $conn->rollback();
    }

    error_log("GameBetting ERROR: ".$e->getMessage());

    echo json_encode([
        "code"=>500,
        "msg"=>"Server Controlled Exception",
        "error"=>$e->getMessage()
    ]);
    exit;
}
?>
