<?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-Origin: *'); // Allow all origins for CORS
    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);

    // Only allow non-GET methods
    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']));
            
            // Creating the string for signature verification
            $shonustr = '{"language":'.$language.',"random":"'.$random.'"}';
            $shonusign = strtoupper(md5($shonustr));

            // Check if the provided signature matches the calculated one
            if ($shonusign == $signature) {
                // Extract the JWT token from Authorization header
                $bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
                $author = $bearer[1];

                // Validate JWT token
                $is_jwt_valid = is_jwt_valid($author);
                $data_auth = json_decode($is_jwt_valid, true);

                // If JWT token is valid, proceed further
                if ($data_auth['status'] === 'Success') {
                    $sesquery = "SELECT akshinak FROM shonu_subjects WHERE akshinak = '$author'";
                    $sesresult = $conn->query($sesquery);
                    $sesnum = mysqli_num_rows($sesresult);
                    
                    // Check if the user exists
                    if ($sesnum == 1) {
                        $balquery = "SELECT balakedara, motta FROM shonu_kaichila WHERE balakedara = ".$data_auth['payload']['id'];
                        $balresult = $conn->query($balquery);
                        $balarr = mysqli_fetch_array($balresult);
                        
                        // Get user balance
                        $data['amount'] = $balarr['motta'];
                        $userid= $balarr['balakedara'];
                        
                        $balquerya = "SELECT sum(motta) as mottanew FROM thevani WHERE balakedara ='$userid' and sthiti=1";
                        $balresulta = $conn->query($balquerya);
                        $balarra = mysqli_fetch_array($balresulta);
                        $totalamt = $balarra['mottanew'];
                        
                        
if($totalamt>99){
                     
                         // Send success response with user balance data
                        $res['data'] = $data;
                        $res['code'] = 0;
                        $res['msg'] = 'Succeed';
                        $res['msgCode'] = 0;
                        http_response_code(200);
                        echo json_encode($res); 
                        
}
else{
        // Constructing the response array
                        $response = array(
                            "data" => array(
                                "canDirectToGame" => false,
                                "userRechargeTimes" => 0,
                                "allowNoRechargeGame" => "0",
                                "userRechargeAmount" => 0.0,
                                "lowestRechargeAmountToGame" => "200"
                            ),
                            "code" => 0,
                            "msg" => "Succeed",
                            "msgCode" => 0,
                            "serviceNowTime" => $shnunc
                        );
                          echo json_encode($response); 
}
                      
                    } else {
                        // No operation permission if user doesn't exist
                        $res['code'] = 4;
                        $res['msg'] = 'No operation permission';
                        $res['msgCode'] = 2;
                        http_response_code(401);
                        echo json_encode($res);
                    }
                } else {
                    // Invalid JWT token
                    $res['code'] = 4;
                    $res['msg'] = 'No operation permission';
                    $res['msgCode'] = 2;
                    http_response_code(401);
                    echo json_encode($res);
                }
            } else {
                // Invalid signature
                $res['code'] = 5;
                $res['msg'] = 'Wrong signature';
                $res['msgCode'] = 3;
                http_response_code(200);
                echo json_encode($res);
            }
        } else {
            // Missing parameters in the request body
            $res['code'] = 7;
            $res['msg'] = 'Param is Invalid';
            $res['msgCode'] = 6;
            http_response_code(200);
            echo json_encode($res);
        }
    } else {
        // Method not allowed (for GET requests)
        http_response_code(405);
        echo json_encode($res);
    }
?>
