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

function aes256Encrypt($secret, $requestData) {
    // Append the client secret to the request data
    $requestData['client_secret'] = $secret;
    
    $url = 'https://playwin6.com/encryptedNow';

    // Build the full URL with query string
    $fullUrl = $url . '?' . http_build_query($requestData);
    
    // Initialize cURL
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $fullUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

    // Optional: Set timeout and SSL verify if needed
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Set to false if testing locally

    // Execute cURL request
    $response = curl_exec($ch);

    // Error handling
    if (curl_errno($ch)) {
        $error = 'Curl error: ' . curl_error($ch);
        curl_close($ch); // Close before returning
        return $error;
    }

    // Close cURL and return response
    curl_close($ch);
    return $response;
}


function launchHomeGame($userId, $walletBalance, $providerId, $token, $secret) {
    try {
        // Validate inputs
        if (!$userId) {
            http_response_code(400);  // Send HTTP 400 Bad Request
            return "Error: Missing user ID.";
        }

        if (!is_numeric($walletBalance) || $walletBalance < 0) {
            $walletBalance = 0;
            //return "Error: Invalid wallet balance.-".$walletBalance."-";
        }

        if (!$providerId) {
            http_response_code(400);  // Send HTTP 400 Bad Request
            return "Error: Missing provider ID.";
        }
        
        if (!$token) {
            http_response_code(500);  // Send HTTP 500 Internal Server Error
            return "Error: Server configuration issue. Missing API token.";
        }

        if (!$secret) {
            http_response_code(500);  // Send HTTP 500 Internal Server Error
            return "Error: Server configuration issue. Missing API secret.";
        }

        // Timestamp (current time in milliseconds)
        $timestamp = time() * 1000;

        // Prepare the request data
        $requestData = [
            "user_id" => $userId,
            "wallet_amount" => $walletBalance,
            "game_uid" => $providerId,
            "token" => $token,
            "timestamp" => $timestamp,
            
        ];

        // Convert the request data to a JSON string
        //$message = json_encode($requestData);

        // Generate the HMAC-SHA-256 hash (encryption part)
        $response = aes256Encrypt($secret, $requestData);

        // Decode JSON response into associative array
        $data = json_decode($response, true);
        
        // Generate the game URL with encoded parameters
        $gameUrl = "https://playwin6.com/launchGame?user_id=" . urlencode($userId) .
                   "&wallet_amount=" . urlencode($walletBalance) .
                   "&game_uid=" . urlencode($providerId) .
                   "&token=" . urlencode($token) . 
                   "&timestamp=" . urlencode($timestamp) .
                   "&payload=" . urlencode($data['encrypted']);

        // Redirect to the game URL
        // header("Location: " . $gameUrl);
        // exit;
        return $gameUrl;
    } catch (Exception $e) {
        // Handle any errors
        error_log("Launch game error: " . $e->getMessage());
        http_response_code(500);  // Send HTTP 500 Internal Server Error
        return "Error: Internal server error.". $e->getMessage();
    }
}

// function launchHomeGame($userId, $walletBalance, $providerId, $token, $secret) {
//     try {
//         // Validate inputs
//         if (!$userId) {
//             http_response_code(400);  // Send HTTP 400 Bad Request
//             echo "Error: Missing user ID.";
//             return;
//         }

//         if (!is_numeric($walletBalance) || $walletBalance < 0) {
//             http_response_code(400);  // Send HTTP 400 Bad Request
//             echo "Error: Invalid wallet balance.";
//             return;
//         }

//         if (!$providerId) {
//             http_response_code(400);  // Send HTTP 400 Bad Request
//             echo "Error: Missing provider ID.";
//             return;
//         }
        
//         if (!$token) {
//             http_response_code(500);  // Send HTTP 500 Internal Server Error
//             echo "Error: Server configuration issue. Missing API token.";
//             return;
//         }

//         if (!$secret) {
//             http_response_code(500);  // Send HTTP 500 Internal Server Error
//             echo "Error: Server configuration issue. Missing API secret.";
//             return;
//         }

//         // Timestamp (current time in milliseconds)
//         $timestamp = time() * 1000;

//         // Prepare the request data
//         $requestData = [
//             "user_id" => $userId,
//             "wallet_amount" => $walletBalance,
//             "game_uid" => $providerId,
//             "token" => $token,
//             "timestamp" => $timestamp
//         ];

//         // Convert the request data to a JSON string
//         $message = json_encode($requestData);

