<?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');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header('Access-Control-Allow-Origin: ' . $origin);
header('Vary: Origin');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

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']) && isset($shonupost['random']) && isset($shonupost['signature']) && isset($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, 1);

            if($data_auth['status'] === 'Success') {
                $sesquery = "SELECT akshinak FROM shonu_subjects WHERE akshinak = '$author'";
                $sesresult = $conn->query($sesquery);
                $sesnum = mysqli_num_rows($sesresult);

                if($sesnum == 1){
                    $userId = $data_auth['payload']['id'];

                    // Check user's turntable record
                    $turntableQuery = "SELECT total_spins, invited_wheel_amount FROM shonu_turntable WHERE user_id = $userId";
                    $turntableResult = $conn->query($turntableQuery);

                    if($turntableResult && mysqli_num_rows($turntableResult) > 0){
                        $turntableRow = mysqli_fetch_assoc($turntableResult);
                        $userInvitedWheelCount = intval($turntableRow['total_spins']);
                        $userInvitedWheelAmount = floatval($turntableRow['invited_wheel_amount']);
                    } else {
                        // First time user: create record with 1 spin
                        $userInvitedWheelCount = 1;
                        $userInvitedWheelAmount = 0.00;
                        $insertQuery = "INSERT INTO shonu_turntable (user_id, total_spins, invited_wheel_amount) VALUES ($userId, 1, 0)";
                        $conn->query($insertQuery);
                    }

                    // Minimum withdrawal amount fixed
                    $invitedWheelAmountofcodeAmount = 500.00;

                    // Get total prize amount from all spins
                    $totalPrizeQuery = "SELECT SUM(prize_amount) as total_prize FROM shonu_turntable_spins WHERE user_id = ".$userId;
                    $totalPrizeResult = $conn->query($totalPrizeQuery);
                    $invitedWheelTotalPrizeAmount = 0.00;

                    if($totalPrizeResult && mysqli_num_rows($totalPrizeResult) > 0) {
                        $totalPrizeRow = mysqli_fetch_array($totalPrizeResult);
                        $invitedWheelTotalPrizeAmount = floatval($totalPrizeRow['total_prize']);
                    }

                    // Ensure minimum total prize 500
                    if($invitedWheelTotalPrizeAmount < 500) {
                        $invitedWheelTotalPrizeAmount = 500.00;
                    }

                    // Check if this is user's first spin
                    $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);

                    // Wheel open status
                    $isOpenInvitedWheel = true;

                    // Expired time 72 hours
                    $expiredTime = date('Y-m-d H:i:s', strtotime('+72 hours'));

                    // Disk display amounts
                    $diskDisplayAmount = [500.0, 5.0, 10.0, 20.0, 30.0, 50.0, 80.0];

                    // No winning random amounts
                    $noWinningRandomAmount = [0.0, 10.0];

                    // Last 10 wheel records
                    $historyQuery = "SELECT user_id, user_name, prize_amount, spin_time as createTime 
                                    FROM shonu_turntable_spins 
                                    WHERE user_id = ".$userId." 
                                    ORDER BY spin_time DESC LIMIT 10";
                    $historyResult = $conn->query($historyQuery);
                    $lastWheelRecordList = [];

                    if($historyResult && mysqli_num_rows($historyResult) > 0) {
                        while($historyRow = mysqli_fetch_assoc($historyResult)) {
                            $lastWheelRecordList[] = [
                                'userId' => (int)$historyRow['user_id'],
                                'userName' => $historyRow['user_name'] ?? 'User',
                                'invitedWheelAmount' => floatval($userInvitedWheelAmount),
                                'prizeAmount' => floatval($historyRow['prize_amount']),
                                'createTime' => $historyRow['createTime']
                            ];
                        }
                    }

                    if(empty($lastWheelRecordList)) {
                        $lastWheelRecordList = [
                            [
                                'userId' => (int)$userId,
                                'userName' => 'User',
                                'invitedWheelAmount' => floatval($userInvitedWheelAmount),
                                'prizeAmount' => 0.02,
                                'createTime' => date('Y-m-d H:i:s', strtotime('-1 hour'))
                            ]
                        ];
                    }

                    // Prepare response
                    $data['isOpenInvitedWheel'] = $isOpenInvitedWheel;
                    $data['isFirstInvitedWheel'] = $isFirstInvitedWheel;
                    $data['userInvitedWheelCount'] = (int)$userInvitedWheelCount;
                    $data['userInvitedWheelAmount'] = floatval($userInvitedWheelAmount);
                    $data['invitedWheelTotalPrizeAmount'] = floatval($invitedWheelTotalPrizeAmount);
                    $data['invitedWheelAmountofcodeAmount'] = floatval($invitedWheelAmountofcodeAmount);
                    $data['expiredTime'] = $expiredTime;
                    $data['diskDisplayAmount'] = $diskDisplayAmount;
                    $data['noWinningRandomAmount'] = $noWinningRandomAmount;
                    $data['lastWheelRecordList'] = $lastWheelRecordList;

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