<?php 
namespace App\Controllers\User;

use App\Views;
use App\Models\CommonModel;
use PHPMailer\PHPMailer\Exception;
use App\Helpers\site_helper;
use App\Helpers\kucoin_helper;
use App\Libraries\MyEncrypt;
use App\Libraries\My_PHPMailer;
use App\Libraries\PHPMailer; 
use App\Libraries\mathcaptcha;
use App\Libraries\BybitApi;
use Binance; 
use Lin\Kraken\Kraken;
//require_once __DIR__ .'../../../kucoin-php-master/vendor/autoload.php';

class ApiKeyList extends BaseController
{
	public function __construct(){
		// $CommonModel = new CommonModel();
		$CommonModel = model('CommonModel');
	}
   public function index() {
   	$session = \Config\Services::session();
		if(!($session->get('user_login') || $session->get('admin_login')))
		{			
			throw new \CodeIgniter\Router\Exceptions\RedirectException('login');
		}
		$this->indexpage();
    }
	
	public function indexpage() {

		// print_r(__DIR__ .'../../../kucoin-php-master/vendor/autoload.php');
		// exit;

		$session = \Config\Services::session();
		$this->db = db_connect();
		if(!($session->get('user_login') || $session->get('admin_login')))
		{			
			return redirect()->to('login');
		}
        $CommonModel = model('CommonModel');
		//$this->db->query("SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''))");


		// $languageid = ($this->session->get('user_langid')) ? $this->session->get('user_langid'): '1';

		$condition = "payment_key in('logo','status')";
		$payment_data_list = $CommonModel->GetPaymentsName($condition);
		$site_data = $CommonModel->GetSettingall('infobox');
		if($site_data) {
			
			foreach ($site_data as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}

		} else {
			$site_data_default = $CommonModel->defaultlangSettingall('infobox');
			foreach ($site_data_default as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}
		}

		$site_lang_data = $CommonModel->GetSiteSettings('site');
		
		if($site_lang_data){	
			$site_data = array_merge($site_data, $site_lang_data);
		}

		foreach ($site_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
     
		$con = "status = 1";
		$this->data['apikey'] = $CommonModel->GetResults('api_exchange_list',$con);

	

	   echo view('user/apikeylist',$this->data);
	}

	public function verificationcode()
	{
		 $this->db = db_connect();
         $this->common_model = model('CommonModel');
         $uusersid = $this->request->getPost('uusersid');
		// $uusersid =$_SESSION["uusersid"];     	
      	
       $referral1=$this->db->query("SELECT * FROM uusers WHERE uusersid='".$uusersid."'")->getResult();

	   $ref=$referral1[0];
	
	   $email = $ref->email;
	  
       $otp = rand(100000, 999999); //generates random otp
	   
	
      
        //$_SESSION['session_otp'] = $otp;
        $message = "Your one time email verification code is " . $otp;
        $sub = "Email verification";

		
         $this->session = \Config\Services::session();

		


        $this->session->set('uusersid',$uusersid);
        $this->session->set('email',$email);
        $this->session->set('otp',$otp);

		

        $this->db = db_connect();
        $table='admin';
        $condition = "id ='1'";
		
        $adminmail=$this->db->query("SELECT * FROM $table WHERE id='1'");	  
		$adminemail= $adminmail->getRow();		
		$admin_email=$adminemail->email;
		
		
		if($admin_email)
		{
			$from_mail=$admin_email;
		}
	

		
		
       if($email)
       {
			$sub = 'Verify E-Mail Address';
			$mailid = '1';
			$mail_subject_data = $this->common_model->getMailTemplate($mailid);
			$message  = str_replace('[OTP]', $otp, $mail_subject_data->message);
			$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);

   //          $email = \Config\Services::email();
			// $email->setFrom($mail_subject_data->from_mail, 'AI Quantification');
			// $email->setTo($email);
			// $email->setSubject($sub);
			// $email->setMessage($message);
			// $email->send();

			//$mail=$this->sendmail($email,$message,$sub,$mail_subject_data->from_mail);
		//$mail=1;
			$this->db = db_connect();
        
         	$data=array(
        		"uusersid" => $uusersid,
         		"email" => $email,
				
         		"otp" => $otp
         	); 

			
         	$session= \Config\Services::session();
	 		$uusersid=SESSION('uusersid');
			$this->db = db_connect();

         	$condition2 = "uusersid ='".$uusersid."'";		
			
		$bind_data = $this->common_model->GetRow('bind_api',$condition2);

		if($bind_data!='')
		{
			
			$query_status = $this->db->table('bind_api')->where('uusersid', $uusersid)->update($data);
			$json['message'] = "OTP send to your Email.";
		}
		else
		{  
			
    
           $query_status = $this->db->table('bind_api')->insert($data);
           $json['message'] = "OTP send to your Email.";
        }
		
        
     }

     
        else
        {        	
         	 $json['message'] = "Cannot Send OTP.";
         	
        }

        echo json_encode($json['message']);
          
        

	}

