<?php 
	include "../../conn.php";
	include "../../functions2.php";
	include "apifiles/apibaseurl.php";
	
	// ──────────────── CORS & Headers ────────────────
	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 = $_SERVER['HTTP_ORIGIN'] ?? '';
	header('Access-Control-Allow-Origin: ' . $origin);
	header('Vary: Origin');
	
	// ──────────────── Timestamp & 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,
	];

	// ─────────────── Decode input for GET or POST ───────────────
	$method    = $_SERVER['REQUEST_METHOD'];
	if ($method === 'GET') {
	    $shonupost = $_GET;
	} else {
	    $shonubody = file_get_contents("php://input");
	    $shonupost = json_decode($shonubody, true) ?: [];
	}

	// ─────────────── URL Generator ───────────────
	function generateUrl($fileName) {
	    $protocol = "https://";
	    $host     = $_SERVER['HTTP_HOST'];
	    $uri      = $_SERVER['REQUEST_URI'];
	    $parts    = explode("/", trim($uri, "/"));
	    array_pop($parts);
	    return $protocol . $host . "/" . implode("/", $parts) . "/" . $fileName;
	}
	$jili     = generateUrl("apifiles/jili.php");
	$jdb      = generateUrl("apifiles/jdb.php");
	$jdbpro   = 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');
	$ninesgame  = generateUrl('apifiles/ninesgame.php');

	// ─────────────── Simple HTTP GET via cURL ───────────────
	function http_get($url) {
	    $ch = curl_init($url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
	    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	    $resp = curl_exec($ch);
	    curl_close($ch);
	    return $resp ?: '';
	}

	// ─────────────── Always attempt to process if params present ───────────────
	if (
	    isset($shonupost['language'], $shonupost['random'], $shonupost['signature'], $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] ?? '';
			$jwt_response = is_jwt_valid($author);
			$data_auth    = json_decode($jwt_response, true);

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

				if ($sesresult && $sesresult->num_rows === 1) {
					// ensure columns exist
					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"
					);

					// fetch stored balances
					$uid       = (int)$data_auth['payload']['id'];
					$balquery  = "SELECT motta, wll_jdb, wll_jili
								  FROM shonu_kaichila
								  WHERE balakedara = $uid";
					$balresult = $conn->query($balquery);
					$balarr    = $balresult ? $balresult->fetch_assoc() : ['motta'=>0,'wll_jdb'=>0,'wll_jili'=>0];

					// CQ9 balance
					$cq9_url  = "{$apibaseurl}cq9?action=balance"
					          . "&userid={$uid}"
					          . "&callbackurl=" . urlencode($cq9)
					          . "&accessKey=allow";
					$cq9_data = json_decode(http_get($cq9_url), true) ?: [];
					$xd_cq9   = isset($cq9_data['balance']) ? (int)$cq9_data['balance'] : 0;

					// EVO (EDB) balance
					$evo_url   = "{$apibaseurl}evo?action=balance&userid={$uid}";
					$evo_data  = json_decode(http_get($evo_url), true) ?: [];
					$edbBalance= (!empty($evo_data['success']) ? floatval($evo_data['balance']) : 0);

					// AIO balance
					$aio_url   = "{$apibaseurl}aio?action=balance"
					          . "&callbackurl=" . urlencode($aio)
					          . "&userid={$uid}";
					$aio_data  = json_decode(http_get($aio_url), true) ?: [];
					$AIOBalance= (!empty($aio_data['success']) ? floatval($aio_data['balance']) : 0);

					// Spribe balance
					$spr_url    = "{$apibaseurl}spribe?action=balance"
					           . "&callbackurl=" . urlencode($jdbpro)
					           . "&userid={$uid}";
					$spr_data   = json_decode(http_get($spr_url), true) ?: [];
					$spribebal  = (!empty($spr_data['success']) ? floatval($spr_data['balance']) : 0);
					
					

					// EVO Slots balance
					$slot_url   = "{$apibaseurl}evoslots?action=balance"
					           . "&callbackurl=" . urlencode($evoslots)
					           . "&userid={$uid}";
					$slot_data  = json_decode(http_get($slot_url), true) ?: [];
					$slotBal    = (!empty($slot_data['success']) ? floatval($slot_data['balance']) : 0);
					
					
					
					
					
					
					$ninesgame_url = "{$apibaseurl}ninesgame?action=balance&userid={$uid}";
					$resp = trim(file_get_contents($ninesgame_url));
					$ninesgameBal = is_numeric($resp) ? (float)$resp : 0;

					
					
					
						// All balance
					$spr_url    = "{$bal}?user={$uid}";
					$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $spr_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_IPRESOLVE      => CURL_IPRESOLVE_V4,  // force IPv4 (important)
    CURLOPT_USERAGENT      => "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
]);

