<?php

// Define access constant for gamesintrigrated.php
define('GAME_LAUNCHER_ACCESS', true);

/*
|--------------------------------------------------------------------------
| PRODUCTION SAFE ERROR SETTINGS
|--------------------------------------------------------------------------
*/
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

/*
|--------------------------------------------------------------------------
| CLEAN OUTPUT BUFFER
|--------------------------------------------------------------------------
*/
if (ob_get_level()) {
    ob_end_clean();
}
ob_start();

include_once "../../conn.php";
include_once "../../functions2.php";

/*==============================================================================
  RESELLER CONFIGURATION
==============================================================================*/

define('RESELLER_API_TOKEN', 'f07400e7433e1cc508907d40449eb3096b8c5badb7efd050af32f15b0a614ce7');
define('RESELLER_SECRET_KEY', 'bb042c840d7f37f68594da63d6776b19541b9aa0a538eea288b53ce55c0e6e58');
define('RESELLER_PREFIX', 'dolobd');

define('VERSE_API_URL', 'https://launch.zynverse.cloud/HuidoVerse.php');

/*
|--------------------------------------------------------------------------
| JSON RESPONSE FUNCTION
|--------------------------------------------------------------------------
*/
function jsonResponse($data, $httpCode = 200)
{
    while (ob_get_level()) {
        ob_end_clean();
    }

    http_response_code($httpCode);

    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, X-API-Key');
    header('Access-Control-Allow-Credentials: true');

    $origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
    header('Access-Control-Allow-Origin: ' . $origin);
    header('Vary: Origin');

    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

/**
 * Centralized transaction logging function
 */
function logGameTransaction(
    $conn,
    $userId,
    $vendorCode,
    $gameCode,
    $gameNameEn,
    $amount,
    $timestamp,
    $hadARGameBalanceBefore = false,
    $existingARGameBalanceBefore = 0
) {

    try {

        if (!$hadARGameBalanceBefore && $amount > 0) {

            $serial = 'TRANS_' . uniqid();

            $insertQuery = "
                INSERT INTO game_moved_in_table
                (userkani, price, serial, remark, shonu)
                VALUES (?, ?, ?, 'Game In', ?)
            ";

            $insertStmt = $conn->prepare($insertQuery);

            if (!$insertStmt) {
                return false;
            }

            $insertStmt->bind_param(
                "sdss",
                $userId,
                $amount,
                $serial,
                $timestamp
            );

            return $insertStmt->execute();
        }

        return true;

    } catch (Exception $e) {
        error_log($e->getMessage());
        return false;
    }
}

/*
|--------------------------------------------------------------------------
| DEFAULT RESPONSE
|--------------------------------------------------------------------------
*/
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,
];

/*
|--------------------------------------------------------------------------
| REQUEST PARSING
|--------------------------------------------------------------------------
*/
$rawBody = file_get_contents("php://input");

$parsedBody = [];

if (!empty($rawBody) && strpos($rawBody, '=') !== false) {
    parse_str($rawBody, $parsedBody);
}

$jsonData = json_decode($rawBody, true);

if (!is_array($jsonData)) {
    $jsonData = [];
}

$request = array_merge($jsonData, $parsedBody, $_POST, $_GET);

/*
|--------------------------------------------------------------------------
| FLEXIBLE PARAM PICKER
|--------------------------------------------------------------------------
*/
function pick_param($source, $names)
{
    foreach ($names as $name) {

        if (isset($source[$name])) {
            return $source[$name];
        }

        foreach ($source as $k => $v) {

            if (strcasecmp($k, $name) === 0) {
                return $v;
            }
        }
    }

    return null;
}

$vendorCodeRaw = pick_param($request, [
    'vendorCode',
    'vendorcode',
    'vendor_code',
    'vendor',
    'vendorId',
    'vendor_id'
]);

$gameCodeRaw = pick_param($request, [
    'gameCode',
    'gamecode',
    'game_code',
    'game',
    'gameId',
    'game_id'
]);

/*
|--------------------------------------------------------------------------
| VALIDATION
|--------------------------------------------------------------------------
*/
if (empty($gameCodeRaw) || $gameCodeRaw === 'null') {

    $res['code'] = 7;
    $res['msg'] = 'Param is Invalid (gameCode missing)';
    $res['msgCode'] = 6;

    jsonResponse($res);
}

if (empty($vendorCodeRaw) || $vendorCodeRaw === 'null') {
    $vendorCodeRaw = 18;
}

/*
|--------------------------------------------------------------------------
| OPTIONAL PARAMS
|--------------------------------------------------------------------------
*/
$languageRaw   = $request['language'] ?? 0;
$gameNameEnRaw = $request['gameNameEn'] ?? '';
$phonetypeRaw  = $request['phonetype'] ?? 0;

/*
|--------------------------------------------------------------------------
| SAFE VALUES
|--------------------------------------------------------------------------
*/
$vendorCode = mysqli_real_escape_string($conn, (string)$vendorCodeRaw);
$gameCode   = mysqli_real_escape_string($conn, (string)$gameCodeRaw);
$gameNameEn = mysqli_real_escape_string($conn, (string)$gameNameEnRaw);

/*
|--------------------------------------------------------------------------
| JWT VALIDATION
|--------------------------------------------------------------------------
*/
if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {

    $res['code'] = 4;
    $res['msg'] = 'No operation permission';
    $res['msgCode'] = 2;

    jsonResponse($res, 401);
}

$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') {

    $res['code'] = 4;
    $res['msg'] = 'No operation permission';
    $res['msgCode'] = 2;

    jsonResponse($res, 401);
}

$user_id = $data_auth['payload']['id'];

