<?php 
use CodeIgniter\HTTP\Request;
use App\Models\CommonModel;

	// get site information
	function site_info($KeyValue) {
		$CI = db_connect();
		$builder = $CI->table('site_controls');
		$builder->where('settings_name', 'site');
		$builder->where('site_key', $KeyValue);
		$query=$builder->get();
		$site_data = $query->getRow();
		if($site_data)
		return $site_data->site_value;
	}
	
		function getDecimalDigits($number) {
    // Convert the number to a string
    $number_str = (string)$number;

    // Check if there is a decimal point
    if (strpos($number_str, '.') !== false) {
        // Get the part after the decimal point
        $decimal_part = explode('.', $number_str)[1];

        // Return the number of digits after the decimal point
        return strlen($decimal_part);
    } else {
        // Return 0 if no decimal part exists
        return 0;
    }
}


	function curbalance_old($KeyValue,$currency)
	{
		$CI =db_connect();
		$builder = $CI->table('coin_info');
		$condition="coid ='$currency'";
		$builder->where ($condition);
		$query=$builder->get();
		$coin_data = $query->getRow();		

		if($coin_data)
			$coin_decimal=$coin_data->coin_decimal;
		else
			$coin_decimal='2';

		$condition="type In('deposit','bonus','commissions','interest','return_principal') and uusersid='$KeyValue' and currency='$currency'";
		$builder = $CI->table('history');
		$builder->where($condition);
		$builder->selectSum('amount');
		$query=$builder->get();
		$site_data = $query->getRow();
		if($site_data)
			 $deposit =  $site_data->amount;




		$condition="type In('interest','return_principal','trade_profit') and uusersid='$KeyValue' and currency='$currency'";
		$CI->db = $CI->table('history');
		$CI->db->where ($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$arbit_bal = $query->getRow();
		if($arbit_bal)
			 $arbit_bal = $arbit_bal->amount;

		
		

		$condition="type In('penalty','withdrawal','withdraw_request','withdraw_fee','transfer_fee') and uusersid='$KeyValue' and currency='$currency'";
		$CI->db = $CI->table('history');
		$CI->db->where ($condition);
		$CI->db->selectSum('amount');
		$querys=$CI->db->get();
		$site_datas = $querys->getRow();
		if($site_datas)
			 $withdraw =$site_datas->amount;

		

		/*sub*/
		$condition="type In('1','3') and userid='$KeyValue' and status!='4' and market_type='$currency' and exchange_mode='0'";	
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data2= $query->getRow();
		if($site_data2)
			 $buyamt =  $site_data2->total;


		/*buyback ded*/
		$condition="type In('1') and userid='$KeyValue' and status='1' and market_type='$currency' and exchange_mode='1'";	
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data2= $query->getRow();
		if($site_data2)
			 $buypamt =  $site_data2->total;




		/*add */
		$condition="type In('1') and rec_user='$KeyValue' and status='3' and market_type='$currency' and exchange_mode='0'";	
		
		$CI->db = $CI->table('exchange');
		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data3= $query->getRow();

		if($site_data3)
			 $buyamt1 =  $site_data3->total;

	


		/*add*/
		$condition="type In('1') and userid='$KeyValue' and status='3' and pair='$currency' and exchange_mode='0'";	
		$CI->db = $CI->table('exchange');
		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data4= $query->getRow();
		

		if($site_data4)
			 $buyamt2 =  $site_data4->amount;



		/*sub*/
		$condition="type In('2') and userid='$KeyValue' and status!='4' and pair='$currency' and exchange_mode='0'";	
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
	
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data5= $query->getRow();
		if($site_data5)
			 $buyamt3 =  $site_data5->amount;




		/*sub*/
		$condition="type In('2') and rec_user='$KeyValue' and status='3' and market_type='$currency' and exchange_mode='0'";	
		$CI->db = $CI->table('exchange');
		
		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data6= $query->getRow();

		if($site_data6)
			 $buyamt4 =  $site_data6->total;

		/*sub*/

		$condition="status = '1' and uusersid='$KeyValue' and coin_id='$currency'";	
		$CI->db = $CI->table('arbit_fund');
		
		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$arbit= $query->getRow();

		if($arbit)
			 $arbit_val =  $arbit->amount;
		
		/*add*/
		$condition="type In('2') and rec_user='$KeyValue' and status='3' and pair='$currency'";
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data7= $query->getRow();
		if($site_data7)
			 $buyamt5 =  $site_data7->amount;





		$condition="userid = '$KeyValue' and status='3' and pair='$currency'";	
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		$CI->db->selectSum('ret_amt');
		$query=$CI->db->get();
		$site_data7= $query->getRow();
		if($site_data7)
			 $buybamt =  $site_data7->amount;

		$condition="userid = '$KeyValue' and status='3' and pair='$currency' and type!='4'";
		$CI->db = $CI->table('exchange');	
		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_databuy= $query->getRow();
		if($site_data7)
			 $buybamtbuy =  $site_databuy->amount;

		


			/*sub*/
		$condition="usersid = '$KeyValue' and status='1' and currency='$currency'";	
		$CI->db = $CI->table('trade_history');

		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data7= $query->getRow();
		if($site_data7)
		$buycrpt =  $site_data7->amount;


		$condition="userid = '$KeyValue' and status='3' and market_type='$currency' and type='4'";	
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_databuysell= $query->getRow();
		if($site_data7)
			 $buybamtsell =  $site_databuysell->total;

		//echo $buybamtsell;

		$condition="userid = '$KeyValue' and currency='$currency' and type='4'";	
		$CI->db->where($condition);
		$CI->db = $CI->table('exchange');
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_databuysell1= $query->getRow();
		if($site_data7)
			
			$sell_data =  $site_databuysell1->amount;

		$condition="userid = '$KeyValue'  and currency='$currency' and exchange_mode='1'";	
		$CI->db = $CI->table('exchange');
		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_databuy= $query->getRow();
		if($site_data7)
			 $buybackamtbuy =  $site_databuy->total;

		$condition="rec_user = '$KeyValue'  and status='3' and currency='$currency' ";	
		$CI->db = $CI->table('exchange');
		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_databuy= $query->getRow();
		if($site_data7)
			 $tradecopy =  $site_databuy->amount;


		$bal=$deposit+$buyamt2+$buyamt5+$buybamt+$buybamtbuy+$buybamtsell+$tradecopy -($withdraw+$buyamt+$buyamt3+$buyamt4+$buyamt1+$arbit_val+$buypamt+$buycrpt+$sell_data+$buybackamtbuy);
		
		if($bal< 0)
			$bal=0;

		$bal=number_format($bal,$coin_decimal);

		return $bal;

	}

	function curprofit($userid){
        $CI =db_connect();
		$profit = $CI->query("SELECT SUM(amount) AS amount FROM `history` WHERE `type` IN ('trade_profit','trade_bonus') AND uusersid = '".$userid."'")->getRow()->amount;

		//$profit1 = $CI->query("SELECT SUM(avg_price) AS profit2 FROM `api_trade_history` WHERE  uuserid = '".$userid."'")->getRow()->profit2;

		$trade_profit1 = $CI->query("SELECT SUM(avg_price) AS amount FROM `api_trade_history` WHERE  uuserid = '".$userid."'")->getRow()->amount;



       $trade_profit = $profit + $trade_profit1;
       

		return $trade_profit;
	}
	
	function todayearn($userid){
        $CI =db_connect();
        $date=date("Y-m-d");
	
		$profit = $CI->query("SELECT SUM(amount) AS amount FROM `history` WHERE `type` IN ('trade_profit','commissions') and date like '%$date%' AND uusersid = '".$userid."'")->getRow()->amount;

		
		$trade_profit = $CI->query("SELECT SUM(avg_price) AS amount FROM `api_trade_history` WHERE  date like '%$date%' and uuserid = '".$userid."'")->getRow()->amount;

		
		//$profit1 = $CI->query("SELECT SUM(avg_price) AS profit1 FROM `api_trade_history` WHERE date like '%$date%' AND uuserid = '".$userid."'")->getRow()->profit1;

		$today_profit = $profit + $trade_profit;

		return $today_profit;


	}
	
	function gas_wallet_bal($userid)
	{
		$CI =db_connect();
		$gas_wallet = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('transfer_gaswallet') and payment_id ='0'")->getRow()->amount;
		$deduct_wallet = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('deducted_gaswallet') and payment_id ='0'")->getRow()->amount;
		
		$balance=$gas_wallet-$deduct_wallet;
		if($balance < 0)
		    $balance=0;
        return $balance;
		
	}

	function curbalance($userid)
	{
		$CI =db_connect();
		
		$profit = $CI->query("SELECT SUM(amount) AS amount FROM `history` WHERE `type` IN('deposit','bonus','fund_received','commissions','circle_profit','withdrawal_pool') AND uusersid = '".$userid."'")->getRow()->amount;
	
		$profit_release = 0;
         
	    $withdraw = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('withdrawal','withdraw_request','withdraw_fee','transfer','release_deposit','transfer_fee','penalty','circle_deduct','pool_invest','pool_invest_fee','activation','rank_activation','transfer_gaswallet') and payment_id ='0'")->getRow()->amount;
	    
	  	$withdraw_get = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('withdrawal','withdraw_request','withdraw_fee','transfer','release_deposit','transfer_fee','penalty','circle_deduct','pool_invest','pool_invest_fee','activation','rank_activation','transfer_gaswallet') and payment_id ='9'")->getRow()->amount;

		$withdraw_get1 = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('withdrawal','withdraw_fee','withdraw_request','activation','rank_activation','transfer_gaswallet') and payment_id ='15'")->getRow()->amount;

		//$trade_profit = $CI->query("SELECT SUM(avg_price) AS amount FROM `api_trade_history` WHERE  uuserid = '".$userid."'")->getRow()->amount;
        $trade_profit='0';
		

		$balance = $profit_release + $profit+$trade_profit - ($withdraw + $withdraw_get + $withdraw_get1);
		
		

		/*echo $profit;
		echo "<br>";

		echo $withdraw;
		echo "<br>";

		echo $withdraw_get;
		echo "<br>";*/
		
		if($balance > 0)
		{
		   return number_format($balance,2);
		}
		else
		{
		   return number_format(0,2);
		}
		
	}



	function curbalancetoday($userid){
		$CI =db_connect();
		$curdate = date('Y-m-d');
		$profit = $CI->query("SELECT SUM(amount) AS amount FROM `history` WHERE `type` IN('deposit','bonus','fund_received','commissions') AND `date` LIKE '%$curdate%' AND uusersid = '".$userid."'")->getRow()->amount;
		$withdraw = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and `date` LIKE '%$curdate%' and type IN('withdrawal','withdraw_fee','transfer','fuel','release_deposit','transfer_fee','penalty','transfer_gaswallet') ")->getRow()->amount;
		
		$trade_profit = $CI->query("SELECT SUM(avg_price) AS amount FROM `api_trade_history` WHERE  uuserid = '".$userid."'")->getRow()->amount;

		$balance = $profit - $withdraw + $trade_profit;
		if ($balance < 0) {
			$balance = '0.00';
		}
		return number_format($balance,2);
	}

	
	function balance($KeyValue,$currency)
	{
		$CI =& get_instance();

		$condition="coid ='$currency'";
		$CI->db->where($condition);
		$query=$CI->db->get('coin_info');
		$coin_data = $query->row();		

		if($coin_data)
			$coin_decimal=$coin_data->coin_decimal;
		else
			$coin_decimal='2';

	$condition="type In('deposit','bonus','commissions','interest','return_principal') and uusersid='$KeyValue' and currency='$currency'";
		$CI->db->where ($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get('history');
		$site_data = $query->row();
		if($site_data)
			 $deposit =  $site_data->amount;		

		$condition="type In('penalty','withdrawal','withdraw_fee','transfer_fee') and uusersid='$KeyValue' and currency='$currency'";
		$CI->db->where ($condition);
		$CI->db->selectSum('amount');
		$querys=$CI->db->get('history');
		$site_datas = $querys->row();
		if($site_datas)
			 $withdraw =$site_datas->amount;

		
		$bal=$deposit-$withdraw;
		

		if($bal< 0)
			$bal=0;

		$bal=number_format($bal,$coin_decimal);

		return $bal;

	}


	function order($KeyValue,$currency)
	{

		$CI =db_connect();
		$CI->db = $CI->table('coin_info');

		$condition="coid ='$currency'";
		$CI->db->where ($condition);
		$query=$CI->db->get();
		$coin_data = $query->getRow();		

		if($coin_data)
			$coin_decimal=$coin_data->coin_decimal;
		else
			$coin_decimal='2';

	
		/*sub*/
		$condition="type In('1','3') and userid='$KeyValue' and status!='4' and market_type='$currency'";	
		$CI->db = $CI->table('exchange');
		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data2= $query->getRow();

		
		if($site_data2)
			 $buyamt =  $site_data2->total;


		


		/*add */
		$CI->db = $CI->table('exchange');
		$condition="type In('1') and rec_user='$KeyValue' and status='3' and pair='$currency'";	
		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data3= $query->getRow();
		if($site_data3)
			 $buyamt1 =  $site_data3->total;




		/*add*/
		$condition="type In('1') and userid='$KeyValue' and status='3' and pair='$currency'";
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data4= $query->getRow();
		if($site_data4)
			 $buyamt2 =  $site_data4->amount;




		/*sub*/
		$condition="type In('4') and userid='$KeyValue' and status!='4' and pair='$currency'";
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data5= $query->getRow();
		if($site_data5)
			 $buyamt3 =  $site_data5->amount;



		/*sub*/
		$condition="type In('4') and rec_user='$KeyValue' and status='3' and market_type='$currency'";	
		$CI->db = $CI->table('exchange');

		$CI->db->where($condition);
		$CI->db->selectSum('total');
		$query=$CI->db->get();
		$site_data6= $query->getRow();
		if($site_data6)
			 $buyamt4 =  $site_data6->total;

		/*add*/
		$CI->db = $CI->table('exchange');
		$condition="type In('4') and rec_user='$KeyValue' and status='3' and pair='$currency'";	
		$CI->db->where($condition);
		$CI->db->selectSum('amount');
		$query=$CI->db->get();
		$site_data7= $query->getRow();
		if($site_data7)
			 $buyamt5 =  $site_data7->amount;



		$bal=$buyamt1+$buyamt2+$buyamt5 -($buyamt+$buyamt3+$buyamt4);
		

		if($bal< 0)
			$bal=0;

		$bal=number_format($bal,$coin_decimal);

		return $bal;

	}


	function arbit_ded($KeyValue,$currency)
	{

		$CI =& get_instance();

		$condition="status IN('2')";
		$CI->db->where ($condition);
		
		$CI->db->where('uusersid',$KeyValue);
		$CI->db->where('coin_id',$currency);
		$CI->db->selectSum('amount');
		$query=$CI->db->get('arbit_fund');
		$site_data = $query->row();
		if($site_data)
		 $deposit =  $site_data->amount;

		if($deposit=='')
			$deposit=0;

		return $deposit;
		


	}
	

	function binance_balance($apiKey,$apiSecret)
	{
	    $balance=0;
	    // Binance API endpoint
        $endpoint = 'https://api-gcp.binance.com/api/v3/account';
        
        // Generate a timestamp
        $timestamp = round(microtime(true) * 1000);
        
        // Create a query string
        $queryString = "timestamp={$timestamp}";
        
        // Create a signature
        $signature = hash_hmac('sha256', $queryString, $apiSecret);
        
        // Add the signature to the query string
        $queryString .= "&signature={$signature}";
        
        // Create headers
        $headers = [
            "X-MBX-APIKEY: {$apiKey}"
        ];
        
        // Initialize curl
        $ch = curl_init();
        
        // Set curl options
        curl_setopt($ch, CURLOPT_URL, "{$endpoint}?{$queryString}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Execute curl request
        $response = curl_exec($ch);
        
        // Check for curl errors
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
            exit;
        }
        
        // Close curl
        curl_close($ch);
        
        // Decode the JSON response
        $balance=0;
        $data = json_decode($response, true);
        if(!empty($data['balances']))
        {
        foreach ($data['balances'] as $asset) 
        {
            if ($asset['asset'] == 'USDT') 
            {
                $balance=$asset['free'];
                
            }
        }
        }
        
        return $balance;
	    
	}
	
	function binance_balance1($apiKey,$apiSecret,$pair)
	{
	    $balance=0;
	    // Binance API endpoint
        $endpoint = 'https://api-gcp.binance.com/api/v3/account';
        
        // Generate a timestamp
        $timestamp = round(microtime(true) * 1000);
        
        // Create a query string
        $queryString = "timestamp={$timestamp}";
        
        // Create a signature
        $signature = hash_hmac('sha256', $queryString, $apiSecret);
        
        // Add the signature to the query string
        $queryString .= "&signature={$signature}";
        
        // Create headers
        $headers = [
            "X-MBX-APIKEY: {$apiKey}"
        ];
        
        // Initialize curl
        $ch = curl_init();
        
        // Set curl options
        curl_setopt($ch, CURLOPT_URL, "{$endpoint}?{$queryString}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Execute curl request
        $response = curl_exec($ch);
        
        // Check for curl errors
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
            exit;
        }
        
        // Close curl
        curl_close($ch);
        
        // Decode the JSON response
        $data = json_decode($response, true);
        
        
        
        foreach ($data['balances'] as $asset) 
        {
            if ($asset['asset'] == $pair) 
            {
                $balance=$asset['free'];
                
            }
        }
        
        return $balance;
	    
	}
	
	function candleprice($apiKey,$apiSecret,$pair)
	{
	    
	    $endpoint = 'https://api1.binance.com/api/v1/klines';

        // Parameters for the request
        $params = [
            'symbol' => $pair, // Replace with your desired trading pair
            'interval' => '15m',
            'limit' => 1
        ];
        
        // Build the query string
        $queryString = http_build_query($params);
        
        // Create headers
        $headers = [
            "X-MBX-APIKEY: {$apiKey}"
        ];
        
        // Initialize curl
        $ch = curl_init();
        
        // Set curl options
        curl_setopt($ch, CURLOPT_URL, "{$endpoint}?{$queryString}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Execute curl request
        $response = curl_exec($ch);
        
        // Check for curl errors
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
            exit;
        }
        
        // Close curl
        curl_close($ch);
        
        // Decode the JSON response
        $data = json_decode($response, true);
        
        // Print the first candlestick (the oldest one in ascending order)
        if (isset($data[0])) {
            $candlestick = $data[0];
            return $candlestick[4];
            
       } else {
            return 0;
        }
	    
	    
	}
	
	function binance_exchangeinfo($apiKey)
	{
	    
        // Binance API endpoint for exchange info
       /* $endpoint = 'https://api1.binance.com/api/v3/exchangeInfo';
        
        
        
        // Create headers
        $headers = [
            "X-MBX-APIKEY: {$apiKey}"
        ];
        
        // Initialize curl
        $ch = curl_init();
        
        // Set curl options
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Execute curl request
        $response = curl_exec($ch);
          
   
      
        
        // Close curl
        curl_close($ch);
        
        // Decode the JSON response
        $data = json_decode($response, true);*/
        
        $data = json_decode(file_get_contents('https://aqua-x.co/binance_exchange_info.json'), true);
        
       
        return $data;
	    
	}
	
	function binance_sell($apiKey,$apiSecret,$pair,$quantity)
	{
	    $endpoint = 'https://api1.binance.com/api/v3/order';
	    

        // Order parameters
        $params = [
            'symbol' => $pair, // Replace with your desired trading pair
            'side' => 'SELL',
            'type' => 'MARKET', // Can be MARKET, LIMIT, etc.
            'timeInForce' => 'GTC', // Good 'til canceled
            'quantity' => $quantity, // Replace with the amount you want to sell
            'timestamp' => round(microtime(true) * 1000)
        ];
        
        // Build the query string
        $queryString = http_build_query($params);
        
        // Create a signature
        $signature = hash_hmac('sha256', $queryString, $apiSecret);
        
        // Add the signature to the query string
        $queryString .= "&signature={$signature}";
        
        // Create headers
        $headers = [
            "X-MBX-APIKEY: {$apiKey}",
            "Content-Type: application/x-www-form-urlencoded"
        ];
        
        // Initialize curl
        $ch = curl_init();
        
        // Set curl options
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Execute curl request
        $response = curl_exec($ch);
        
        // Check for curl errors
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
            exit;
        }
        
        // Close curl
        curl_close($ch);
        
        // Decode the JSON response
        $data = json_decode($response, true);
        print_r($data);

	    return $data;
	    
	}
	
	function getLastPrice($symbol) {
        $url = 'https://api1.binance.com/api/v3/ticker/bookTicker?symbol=' . $symbol;
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        $response = curl_exec($ch);
        curl_close($ch);
    
        $priceInfo = json_decode($response, true);
        return (float)$priceInfo['askPrice'];
    }
    
    
    function getliveprice($symbol) {
        $url = 'https://api.binance.com/api/v3/ticker/price?symbol='.$symbol;
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        $response = curl_exec($ch);
        curl_close($ch);
    
        $priceInfo = json_decode($response, true);
        
        return (float)$priceInfo['price'];
    }
    
    
    function getpairs($exchange) {
        $url = 'https://aqua-x.co/trading_pairs.json';
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        $response = curl_exec($ch);
        curl_close($ch);
    
        $priceInfo = json_decode($response, true);
        return $priceInfo;
    }

	
	
	function binance_order($apiKey,$apiSecret,$side,$pair,$quantity,$price,$type,$flag='')
	{
	    $endpoint = 'https://api1.binance.com/api/v3/order';

        $params = [
            'symbol' => $pair, // Replace with your desired trading pair
            'side' => $side,
            'type' => 'MARKET', // Can be MARKET, LIMIT, etc.
         //'quantity' => $quantity, // Replace with the amount you want to sell
            'timestamp' => round(microtime(true) * 1000)
        ];
        if($side=='BUY')
             $params['quoteOrderQty'] = $quantity;
        else
             $params['quantity'] = $quantity;

        
        // Build the query string
        $queryString = http_build_query($params);
        
       
        
        // Create a signature
        $signature = hash_hmac('sha256', $queryString, $apiSecret);
        
        // Add the signature to the query string
        $queryString .= "&signature={$signature}";
        
        // Create headers
        $headers = [
            "X-MBX-APIKEY: {$apiKey}",
            "Content-Type: application/x-www-form-urlencoded"
        ];
        
        // Initialize curl
        $ch = curl_init();
        
        // Set curl options
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        
        // Execute curl request
        $response = curl_exec($ch);
        
        // Check for curl errors
        if (curl_errno($ch)) {
            echo 'Curl error: ' . curl_error($ch);
            exit;
        }
        
        // Close curl
        curl_close($ch);
        
        // Decode the JSON response
        $data = json_decode($response, true);
        
        
	    return $data;
	    
	}



	function balancecheck($KeyValue) {
		$CI =& get_instance();

		$condition="type In('interest','Lending Matured','bonus','commissions')";
		$CI->db->where ($condition);
		
		$CI->db->where('uusersid',$KeyValue);
		$CI->db->selectSum('amount');
		$query=$CI->db->get('history');
		$site_data = $query->row();
		if($site_data)
		 $deposit =  $site_data->amount;



		$condition="type In('withdrawal','withdraw_request','penalty')";
		$CI->db->where ($condition);
		
		$CI->db->where('uusersid',$KeyValue);
		$CI->db->selectSum('amount');
		$query=$CI->db->get('history');
		$site_data = $query->row();
		if($site_data)
		 $deposit1 =  $site_data->amount;

		$bal =$deposit- $deposit1;

		if($bal<0){
			$bal = "0.00";
		}else{
			$bal = $bal;
		}

		return $bal;

	}
	


	function tottokens($KeyValue) {
		$CI =& get_instance();
		$CI->db->where('icoid', '1');
		$CI->db->select('notokens');
		$query=$CI->db->get('icoset');
		$site_data = $query->row();
		if($site_data)
		 return $site_data->notokens;

	}
	
	function tokenname($KeyValue) {
		$CI =& get_instance();
		$CI->db->where('icoid', '1');
		$CI->db->select('coinunit');
		$query=$CI->db->get('icoset');
		$site_data = $query->row();
		if($site_data)
		 return $site_data->coinunit;

	}

	
	function tokendet($KeyValue) {
		$CI =& get_instance();
		$CI->db->where('icoid', '1');
		$CI->db->select('*');
		$query=$CI->db->get('icoset');
		$site_data = $query->row();
		if($site_data)
		 return $site_data;

	}


	function tokenvalue($KeyValue)
	{
		$CI =& get_instance();
		$CI->db->where('icoid', '1');
		$CI->db->select('*');
		$query=$CI->db->get('icoset');
		$site_data = $query->row();
		$startdate=date("Y-m-d",strtotime($site_data->startdate));
		$enddate=date("Y-m-d",strtotime($site_data->enddate));
		$now=date("Y-m-d");
		if(strtotime($startdate)>strtotime($now))
		{
			$tokenvalue=$site_data->valuetoken;

		}
		else 
		{
			$CI->db->where('status', '0');
			$CI->db->select('*');
			$CI->db->order_by("icocal", "asc");
			$CI->db->limit('1');
			$query=$CI->db->get('icocalendar');
			$site_data = $query->row();
			$tokenvalue=$site_data->price;
			if(!$tokenvalue)
			{
				$CI->db->where('status', '1');
				$CI->db->select('*');
				$CI->db->order_by("icocal", "desc");
				$CI->db->limit('1');
				$query=$CI->db->get('icocalendar');
				$site_data = $query->row();
				$tokenvalue=$site_data->price;

			}
		}
		return $tokenvalue;
	}

	// get site information with language
	function site_info_lang($KeyValue, $language) {
		$CI = db_connect();
		$builder = $CI->table('site_controls');
		$builder->where('settings_name', 'site');
		$builder->where('site_key', $KeyValue);
		if($language)
			$builder->where('language_id', $language);
		$query=$builder->get();
		
		$site_data = $query->getRow();
		if($site_data)
		return $site_data->site_value;
	}

	// get language
	function activeLanginfo($condition='') {
		$CI = db_connect();
		$builder = $CI->table('language_controls');
		if($condition!='') {
			$builder->where('language_name', $condition);	
		} else {
			$builder->where('language_default', '1');	
		}
		$builder->where('language_status', '1');
		$query=$builder->get();
		$active_lang_data = $query->getRow();
		if($active_lang_data)
		return $active_lang_data;
	}

	// get footer content
	function site_footer() {

		$CI = db_connect();
		$builder = $CI->table('site_controls');
		$builder->select('site_value');
		$builder->where('settings_name', 'footer');
		$builder->where('site_key', 'footer_note');
		$query=$builder->get();
		$footer_data = $query->getRow();
		// $footer_content = str_replace("<p>", "", $footer_data->site_value);
		// $footer_content = str_replace("<p>", "", $footer_data->site_value);
		// $footer_content = str_replace("&amp;", "&", $footer_data->site_value);
		// if($footer_content) {
			// $dom = new DOMDocument();

	  //       $dom->loadHTML($footer_content);
	  //       $xpath = new DOMXPath($dom);
	  //       $div = $xpath->query('//div[@class="footer_bottom_left"]');
	  //       $div = $div->item(0);
	  //       $footer_cnt = $dom->saveXML($div);
	  //       if($footer_cnt)
	  //       	return $footer_cnt;
	  //       else
	  //       	return $footer_content;
		// }
		
	}

	// get header content
	function site_header() {
		$CI =& get_instance();
		$language_id = ($CI->session->userdata('user_langid')) ? $CI->session->userdata('user_langid') : '1';
		$CI->db->where('settings_name', 'site');
		$CI->db->where('language_id',$language_id);
		$CI->db->select('site_key, site_value');
		$query=$CI->db->get('site_controls');
		$header_data = $query->result();
		if($header_data)
		return $header_data;
	}

	// get currency
	function defaultcurrency() {
		$CI = db_connect();
		$builder = $CI->table('currency_controls');
		// $CI->db->where('currency_name', $condition);
		$builder->where('currency_default', '1');
		$builder->where('currency_status', '1');
		$query=$builder->get();
		$active_cur_data = $query->getRow();
		if($active_cur_data)
		return $active_cur_data;
	}

	// get user setting
	function userMinPass() {
		$CI = db_connect();
		$CI->db = $CI->table('site_controls');
		$CI->db->where('settings_name', 'user');
		$CI->db->where('site_key', 'user_min_password_length');
		$CI->db->select('site_value');
		$query=$CI->db->get();
		$user_def_data = $query->getRow();
		if($user_def_data)
		return $user_def_data->site_value;
	}


//get login setting
	function authentication_loginlimit(){
		$CI =db_connect();
		$builder = $CI->table('site_controls');
		$builder->where('settings_name', 'login');
		$builder->where('site_key', 'log_auth_limit');
		$builder->select('site_value');
		$query=$builder->get();
		$login_authlimit_data = $query->getRow();
		if($login_authlimit_data)
		return $login_authlimit_data->site_value;
	}
	// active language list
	function activelang() {
		$CI = db_connect();
		$builder = $CI->table('language_controls');
		$builder->select('language_code,language_name,language_id');
		$builder->where('language_status', '1');
		$query=$builder->get();
		$active_lang_data = $query->getResult();
		if($active_lang_data)
		return $active_lang_data;
	}


	// get site control single column
	function setting_info($settings_name, $KeyValue) {
		$CI =& get_instance();
		$CI->db->where('settings_name', $settings_name);
		$CI->db->where('site_key', $KeyValue);
		$query=$CI->db->get('site_controls');
		$site_data = $query->row();
		if($site_data)
		return $site_data->site_value;
	}
    

	function statisticsRecord() {

		$CI =& get_instance();
		$CI->db->where('statistics_name','show_infobox');
		$CI->db->select('statistics_key, statistics_value');
		$CI->db->from('statistics_controls');
		
		$query = $CI->db->get();
		if ($query->num_rows()>0) {
			return $query->result();
		} else {
			return FALSE;
		}
	}

	function Checkip() {
        $session = new Request;
		$CI = db_connect();
		$builder = $CI->table('ip_controls');
		$builder->where('ip_address',$session->getIPAddress());
		$builder->select('*');
		
		$query = $builder->get();
		if ($query->getNumRows()>0) {
			return TRUE;
		} else {
			return FALSE;
		}

	}

	function pagePermission() {
        $common_model = model('CommonModel');
		$CI = db_connect();
		if(!session()->get('permission')) {
			$condition = "id = '".session()->get('userid')."'";
			if(session()->get('userid') == "")
				$condition = "id = 1 ";
        	$admin_page = $common_model->GetRow('admin',$condition);
        	session()->set(array("permission" =>  $admin_page->permission));
        	return $admin_page->permission;
		}
		
	}


	/* -------------------------------------------------------------------------------------- */
	/* -------------------------------------------------------------------------------------- */
	/* -------------------------------  pool trade volume helpers  ------------------------------- */
	/* -------------------------------------------------------------------------------------- */
	/* ------------------------------- ------------------------------------------------------- */


	function profit_wallet($userid)
	{

	$CI =db_connect();
	/*$profit = $CI->query("SELECT SUM(total_earn) AS amount FROM `deposit` WHERE uusersid = '".$userid."' ")->getRow();*/
	//$profit=$CI->query("select sum(amount) as amount from history where type='pool_interest' and uusersid='".$userid."' and status='0'")->getRow();

	$profit=$CI->query("select sum(total_earn) as amount from deposit where uusersid='".$userid."'")->getRow();

//print_r("Profit Wallet ==> ".$profit->amount);
	$profit1=$CI->query("select sum(amount) as amount from history where type='share_commissions' and uusersid='".$userid."'")->getRow();

	//$withdraw = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('pool_invest','pool_invest_fee','pool_withdraw_request','pool_fuel_fee','withdrawal_pool','pool_withdraw_fee') and payment_id ='1' ")->getRow()->amount;

	$withdraw = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('pool_invest','pool_invest_fee','pool_withdraw_request','withdrawal_pool','pool_withdraw_fee') and payment_id ='1' ")->getRow()->amount;

//print_r("withdraw Wallet ==> ".$withdraw);

	$fuel_pool = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('pool_fuel_fee') and payment_id ='0' ")->getRow()->amount;
	
//print_r("fuel fee ==> ".$fuel_pool);

	$share_pool = $CI->query("SELECT SUM(amount) as amount from history WHERE  type IN('share_commissions') and from_pool_earn ='".$userid."' ")->getRow()->amount;
	
//print_r("share Wallet ==> ".$share_pool);	
	$balan_share_fee = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('balance_share_commision') ")->getRow()->amount;

//print_r("balance share ==> ".$balan_share_fee);
//$profit1->amount
	//$minus_value = $profit->amount-$withdraw-$fuel_pool-$share_pool-$balan_share_fee;
	//$minus_value = $profit->amount-$withdraw-$share_pool-$balan_share_fee;
	//$minus_value = $profit->amount-$withdraw-$share_pool;
	$minus_value = $profit->amount-$withdraw;
	return number_format($minus_value,4);

	}

	function today_percentage()
	{

	$CI =db_connect();
	$today = date('Y-m-d');
	$fetch_interest = $CI->query("SELECT * FROM `daily_interest` where DATE(cr_date) = '".$today."' ")->getRow();

	return $fetch_interest->rate;

	}


	function total_downline($userid)
	{

	$CI =db_connect();
	$today = date('Y-m-d');
	$fetch_interest = $CI->query("SELECT * FROM  uusers_matrix  WHERE uusersid = '".$userid."'  ")->getRow();
    $array_count = $fetch_interest->members_cnt;

    if($array_count!="")
    {
      $check_array = count(explode(',', $array_count));
    }
    else
    {
      $check_array = 0;
    }

     return $check_array;
	}


    function reward_wallet($userid)
	{
		$CI =db_connect();
		$today = date('Y-m-d');

		$fetch_interest = $CI->query("SELECT SUM(amount)as amt FROM  history  WHERE uusersid = '".$userid."' and type IN('share_commissions','bonus_commissions') ")->getRow();

	   $withdraw = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('pool_invest','pool_invest_fee','pool_withdraw_request','withdrawal_pool','pool_withdraw_fee') and payment_id ='2' ")->getRow()->amount;

		$array_count = $fetch_interest->amt - $withdraw;


		if($array_count >0)
		{
		   $amt = $array_count;
		}
		else
		{
	       $amt = 0;
		}

		return $amt;
    }


function total_earnings_wallet($userid)
{
	$CI =db_connect();
	$today = date('Y-m-d');

	$fetch_interest = $CI->query("SELECT SUM(amount)as amt FROM  history  WHERE uusersid = '".$userid."' and type IN('share_commissions','bonus_commissions') ")->getRow();

	$array_count = $fetch_interest->amt;

	$profit=$CI->query("select sum(amount) as amount from history where type='pool_interest' and uusersid='".$userid."' and status='0'")->getRow();
	//$profit = $CI->query("SELECT SUM(total_earn) AS amount FROM `deposit` WHERE uusersid = '".$userid."' ")->getRow();
	

	if($profit)
	{	
		$minus_value = $profit->amount;
	}
	else
	{
		$minus_value='0';
	}

	

	
	$amt='0';
	if($array_count >0)
	{
	$amt = $array_count + $minus_value;
	}
	else
	{
		$amt = $minus_value;
	}



	return $amt;

 }


	function share_pool_profit($userid)
	{
	
	$CI =db_connect();
	$profit = $CI->query("SELECT SUM(total_earn) AS amount FROM `deposit` WHERE uusersid = '".$userid."' ")->getRow();
	$minus_value = $profit->amount;
	return number_format($minus_value,4);

	}

	function cash_wallet($userid)
	{
		$CI =db_connect();

		$profit = $CI->query("SELECT SUM(amount) AS amount FROM `deposit` WHERE uusersid = '".$userid."' and status='released'")->getRow();

	   $withdraw = $CI->query("SELECT SUM(amount) as amount from history WHERE uusersid = '".$userid."' and type IN('pool_invest','pool_invest_fee','pool_withdraw_request','withdrawal_pool','pool_withdraw_fee') and payment_id ='3' ")->getRow()->amount;


		if($profit)
		{
		  $minus_value = $profit->amount - $withdraw;
		}
		else
		{
          $minus_value = 0;
		}

		return number_format($minus_value,4);	

		
	}

	function my_pool_balance($userid)
	{

	$CI =db_connect();
	$profit = $CI->query("SELECT SUM(amount) AS amount FROM `deposit` WHERE status !='released' AND uusersid = '".$userid."'")->getRow();

	$pool_balance = $profit->amount;

	return number_format($pool_balance,4);

	}

	function overall_trade_volume()
	{
	
	$CI =db_connect();

    $admin_check = $CI->query("SELECT * FROM `site_controls` WHERE settings_name = 'pool_invest' and site_key = 'trade_pool_volume_status'")->getRow();


   if($admin_check->site_value!=0)
   {
        $check_admin_show = 'on';	
   }
   else
   {
     	$check_admin_show = 'off';
   }
   

   if($check_admin_show == 'on')
   {

    $admin_check_row = $CI->query("SELECT * FROM `site_controls` WHERE settings_name = 'pool_invest' and site_key = 'robot_trade_volume'")->getRow();

	 return  $admin_check_row->site_value;
    
   }
   else
   {

   $profit = $CI->query("SELECT SUM(amount) AS amount FROM `deposit` WHERE status ='active' ")->getRow();

   return  $profit->amount;

   }


	}

	 function pool_deposit($userid)
	{
		$CI =db_connect();

		$deposit_amount = $CI->query("SELECT SUM(amount) as amt from deposit where uusersid='".$userid."' and status='active' ORDER BY `deposit`.`amount` DESC ")->getRow();

		if($deposit_amount)
		{
		if($deposit_amount->amt > 0)
		{
		$retrun_amt = $deposit_amount->amt;
		}
		else
		{
		$retrun_amt ='0';
		}
		}
		else
		{
		$retrun_amt ='0';
		}

		return $retrun_amt;
	}
	
	function progress_bar($id, $user)
    {
        $common_model = model("CommonModel");
        $CI = db_connect();
    
        $flag = 0;
        $balance = 0;
    
        $con = "id = '" . $id . "'";
        $rank = $common_model->GetRow("rewardsettings", $con);
    
        $con = "referral_id= '" . $user . "'";
    
        $user_count = $CI->query('select count("id") as user_cnt from uusers_matrix where referral_id = "' .$user .'"')->getRow();
    
        $uuser_count = $user_count->user_cnt;
    
        $direct_sponsor = $common_model->GetResults("uusers_matrix", $con);

        if($direct_sponsor)
        {
    
            foreach ($direct_sponsor as $row) {
                $ucon = "uusersid = '" . $row->uusersid . "'";
                $uuser = $common_model->GetRow("uusers", $ucon);
        
                if ($uuser->rankid == $rank->sponsor_elg_rank) {
                    $flag++;
                }
        
                $buy_bal = curbalance($row->uusersid, 1);
                $curbalance = str_replace(",", "", $buy_bal);
        
                $balance = $balance + $curbalance;
            }
        }

      if($rank->direct_spon_count != 0) 
      {
        $dcount = ($uuser_count / $rank->direct_spon_count) * 100;
        if ($dcount >= 100) {
            $dcount = 100;
        }
        else
        {
            $dcount=0;
        }
		
    } 
    else 
    {
        $dcount = "100";
    }

    if ($rank->sponsor_elg_count != 0) {
        $scount = ($flag / $rank->sponsor_elg_count) * 100;
        if ($scount >= 100) {
            $scount = 100;
        }
    } else {
        $scount = "100";
    }

    if ($rank->group_sales != 0) {
        $gcount = ($balance / $rank->group_sales) * 100;
        if ($gcount >= 100) {
            $gcount = 100;
        }
    } else {
        $gcount = "100";
    }

    $avg = ($dcount + $scount + $gcount) / 3;

    if ($avg > 100) {
        $avgg = 100;
    } else {
        $avgg = $avg;
    }

    return $avgg;
}


	/* -------------------------------  pool trade volume helpers  ------------------------------- */