<?php
// 1. Basic Settings
ini_set('display_errors', 0);
error_reporting(E_ALL);

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

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

// --- Helper Function: फाइल सेव करें और लोकल लिंक बनाएं ---
function getLocalLink($filename, $sourceUrl) {
    // 1. अगर फाइल सर्वर पर नहीं है, तो डाउनलोड कर लो
    if (!file_exists($filename)) {
        $data = @file_get_contents($sourceUrl);
        if ($data) {
            file_put_contents($filename, $data);
        }
    }

    // 2. अपना खुद का लोकल लिंक बनाओ
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    // जिस फोल्डर में यह PHP फाइल है, उसी का रास्ता निकालें
    $path = dirname($_SERVER['PHP_SELF']);
    
    // उदाहरण: https://55dk.site/api/win_anim.json
    return "$protocol://$host$path/$filename";
}

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

    // 2. INPUT READ
    $body = file_get_contents("php://input");
    $post = json_decode($body, true);
    if (!$post) { $post = $_POST; }

    if (!isset($post["issueNumber"])) {
        throw new Exception("Missing param: issueNumber");
    }

    // JWT AUTH
    $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");
    }
    $loggedInUserId = intval($jwt['payload']['id']);

    $issueNumInput = $post["issueNumber"];
    if (is_array($issueNumInput)) {
        $issueNumber = trim((string)$issueNumInput[0]);
    } else {
        $issueNumber = trim((string)$issueNumInput);
    }

    // Read game type (1=1min, 2=3min, 3=5min, 4=30s)
    $typeId = 0;
    if (isset($post["typeId"])) {
        $typeId = intval($post["typeId"]);
    }
    $gameFilter = ($typeId > 0) ? "AND game_type = $typeId" : "";

    // 3. GET RESULT
    $sql = "SELECT number, colour FROM wingo_results WHERE issue_number='$issueNumber' AND user_id IS NULL $gameFilter LIMIT 1";
    $res = $conn->query($sql);
    
    if (!$res || $res->num_rows === 0) {
        throw new Exception("Result pending: $issueNumber");
    }

    $result = $res->fetch_assoc();
    $winningNumber = intval($result["number"]);
    $winningColour = $result["colour"];
    $bigSmall = ($winningNumber >= 5) ? "big" : "small";
    $evenOdd  = ($winningNumber % 2 == 0) ? "even" : "odd";

    // --- 4. CREATE LOCAL LINKS (AUTOMATIC) ---
    // यह कोड फाइल को आपके सर्वर पर 'win_anim.json' के नाम से सेव करेगा
    // और गेम को आपकी वेबसाइट का लिंक देगा।
    
    $urlMain = "https://91appt.com/assets/json/win_animation-7d5b66f8.json";
    $urlTip  = "https://91appt.com/assets/json/winTip-4f4f6226.json";

    // जादू यहाँ है:
    $myLocalLink1 = getLocalLink("win_anim.json", $urlMain);
    $myLocalLink2 = getLocalLink("win_tip.json", $urlTip);

    // 5. SETTLE ALL OUTSTANDING BETS FOR THIS ISSUE (Global Settlement)
    $sqlUnsettled = "SELECT * FROM wingo_results WHERE issue_number='$issueNumber' AND user_id IS NOT NULL AND settled=0 $gameFilter";
    $unsettledBets = $conn->query($sqlUnsettled);

    if ($unsettledBets && $unsettledBets->num_rows > 0) {
        while ($bet = $unsettledBets->fetch_assoc()) {
            $betId    = $bet["id"];
            $userId   = $bet["user_id"];
            $betType  = $bet["bet_type"];
            $amount   = floatval($bet["bet_amount"]);
            $count    = intval($bet["bet_count"]);
            $isWin    = false;

            if (is_numeric($betType) && 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;
            
            $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";

            $conn->query("UPDATE wingo_results SET result_status = '$status', win_amount = '$winAmount', number = '$winningNumber', colour = '$winningColour', settled = 1, updated_at = NOW() WHERE id = $betId");
            if ($isWin && $winAmount > 0) {
                $conn->query("UPDATE shonu_kaichila SET motta = motta + $winAmount WHERE balakedara = $userId");
            }
        }
    }

    // 6. BUILD FINAL DATA FOR THE CURRENT LOGGED IN USER
    $sqlMyBets = "SELECT * FROM wingo_results WHERE issue_number='$issueNumber' AND user_id=$loggedInUserId $gameFilter";
    $myBets = $conn->query($sqlMyBets);
    $finalData = [];

    if ($myBets && $myBets->num_rows > 0) {
        while ($bet = $myBets->fetch_assoc()) {
            $isWin = ($bet["result_status"] === "gagner");
            $winAmount = floatval($bet["win_amount"]);

            $finalData[] = [
                "issueNumber" => $issueNumber,
                "number"      => $winningNumber,
                "colour"      => $winningColour,
                "winAmount"   => number_format($winAmount, 2, '.', ''),
                "state"       => $isWin ? 1 : 0,
                "animation"   => $isWin ? $myLocalLink1 : null,
                "winTip"      => $isWin ? $myLocalLink2 : null
            ];
        }
    }

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

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