/*
|--------------------------------------------------------------------------
| USER CHECK
|--------------------------------------------------------------------------
*/
$sesquery = "
    SELECT id
    FROM shonu_subjects
    WHERE id = ?
";

$sesstmt = $conn->prepare($sesquery);

if (!$sesstmt) {

    $res['code'] = 4;
    $res['msg'] = 'Database error';
    $res['msgCode'] = 2;

    jsonResponse($res, 500);
}

$sesstmt->bind_param("s", $user_id);

$sesstmt->execute();

$sesresult = $sesstmt->get_result();

if ($sesresult->num_rows != 1) {

    $res['code'] = 4;
    $res['msg'] = 'User not found';
    $res['msgCode'] = 2;

    jsonResponse($res, 401);
}

/*
|--------------------------------------------------------------------------
| MAIN WALLET
|--------------------------------------------------------------------------
*/
$stmtMain = $conn->prepare("
    SELECT motta
    FROM shonu_kaichila
    WHERE balakedara = ?
");

$stmtMain->bind_param("s", $user_id);

$stmtMain->execute();

$stmtMain->bind_result($motta);

$mainBalance = 0;

if ($stmtMain->fetch()) {
    $mainBalance = floatval($motta);
}

$stmtMain->close();

/*
|--------------------------------------------------------------------------
| ARGAME TABLE CREATE
|--------------------------------------------------------------------------
*/
$conn->query("
CREATE TABLE IF NOT EXISTS argame_balances (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id VARCHAR(255) NOT NULL,
    balance DECIMAL(15,2) DEFAULT 0.00,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

/*
|--------------------------------------------------------------------------
| ARGAME BALANCE
|--------------------------------------------------------------------------
*/
$checkStmt = $conn->prepare("
    SELECT balance
    FROM argame_balances
    WHERE user_id = ?
");

$checkStmt->bind_param("s", $user_id);

$checkStmt->execute();

$checkStmt->store_result();

$hadARGameBalanceBefore = false;
$existingARGameBalance = 0;
$finalBalance = $mainBalance;

if ($checkStmt->num_rows > 0) {

    $hadARGameBalanceBefore = true;

    $checkStmt->bind_result($balance);

    $checkStmt->fetch();

    $existingARGameBalance = floatval($balance);

    $finalBalance = $existingARGameBalance + $mainBalance;

    $updateStmt = $conn->prepare("
        UPDATE argame_balances
        SET balance = ?, updated_at = NOW()
        WHERE user_id = ?
    ");

    $updateStmt->bind_param("ds", $finalBalance, $user_id);

    $updateStmt->execute();

    $updateStmt->close();

} else {

    $insertStmt = $conn->prepare("
        INSERT INTO argame_balances
        (user_id, balance, updated_at)
        VALUES (?, ?, NOW())
    ");

    $insertStmt->bind_param(
        "sd",
        $user_id,
        $mainBalance
    );

    $insertStmt->execute();

    $insertStmt->close();
}

$checkStmt->close();

/*
|--------------------------------------------------------------------------
| MAIN WALLET ZERO
|--------------------------------------------------------------------------
*/
if ($mainBalance > 0) {

    $updateMainWallet = $conn->prepare("
        UPDATE shonu_kaichila
        SET motta = 0
        WHERE balakedara = ?
    ");

    $updateMainWallet->bind_param("s", $user_id);

    $updateMainWallet->execute();

    $updateMainWallet->close();
}

/*
|--------------------------------------------------------------------------
| LOG TRANSACTION
|--------------------------------------------------------------------------
*/
if (!$hadARGameBalanceBefore && $mainBalance > 0) {

    logGameTransaction(
        $conn,
        $user_id,
        $vendorCode,
        $gameCode,
        $gameNameEn,
        $mainBalance,
        $shnunc,
        $hadARGameBalanceBefore,
        $existingARGameBalance
    );
}

/*
|--------------------------------------------------------------------------
| API CALL
|--------------------------------------------------------------------------
*/
$api_payload = [
    'userId'      => $user_id,
    'gameCode'    => $gameCodeRaw,
    'vendorCode'  => $vendorCodeRaw,
    'userBalance' => $finalBalance,
    'language'    => $languageRaw,
    'phonetype'   => $phonetypeRaw,
    'returnUrl'   => 'https://dclottery.ink'
];

$ch = curl_init(VERSE_API_URL);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($api_payload));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-API-Token: ' . RESELLER_API_TOKEN,
    'X-Secret-Key: ' . RESELLER_SECRET_KEY
]);

curl_setopt($ch, CURLOPT_TIMEOUT, 30);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

$api_response = curl_exec($ch);

$api_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$curl_error = curl_error($ch);

curl_close($ch);

/*
|--------------------------------------------------------------------------
| API RESPONSE
|--------------------------------------------------------------------------
*/
if ($curl_error) {

    $res['code'] = 8;
    $res['msg'] = 'Failed to connect to game provider';
    $res['msgCode'] = 8;

    jsonResponse($res);
}

$api_result = json_decode($api_response, true);

if (
    $api_result &&
    isset($api_result['code']) &&
    $api_result['code'] === 0
) {

    $res['code'] = 0;

    $res['msg'] = 'Game launched successfully';

    $res['msgCode'] = 12;

    $res['data'] = [
        'url' => $api_result['data']['url'] ?? '',
        'returnType' => 'game_url'
    ];

} else {

    $res['code'] = 8;

    $res['msg'] = $api_result['msg']
        ?? 'Failed to launch game';

    $res['msgCode'] = 8;

    $res['httpCode'] = $api_http_code;
}

/*
|--------------------------------------------------------------------------
| FINAL CLEAN JSON OUTPUT
|--------------------------------------------------------------------------
*/
jsonResponse($res);