$response = curl_exec($ch);
$curl_error = curl_error($ch);
$http_code  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($curl_error || $http_code != 200) {
    // Something blocked the request
    $spribebalwith = 0;
} else {
    $spr_data = json_decode($response, true) ?: [];
    $spribebalwith = (!empty($spr_data['success']) ? floatval($spr_data['balance']) : 0);
}

					
					
					

					// assemble list
					$list = [];
					$list[] = ['vendorCode'=>'Lottery',    'balance'=> (int)$balarr['motta']];
					$list[] = ['vendorCode'=>'TB_Chess',   'balance'=> $AIOBalance];
					$list[] = ['vendorCode'=>'Wickets9',   'balance'=> 0];
					$list[] = ['vendorCode'=>'CQ9',        'balance'=> $xd_cq9];
					$list[] = ['vendorCode'=>'MG',         'balance'=> 0];
					$list[] = ['vendorCode'=>'JDB',        'balance'=> $spribebal];
					$list[] = ['vendorCode'=>'DG',         'balance'=> $ninesgameBal];
					$list[] = ['vendorCode'=>'CMD',        'balance'=> 0];
					$list[] = ['vendorCode'=>'SaBa',       'balance'=> 0];
					$list[] = ['vendorCode'=>'EVO_Video',  'balance'=> $edbBalance];
					$list[] = ['vendorCode'=>'JILI',       'balance'=> (int)$balarr['wll_jili']];
					$list[] = ['vendorCode'=>'Card365',    'balance'=> 0];
					$list[] = ['vendorCode'=>'V8Card',     'balance'=> 0];
					$list[] = ['vendorCode'=>'AG_Video',   'balance'=> 0];
					$list[] = ['vendorCode'=>'PG',         'balance'=> 0];
					$list[] = ['vendorCode'=>'TB',         'balance'=> 0];
					$list[] = ['vendorCode'=>'WM_Video',   'balance'=> 0];
					$list[] = ['vendorCode'=>'SEXY_Video', 'balance'=> 0];
					$list[] = ['vendorCode'=>'EVO_Slots',  'balance'=> $slotBal];

					$data = [
						'thidGameBalanceList' => $list,
						'totalWithdraw'       => 0,
						'totalRecharge'       => 0
					];

					$res = [
						'code'            => 0,
						'msg'             => 'Succeed',
						'msgCode'         => 0,
						'serviceNowTime'  => $shnunc,
						'data'            => $data
					];
					http_response_code(200);
					echo json_encode($res);
					exit;
				}
				// session row missing
				http_response_code(401);
				$res['code']    = 4;
				$res['msg']     = 'No operation permission';
				$res['msgCode']= 2;
				echo json_encode($res);
				exit;
			}
			// invalid JWT
			http_response_code(401);
			$res['code']    = 4;
			$res['msg']     = 'No operation permission';
			$res['msgCode']= 2;
			echo json_encode($res);
			exit;
		}
		// wrong signature
		http_response_code(200);
		$res['code']    = 5;
		$res['msg']     = 'Wrong signature';
		$res['msgCode']= 3;
		echo json_encode($res);
		exit;
	}

	// missing params
	http_response_code(200);
	$res['code']    = 7;
	$res['msg']     = 'Param is Invalid';
	$res['msgCode']= 6;
	echo json_encode($res);
