<?php
include "../../conn.php";
include "../../functions2.php";
include "apifiles/apibaseurl.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,
];

$alter = "
  ALTER TABLE shonu_kaichila 
    ADD COLUMN IF NOT EXISTS wll_jili DECIMAL(10,2) DEFAULT 0,
    ADD COLUMN IF NOT EXISTS wll_jdb DECIMAL(10,2) DEFAULT 0;
";
mysqli_query($conn, $alter);


function generateUrl(string $fileName): string {
    $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off')
             || ($_SERVER['SERVER_PORT'] ?? '') == 443;
    $scheme   = $isHttps ? 'https://' : 'http://';
    $host     = $_SERVER['HTTP_HOST'];
    $basePath = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
    return $scheme
         . $host
         . ($basePath !== '/' ? $basePath : '')
         . '/'
         . ltrim($fileName, '/');
}

// 1. Callback URLs
$jili      = generateUrl('apifiles/jili.php');
$jdb       = generateUrl('apifiles/jdbpro.php');
$spribe    = generateUrl('apifiles/jdbpro.php');
$aio       = generateUrl('apifiles/aio.php');
$evoslots  = generateUrl('apifiles/evoslots.php');
$evo       = generateUrl('apifiles/evo.php');
$cq9       = generateUrl('apifiles/cq9.php');
$mt        = generateUrl('apifiles/mt.php');
$bal       = generateUrl('apifiles/balance.php');
$chicken   = generateUrl('apifiles/inout.php');
$ninesgame  = generateUrl('apifiles/ninesgame.php');

// 2. Ensure wallet columns exist (once)
mysqli_query($conn, "
  ALTER TABLE shonu_kaichila 
    ADD COLUMN IF NOT EXISTS wll_jili DECIMAL(10,2) DEFAULT 0,
    ADD COLUMN IF NOT EXISTS wll_jdb DECIMAL(10,2) DEFAULT 0;
");

// 3. Helper: follow redirects, return final URL
function fetchEffectiveUrl(string $url): string {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 1,
    ]);
    curl_exec($ch);
    $final = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    return $final;
}

// 4. Vendor configuration
$vendors = [
    18               => ['ep'=>'jili','pre'=>'','upd'=>"wll_jili=wll_jdb+wll_jili+motta,motta=0,wll_jdb=0"],
    'JILI'           => ['ep'=>'jili','pre'=>'','upd'=>"wll_jili=wll_jdb+wll_jili+motta,motta=0,wll_jdb=0"],
    23               => ['ep'=>'jdb','pre'=>'0_','upd'=>null],
    'JDB'            => ['ep'=>'jdb','pre'=>'0_','upd'=>null],
    'SPRIBE'         => ['ep'=>'spribe','pre'=>'22_','upd'=>null],
    'AIO'            => ['ep'=>'aio','pre'=>'22_','upd'=>null],
    'EVO_Electronic' => ['ep'=>'evoslots','pre'=>'','upd'=>null],
    'EVO_Video'      => ['ep'=>'evo','pre'=>'','upd'=>null],
    'CQ9'            => ['ep'=>'cq9','pre'=>'','upd'=>null],
    'MT'             => ['ep'=>'cq9','pre'=>'','upd'=>null],
    'G9'             => ['ep'=>'ninesgame','pre'=>'','upd'=>null],
];

$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']));
        $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;
                
                // Fetch kramasankhye for this user
$stmt = $conn->prepare("SELECT kramasankhye FROM shonu_kaichila WHERE balakedara = ?");
$stmt->bind_param("i", $uid);
$stmt->execute();
$stmt->bind_result($kramasankhye);
$stmt->fetch();
$stmt->close();
                
                
// 5. Balance refresh & game launch
if (isset($vendors[$vendorCode])) {
    $c = $vendors[$vendorCode];
    // refresh user balance (you can log $gameUrl if needed)
    $gameUrl = fetchEffectiveUrl("{$bal}?user={$uid}");

    // apply wallet-rollup if needed
    if ($c['upd']) {
        $sql = sprintf(
          "UPDATE shonu_kaichila 
             SET %s
           WHERE balakedara='%s'",
          $c['upd'],
          mysqli_real_escape_string($conn, $uid)
        );
        mysqli_query($conn, $sql);
    }

    // build and fetch the game launch URL
    $endpoint = $c['ep'];
    $prefix   = $c['pre'];
    $callback = ${strtolower($endpoint)};  // e.g. $jili, $jdb, etc.
    $game     = fetchEffectiveUrl(
        "{$apibaseurl}{$endpoint}"
        . "?userid={$uid}"
        . "&gameid={$prefix}{$gameCode}"
        . "&callbackurl={$callback}"
    );
} else {
     $gameUrl = fetchEffectiveUrl("{$bal}?user={$uid}");
    $game = "{$apibaseurl}inout?userid=$kramasankhye&gameid=$gameCode&callbackurl=$chicken";
}

                

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