	public function verifyotp()
	{

       $this->session = session();
		$uusersid = $this->session->get('uusersid');

		$code1=$this->request->getPost('code1');
		$otp=$this->session->get('otp');	
		

		if($code1==$otp)
		{
			$json['message'] = '' ;
			
		}
		else
		{
			$json['message'] = "Please enter valid otp";
		}
	
		echo json_encode($json['message']);
	
	}
	public function verifyapi()
	{
		$this->session = session();
		
		$apikey=$this->request->getPost('api');

		$secret_key=$this->request->getPost('sec');
 
		$api = new Binance\API($apikey,$secret_key);

		$account = $api->account();

		
		
		if(!empty($account['code']))
		{
		 	$json['message'] = $account['msg'];
		}
		else
		{
			$json['message']= "valid";
		}	
		echo json_encode($json['message']);	
	}
	
	public function submit_data()
	{
		$session = session();
		$uusersid=$this->request->getPost('userid');
		$apikey=$this->request->getPost('api_code1');
		$secret_key=$this->request->getPost('sec_code1');
		$data=array(
			'uusersid' => $uusersid,
			'api_key' => $apikey,
			'secret_key' => $secret_key,
			 'type' => '1'
		);
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type=1");
        $ref=$referral1->getRow();
		if($ref!='')
		{
			$query_status = $this->db->table('bind_process')->where('uusersid', $uusersid)->where('type','1')->update($data);
		}
		else
		{        
			$query_status = $this->db->table('bind_process')->insert($data);
		}
      	if($query_status)
      	{
			$session->setFlashData('success_message', 'successfully bind');
      		return redirect()->to('apikeylist');
      	}
      	else
      	{
      		$session->setFlashData('error_message', 'Failed to bind');
      		return redirect()->to('apikeylist');
      	}
     
		// print_r($secret_key);
		// exit();
	}
	
	
	public function remove_api()
	{
		$session = session();
		$uusersid=$this->request->getPost('uusersid');
		$type=$this->request->getPost('id');
	
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type='".$type."'");
        $ref=$referral1->getRow();
		if($ref!='')
		{
		    $check_response=$this->db->query("select * from trade_process where uusersid='".$uusersid."' and trade_status!='2' and exchange='".$type."'")->getRow();
		    if($check_response)
		    {
		        echo 'yes';
		    }
		    else
		    {
		       
		       //echo "delete from bind_process where id='".$ref->id."'";
		       //$this->db->query("delete from bind_process where uusersid='".$uusersid."' and type='".$type."'");
		       //echo  $this->db->getLastQuery(); 
		       //$this->db->table('bind_process')->where('id',$ref->id)->delete();
		       $condition=array("id"=> $ref->id);
		       $this->db->table('bind_process')->where($condition)->delete();
		       
		       
		       
		    
		        echo 'no';
		    }
			
		}
		else
		{        
			echo 'exit';
		}
      	
     
		// print_r($secret_key);
		// exit();
	}

