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

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('vary: Origin');

date_default_timezone_set("Asia/Kolkata");
$shnunc = date("Y-m-d H:i:s");
$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $shnunc,
];

$shonubody = file_get_contents("php://input");
$shonupost = json_decode($shonubody, true);

if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    if (isset($shonupost['language'], $shonupost['random'], $shonupost['signature'], $shonupost['timestamp'])) {
        $language = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['language']));
        $random = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['random']));
        $signature = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['signature']));
        $shonustr = '{"language":'.$language.',"random":"'.$random.'"}';
        $shonusign = strtoupper(md5($shonustr));

        if($shonusign == $signature){
            $bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
            $author = $bearer[1] ?? '';
            $is_jwt_valid = is_jwt_valid($author);
            $data_auth = json_decode($is_jwt_valid, true);

            if($data_auth['status'] === 'Success') {
                $userId = (int)$data_auth['payload']['id'];

                // Ensure shonu_turntable row exists
                $checkTurntableQuery = "SELECT * FROM shonu_turntable WHERE user_id = $userId";
                $checkTurntableResult = $conn->query($checkTurntableQuery);

                if(mysqli_num_rows($checkTurntableResult) == 0) {
                    // new user => 2 spins
                    $insertTurntableQuery = "INSERT INTO shonu_turntable (user_id, invited_wheel_amount, total_spins, spin_start_time) 
                                             VALUES ($userId, 0.00, 2, NULL)";
                    $conn->query($insertTurntableQuery);
                    $availableSpins = 2;
                    $spinStartTime = null;
                } else {
                    $row = mysqli_fetch_assoc($checkTurntableResult);
                    $availableSpins = (int)$row['total_spins'];
                    $spinStartTime = $row['spin_start_time']; // datetime string or NULL
                }

                // Check 72-hour timer
                $timeExpired = false;
                if($spinStartTime !== null){
                    $expireTime = strtotime($spinStartTime) + (72*3600);
                    if(time() > $expireTime){
                        // Timer expired, reset spins and amount
                        $updateResetQuery = "UPDATE shonu_turntable 
                                             SET total_spins = 2, 
                                                 invited_wheel_amount = 0.00,
                                                 spin_start_time = NULL,
                                                 updated_at = NOW()
                                             WHERE user_id = $userId";
                        $conn->query($updateResetQuery);
                        $availableSpins = 2;
                        $timeExpired = true;
                    }
                }

                if($availableSpins <= 0){
                    $res['code'] = 8;
                    $res['msg'] = 'No spins left';
                    $res['msgCode'] = 9;
                    http_response_code(200);
                    echo json_encode($res);
                    exit();
                }

                // Check if first spin ever
                $firstSpinQuery = "SELECT COUNT(*) as total_spins FROM shonu_turntable_spins WHERE user_id = $userId";
                $firstSpinResult = $conn->query($firstSpinQuery);
                $firstSpinRow = mysqli_fetch_array($firstSpinResult);
                $isFirstInvitedWheel = ($firstSpinRow['total_spins'] == 0);

                // Start timer if first spin
                if($spinStartTime === null){
                    $updateTimerQuery = "UPDATE shonu_turntable SET spin_start_time = '$shnunc' WHERE user_id = $userId";
                    $conn->query($updateTimerQuery);
                    $spinStartTime = $shnunc;
                }

                // Fetch user name
                $userQuery = "SELECT codechorkamukala FROM shonu_subjects WHERE id = $userId";
                $userResult = $conn->query($userQuery);
                $userRow = mysqli_fetch_array($userResult);
                $userName = $userRow['codechorkamukala'] ?? 'User';

                // Default prize values
                $prizeAmount = 0.00;
                $isWin = false;
                $firstInvitedWheelDatas = null;

                if($isFirstInvitedWheel || $timeExpired){
                    // First spin or expired: 4-box logic
                    $boxes = [
                        ['amount' => 400.00, 'isSelected' => false],
                        ['amount' => 490.00, 'isSelected' => false],
                        ['amount' => 478.00, 'isSelected' => false],
                        ['amount' => 494.00, 'isSelected' => false]
                    ];
                    $selectedIndex = array_rand($boxes);
                    $boxes[$selectedIndex]['isSelected'] = true;
                    $prizeAmount = $timeExpired ? 0.00 : floatval($boxes[$selectedIndex]['amount']);
                    $isWin = ($prizeAmount > 0);
                    $firstInvitedWheelDatas = $boxes;
                } else {
                    // Normal spin probability
                    $prizes = [
                        ['amount' => 0.02, 'probability' => 0.35, 'isWin' => true],
                        ['amount' => 0.05, 'probability' => 0.25, 'isWin' => true],
                        ['amount' => 0.10, 'probability' => 0.15, 'isWin' => true],
                        ['amount' => 0.20, 'probability' => 0.10, 'isWin' => true],
                        ['amount' => 0.50, 'probability' => 0.08, 'isWin' => true],
                        ['amount' => 1.00, 'probability' => 0.05, 'isWin' => true],
                        ['amount' => 2.00, 'probability' => 0.02, 'isWin' => true],
                        ['amount' => 0.00, 'probability' => 0.00, 'isWin' => false]
                    ];
                    $sumProb = 0.0;
                    foreach ($prizes as $p) $sumProb += $p['probability'];
                    $r = mt_rand() / mt_getrandmax();
                    $cumulative = 0.0;
                    $selectedPrize = null;
                    foreach ($prizes as $p){
                        $cumulative += ($p['probability'] / max($sumProb, 1.0));
                        if($r <= $cumulative){
                            $selectedPrize = $p;
                            break;
                        }
                    }
                    if($selectedPrize === null){
                        $selectedPrize = ['amount'=>0.00,'isWin'=>false];
                    }
                    $prizeAmount = floatval($selectedPrize['amount']);
                    $isWin = (bool)$selectedPrize['isWin'];
                }

                // Record spin
                $spinTime = date('Y-m-d H:i:s');
                $insertSpinQuery = "INSERT INTO shonu_turntable_spins (user_id, prize_amount, spin_time, user_name) 
                                    VALUES ($userId, $prizeAmount, '$spinTime', '".mysqli_real_escape_string($conn,$userName)."')";
                $conn->query($insertSpinQuery);

                // Update spins (-1) and wallet if win
                $newAvailableSpins = $availableSpins - 1;
                $updateSpinsQuery = "UPDATE shonu_turntable SET total_spins = $newAvailableSpins, updated_at = NOW()";
                if($isWin && $prizeAmount > 0){
                    $updateSpinsQuery .= ", invited_wheel_amount = invited_wheel_amount + $prizeAmount";
                    $conn->query("UPDATE shonu_kaichila SET motta = motta + $prizeAmount, updated_at = NOW() WHERE balakedara = $userId");
                }
                $updateSpinsQuery .= " WHERE user_id = $userId";
                $conn->query($updateSpinsQuery);

                // Prepare response
                $data['isFirstInvitedWheel'] = $isFirstInvitedWheel || $timeExpired;
                $data['prizeAmount'] = (float)$prizeAmount;
                $data['isWin'] = $isWin;
                $data['firstInvitedWheelDatas'] = $firstInvitedWheelDatas;
                $data['availableSpins'] = $newAvailableSpins;

                $res['data'] = $data;
                $res['code'] = 0;
                $res['msg'] = 'Succeed';
                $res['msgCode'] = 0;
                $res['serviceNowTime'] = $shnunc;
                http_response_code(200);
                echo json_encode($res);
                exit();

            } else{
                $res['code'] = 4;
                $res['msg'] = 'No operation permission';
                $res['msgCode'] = 2;
                http_response_code(401);
                echo json_encode($res);
                exit();
            }
        } else{
            $res['code'] = 5;
            $res['msg'] = 'Wrong signature';
            $res['msgCode'] = 3;
            http_response_code(200);
            echo json_encode($res);
            exit();
        }
    } else{
        $res['code'] = 7;
        $res['msg'] = 'Param is Invalid';
        $res['msgCode'] = 6;
        http_response_code(200);
        echo json_encode($res);
        exit();
    }		
} else{
    $res['code'] = 11;
    $res['msg'] = 'Method not allowed';
    $res['msgCode'] = 12;
    http_response_code(405);
    echo json_encode($res);
    exit();		
}
?>