//         // Generate the HMAC-SHA-256 hash (encryption part)
//         $hash = aes256Encrypt($secret, $message);  // Assuming aes256Encrypt is a function you have for encryption
        
//         // Generate the game URL with encoded parameters
//         $gameUrl = "https://playwin6.com/launchGame?user_id=" . urlencode($userId) .
//                   "&wallet_amount=" . urlencode($walletBalance) .
//                   "&game_uid=" . urlencode($providerId) .
//                   "&token=" . urlencode($token) . 
//                   "&timestamp=" . urlencode($timestamp) .
//                   "&payload=" . urlencode($hash);

//         // Redirect to the game URL
//         // header("Location: " . $gameUrl);
//         // exit;
//     return $gameUrl;
//     } catch (Exception $e) {
//         // Handle any errors
//         error_log("Launch game error: " . $e->getMessage());
//         http_response_code(500);  // Send HTTP 500 Internal Server Error
//         echo "Error: Internal server error.";
//     }
// }

// Function for AES256 encryption (example implementation)
// function aes256Encrypt($key, $data) {
//     // Ensure the key length is 32 bytes (256 bits) for AES-256
//     $key = substr(hash('sha256', $key, true), 0, 32);  // Use SHA-256 hash to ensure key is 256 bits

//     // Encrypt the data using AES-256-ECB (no IV)
//     $encryptedData = openssl_encrypt($data, 'aes-256-ecb', $key, OPENSSL_RAW_DATA);

//     // Return the encrypted data in base64 encoding
//     return base64_encode($encryptedData);
// }

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']));
        $vendorCode = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['vendorCode']));
        $gameCode = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['gameCode']));
        $phonetype = htmlspecialchars(mysqli_real_escape_string($conn, $shonupost['phonetype']));

        $shonustr = '{"gameCode":"' . $gameCode . '","language":' . $language . ',"phonetype":' . $phonetype . ',"random":"' . $random . '","vendorCode":' . $vendorCode . '}';
        $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') {
                $sesquery = "SELECT id, mobile FROM shonu_subjects WHERE akshinak = '$author'";
                $sesresult = $conn->query($sesquery);
                $sesnum = mysqli_num_rows($sesresult);
                $row = $sesresult->fetch_assoc();

                $uid = $row['id'] ?? null;
                $no = $row['mobile'] ?? null;
                
                $rechargeQuery = "SELECT motta FROM shonu_kaichila WHERE balakedara = '$uid' LIMIT 1";
                
                $sesresult2 = $conn->query($rechargeQuery);
                $sesnum2 = mysqli_num_rows($sesresult2);
                $row2 = $sesresult2->fetch_assoc();

                $amt = $row2['motta'] ?? null;
                
                // if ($vendorCode == 18) {
                //     $game = "https://apiprovider.codesellr.com/jilicontroller_to_server?gameId=$gameCode&mobile={$uid}&referrerUrl=https://bdgamess.in/jili/jili.php";
                // } elseif ($vendorCode == 23) {
                //     $game = "https://apiprovider.codesellr.com/home/bm69?uid={$no}&serverUrl=https://bdgamess.in/jdb/index.php&gType=0&mType={$gameCode}";
                // } elseif ($vendorCode === 'JILI') {
                //     $game = "https://allapi.7xclub.live/api/delhigame?gameId={$gameCode}&uid={$uid}";
                // } elseif ($vendoeCode === 'OLD') {
                //      $game = "https://apiprovider.codesellr.com/home/posts?iv=58fcfd9edc6bac1c&key=a9475e3d049664c8&uid={$no}&serverUrl=https://bdgamess.in/jdb/index.php&parent=bwininrag&gType=22&mType={$gameCode}";
                // } else {
                    
                    // Example call to the function with parameters
                    $userId = $uid;  // Example user ID
                    $walletBalance = $amt;  // Example wallet balance
                    $providerId = $gameCode;  // Example provider ID
                    $token =  "cf9b9123-a48d-431a-b993-73c7b35fa00f";     // Example API token
                    $secret = "d28328df0b970b520c6ec9066d3d907e";   // Example API secret
                    
                    $game = launchHomeGame($userId, $walletBalance, $providerId, $token, $secret);

                //}

                if ($sesnum === 1) {
                    $data['url'] = $game;
                    $data['returnType'] = 1;
                    $res['data'] = $data;
                    $res['code'] = 0;
                    $res['msg'] = 'Succeed';
                    $res['msgCode'] = 0;
                    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'] = 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 {
    http_response_code(405);
    echo json_encode($res);
    exit;
}
?>