   public function huobi_bind_update()
	{
		$session = session();
		$uusersid=$this->request->getPost('userid');
		$apikey=$this->request->getPost('api_code1');
		$secret_key=$this->request->getPost('sec_code1');
		//$pass_phrase=$this->request->getPost('pass_phrase');
		$data=array(
			'uusersid' => $uusersid,
			'api_key' => $apikey,
			'secret_key' => $secret_key,
			'type' => '2',
		);
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type=2 ");
        $ref=$referral1->getRow();
		if($ref!='')
		{
			$query_status = $this->db->table('bind_process')->where('uusersid', $uusersid)->where('type','2')->update($data);
		}
		else
		{        
			$query_status = $this->db->table('bind_process')->insert($data);
		}
      	if($query_status)
      	{
			$session->setFlashData('success_message', 'successfully bind');
      		return redirect()->to('apikeylist');
      	}
      	else
      	{
      		$session->setFlashData('error_message', 'Failed to bind');
      		return redirect()->to('apikeylist');
      	}
     
		// print_r($secret_key);
		// exit();
	}

    public function bybit_bind_update()
	{
		
		$session = session();

		$validation =  \Config\Services::validation();
		$validation->setRules([
				'api_code1' => [ "label" =>'Api Key', "rules" => 'trim|required'],
				'sec_code1' => [ "label" =>'Secret Key', "rules" => 'trim|required'],
				'account' => [ "label" =>'Account', "rules" => 'trim|required'],
				]);
		if ($validation->withRequest($this->request)->run() == TRUE) {
		$uusersid=$this->request->getPost('userid');
		$apikey=$this->request->getPost('api_code1');
		$secret_key=$this->request->getPost('sec_code1');

			$bybitapi = new BybitApi($apikey,$secret_key);
			$account = $bybitapi->accountInfo();
			if($account == false){
				$session->setFlashData('error_message', 'Enter Valid API and Secret Key');
				return redirect()->to('binding/bybit');
			}
			$margintype = $account['unifiedMarginStatus']; // 1 = general account and 3 or 4 for unified account
			$selectedacc = $this->request->getPost('account');
			if(($margintype == 1 && $selectedacc != 1) || ($margintype > 2 && $selectedacc != 2)){
				$session->setFlashData('error_message', 'Account mis-match error Select valid account type');
				return redirect()->to('binding/bybit');
			}

			$data=array(
				'uusersid' => $uusersid,
				'api_key' => $apikey,
				'secret_key' => $secret_key,
				'type' => '5',
				'account'=> $selectedacc
			);
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type=5");
       $ref=$referral1->getRow();
		if($ref!='')
		{
			$query_status = $this->db->table('bind_process')->where('uusersid', $uusersid)->where('type','5')->update($data);
		}
		else
		{        
			$query_status = $this->db->table('bind_process')->insert($data);
		}
 
		$session->setFlashData('success_message', 'successfully bind');
      	return redirect()->to('apikeylist');
      

      }else{
      		$session->setFlashData('error_message', 'Please Enter All values');
				return redirect()->to('binding/bybit');
      }
     
		// print_r($secret_key);
		// exit();
	}

	


	public function kucoin_bind_update()
	{
		$session = session();
		$uusersid=$this->request->getPost('userid');
		$apikey=$this->request->getPost('api_code1');
		$secret_key=$this->request->getPost('sec_code1');
		$pass_phrase=$this->request->getPost('pass_phrase');
		$data=array(
			'uusersid' => $uusersid,
			'api_key' => $apikey,
			'secret_key' => $secret_key,
			'pass_phrase' => $pass_phrase,
			 'type' => '7'
		);
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type=7");
        $ref=$referral1->getRow();
		if($ref!='')
		{
			$query_status = $this->db->table('bind_process')->where('uusersid', $uusersid)->where('type','7')->update($data);
		}
		else
		{        
			$query_status = $this->db->table('bind_process')->insert($data);
		}
      	if($query_status)
      	{
			$session->setFlashData('success_message', 'successfully bind');
      		return redirect()->to('apikeylist');
      	}
      	else
      	{
      		$session->setFlashData('error_message', 'Failed to bind');
      		return redirect()->to('apikeylist');
      	}
     
		// print_r($secret_key);
		// exit();
	}

	public function okx_bind_update()
	{
		$session = session();
		$uusersid=$this->request->getPost('userid');
		$apikey=$this->request->getPost('api_code1');
		$secret_key=$this->request->getPost('sec_code1');
		$pass_phrase=$this->request->getPost('pass_phrase');
		$data=array(
			'uusersid' => $uusersid,
			'api_key' => $apikey,
			'secret_key' => $secret_key,
			'pass_phrase' => $pass_phrase,
			 'type' => '6'
		);
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type=6");
        $ref=$referral1->getRow();
		if($ref!='')
		{
			$query_status = $this->db->table('bind_process')->where('uusersid', $uusersid)->where('type','6')->update($data);
		}
		else
		{        
			$query_status = $this->db->table('bind_process')->insert($data);
		}
      	if($query_status)
      	{
			$session->setFlashData('success_message', 'successfully bind');
      		return redirect()->to('apikeylist');
      	}
      	else
      	{
      		$session->setFlashData('error_message', 'Failed to bind');
      		return redirect()->to('apikeylist');
      	}
     
		
	}


	public function kraken_bind_update()
	{
		$session = session();
		$uusersid=$this->request->getPost('userid');
		$apikey=$this->request->getPost('api_code1');
		$secret_key=$this->request->getPost('sec_code1');
		$pass_phrase=$this->request->getPost('pass_phrase');
		$data=array(
			'uusersid' => $uusersid,
			'api_key' => $apikey,
			'secret_key' => $secret_key,
			'pass_phrase' => $pass_phrase,
			 'type' => '6'
		);
		$this->db = db_connect();
 		$referral1=$this->db->query("SELECT * FROM bind_process WHERE uusersid='".$uusersid."' and type=4");
        $ref=$referral1->getRow();
		if($ref!='')
		{
			$query_status = $this->db->table('bind_process')->where('uusersid', $uusersid)->where('type','4')->update($data);
		}
		else
		{        
			$query_status = $this->db->table('bind_process')->insert($data);
		}
      	if($query_status)
      	{
			$session->setFlashData('success_message', 'successfully bind');
      		return redirect()->to('apikeylist');
      	}
      	else
      	{
      		$session->setFlashData('error_message', 'Failed to bind');
      		return redirect()->to('apikeylist');
      	}
     
		
	}

	
function sendmail($useremail, $message, $subject,$from_mail) {

//$this->load->library('My_PHPMailer');
$condition = "settings_name = 'email'";
$email_setting_data = $this->common_model->GetSettingall_lang($condition);

foreach ($email_setting_data as $row) {
$mail_data[$row->site_key] = $row->site_value;
}

if($mail_data['email_throw']=='php')
{
$mail = new PHPMailer();
$mail->isMail();

} else {

$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPAuth   = TRUE; 
$mail->SMTPSecure = $mail_data['smtp_type'];  
$mail->Host       = $mail_data['smtp_hostname'];      
$mail->Port       = $mail_data['smtp_portno'];                   
$mail->Username   = $mail_data['smtp_username'];  
$mail->Password   = $mail_data['smtp_password'];   
}

$mail->SetFrom($from_mail, site_info_lang('site_name',session()->get('langid')));  
$mail->AddReplyTo($from_mail,site_info_lang('site_name',session()->get('langid')));
$message  = str_replace('#adminemail', $from_mail, $message);

$mail->Subject    = $subject;
$mail->msgHTML($message);

$mail->AddAddress($useremail, $fullname);

if(!$mail->Send()) {
// return $mail->ErrorInfo;
return $mail->ErrorInfo;
} else {
return true;
}
}

public function binance_bind()
{
	return view('user/binance_bind');
}

public function huobi_bind()
{
	return view('user/huobi_bind');
}

public function bybit_bind()
{
	return view('user/bybit_bind');
}

public function kucoin_bind()
{
	
	 return view('user/kucoin_bind');
}

public function okx_bind()
{
	return view('user/okx_bind');
}

public function kraken_bind()
{
	return view('user/kraken_bind');
}


public function verifykucoinapi()
	{
		helper('kucoin_helper');
		$this->session = session();
		
		$apikey=$this->request->getPost('api');

		$secret_key=$this->request->getPost('sec');
		
		$pass_phrase = $this->request->getPost('pass');


        $account = accountStatus($apikey,$secret_key,$pass_phrase);
		
		
		if($account != '200000')
		{
		 	$json['message'] = "Invalid";
		}
		else
		{
			$json['message']= "";
		}	
		echo json_encode($json['message']);	
	}

}
