<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;
use App\Libraries\Commission;

//require_once(dirname(__DIR__).'/payout.php');
class Masspayout extends BaseController {

	/**
	* 
	* Start 
	* Create Date: 20 August, 2016
	* This controller to manage for user and admin payout.
	* Created saravanan.
	* @see http://zhyip.com/
	* Last Updated: 20 August, 2016
	* End
	* 
	*/

	public function __construct() {
		
		$this->finance_model = model('finance_model');
	}
	
	public function index()
	{
		$this->session = session();
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
		if(!$this->session->get('admin_login'))
			return redirect()->to('admin');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_history')
		);

		$withdraw_data = $this->common_model->GetSettingall('withdraw');
            	
	    foreach ($withdraw_data as $row) {
			$withdata[$row->site_key] = $row->site_value;
		}

		$this->data['page_title'] = lang('language_lang.pending_payouts_history_page_title');
		$this->data['type'] = false;
		$this->data['module_name'] = 'finance';
		$condition = "history.type = 'pool_withdraw_request' AND history.is_delete = '0'";
		$this->data['history'] = $this->finance_model->GetTransactions($condition);
		$this->data['action'] = 'admin/masspayout/pendingwithdraw';
		// echo $this->db->last_query();
		//echo view('admin/finance/pendingwithdraw',$this->data);

		echo view('admin/finance/pending_transfer',$this->data);
	}


	public function pendingpayment()
	{
		$this->session = session();
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
		if(!$this->session->get('admin_login'))
			return redirect()->to('admin');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_history')
		);

		$withdraw_data = $this->common_model->GetSettingall('withdraw');
            	
	    foreach ($withdraw_data as $row) {
			$withdata[$row->site_key] = $row->site_value;
		}

		$this->data['page_title'] = lang('language_lang.pending_payouts_history_page_title');
		$this->data['type'] = false;
		$this->data['module_name'] = 'finance';
		$condition = "history.type = 'withdraw_request' AND history.is_delete = '0'";
		$this->data['history'] = $this->finance_model->GetTransactions($condition);
		$this->data['action'] = 'admin/masspayout/pendingwithdraw';
		echo view('admin/finance/pending_payouts',$this->data);
	}

	public function singleuserpay_internal() 
	{


		

		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$this->session = \Config\Services::session();
		$this->form_validation = \Config\Services::validation();

		$historyid = $myencrypt->decode($this->request->getPost('id'));
		$condition = "historyid = '".$historyid."' AND type='pool_withdraw_request'";
		$history_data = $this->common_model->GetRow('history', $condition);

		$payment_id = $history_data->payment_id;
		$uusersid = $history_data->uusersid;
		$user = $this->common_model->GetUser($uusersid);
		$useremail = $user->email; 
		$fullname = $user->fullname;
		$ac_mode=$history_data->ac_mode;
		$coinid=$history_data->currency;

		$wallet=$history_data->payment_id;

		$condition = "coid ='".$coinid."'";
		$cointable = $this->common_model->GetRow('coin_info',$condition);

		$currency=$cointable->coin_symbol;
		$this->data['history']=$history_data;

		// payout is success
		$withdraw_data = array(
		'type' => "withdrawal_pool",
		"description" => "Transfer Successfully"
		);


		$builder = $this->db->table('history');
		$builder->where('historyid',$historyid);
		$builder->update($withdraw_data);



		if($wallet=='1')
      		$wallet_name='Profit Wallet';
    	else if($wallet=='2')
     		$wallet_name='Reward Wallet';
    	else
      		$wallet_name='Cash Wallet';



		$subject = 'Pool Trade Withdrawal Information';
		$mailid = '38';
		$mail_subject_data = $this->common_model->getMailTemplate($mailid);
		$message  = str_replace('[FIRSTNAME]', $user->fullname, $mail_subject_data->message);
		$message  = str_replace('[TXTAMT]', $history_data->amount, $message);
		$message  = str_replace('[DATE]', $history_data->date, $message);
		$message  = str_replace('[Wallet]', $wallet_name, $message);
		$message  = str_replace('[transid]', $history_data->transactionid, $message);
		$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
		$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
		if($mail_subject_data->status=='1')
		{
			$mail_status = $this->sendmail($user->email, $user->fullname, $subject, $message,$mail_subject_data->from_mail);
		}



		$this->session->setFlashData('success_message', lang('language_lang.payout_method_success_message'));

     }



	 public function singpaywithdraw() 
	{

		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$this->session = \Config\Services::session();
		$this->form_validation = \Config\Services::validation();

		$historyid = $myencrypt->decode($this->request->getPost('id'));
		$condition = "historyid = '".$historyid."' AND type='withdraw_request'";
		$history_data = $this->common_model->GetRow('history', $condition);


	
		$uusersid = $history_data->uusersid;
		$user = $this->common_model->GetUser($uusersid);
		$useremail = $user->email; 
		$fullname = $user->fullname;
		$ac_mode=$history_data->ac_mode;
		$coinid=$history_data->currency;

		$condition = "coid ='".$coinid."'";
		$cointable = $this->common_model->GetRow('coin_info',$condition);

		$currency=$cointable->coin_symbol;
		$this->data['history']=$history_data;

		$withdraw_data = $this->common_model->GetSettingall('withdraw');
            	
	    foreach ($withdraw_data as $row) {
			$withdata[$row->site_key] = $row->site_value;
		}

		
		if($withdata['with_instant']=='on')
		{

			$merchant_info=$this->db->query("select * from payment_controls where payment_key='merchant_email' and payment_id='16'")->getRow();
			$merchant_password=$this->db->query("select * from payment_controls where payment_key='merchant_password' and payment_id='16'")->getRow();
			$get_payment=$this->db->query("select * from payment_controls where payment_key='api_key' and payment_id='16'")->getRow();
			$auth_url='https://api.nowpayments.io/v1/auth';
			$params1 = [
				'email' => $merchant_info->payment_value, // Example amount in USD
				'password' => $merchant_password->payment_value,
			];
			$curl = curl_init($auth_url);
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params1));
			curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($curl, CURLOPT_HTTPHEADER, [
				'Content-Type: application/json'
			]);
			// Execute the cURL request
			$response1 = curl_exec($curl);
			$response1=json_decode($response1,true);
			if(!empty($response1['token']))
			{
				$jwtToken=$response1['token'];
				$apiKey = $get_payment->payment_value;
				$endpoint = 'https://api.nowpayments.io/v1/payout';
				$withdrawals = [
					[
						"address" => $history_data->address,
						"currency" => "usdttrc20",
						"amount" => $history_data->amount,
						"ipn_callback_url" => "https://aiquantification.com/user/login/success"
					]
				];

				$data = [
					"withdrawals" => $withdrawals
				];
				
				$curl = curl_init($endpoint);
				curl_setopt($curl, CURLOPT_POST, true);
				curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl, CURLOPT_HTTPHEADER, [
					'Authorization: Bearer ' . $jwtToken,
					'Content-Type: application/json',
					'x-api-key: ' . $apiKey
				]);
				// Execute the cURL request
				$response = curl_exec($curl);
				if ($response === false) 
				{
					echo 'cURL error: ' . curl_error($curl);
					$this->session->setFlashData('error_message', curl_error($curl));
				}
				else 
				{
					$responseData = json_decode($response, true);
					if (isset($responseData['error'])) {
						echo 'Error: ' . $responseData['error'];
						$this->session->setFlashData('error_message', $responseData['error']);
					} else 
					{
						// Payout created successfully
						$payoutId = $responseData['id'];
						$withdraw_data = array(
							'type' => "withdrawal",
							'order_number'=>$payoutId,
							"description" => "Withdrawal Successfully"
							);
						$builder = $this->db->table('history');
						$builder->where('historyid',$historyid);
						//$builder->update($withdraw_data);

						$subject = 'Withdrawal';
						$mailid = '10';
						$mail_subject_data = $this->common_model->getMailTemplate($mailid);
						$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
						$message  = str_replace('[TXTAMT]', $history_data->amount.''.$currency, $message);
						$message  = str_replace('[WITHDRAWDATE]', date("Y-m-d h:i:sa"), $message);
						$message  = str_replace('[transid]', $history_data->transactionid, $message);
						$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
						$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->userdata('langid')), $message);
						
						if($mail_subject_data->status=='1')
						{
							$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);
						}

						$this->session->setFlashData('success_message', "withdraw Request successfully intitated Payment...");
						
						
					}
				}
				}
				else
				{
					echo $response1['code'].''.$response1['message'];
					$this->session->setFlashData('error_message', $response1['message']);
				}
			}
			else
			{
				$withdraw_data = array(
					'type' => "withdrawal",
					'order_number'=>'0',
					"description" => "Withdrawal Successfully"
					);
				$builder = $this->db->table('history');
				$builder->where('historyid',$historyid);
				$builder->update($withdraw_data);

				$subject = 'Withdrawal';
				$mailid = '10';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
				$message  = str_replace('[TXTAMT]', $history_data->amount.''.$currency, $message);
				$message  = str_replace('[WITHDRAWDATE]', date("Y-m-d h:i:sa"), $message);
				$message  = str_replace('[transid]', $history_data->transactionid, $message);
				$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
				$message  = str_replace('#sitename', site_info_lang('site_name',1), $message);
				
				if($mail_subject_data->status=='1')
				{
					$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);
				}
				$this->session->setFlashData('success_message', "withdraw successfully Approved");

			}

		
		

		
		
     }
	public function singleuserpay() 
	{
		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($this->input->post('id'));
		$condition = "historyid = '".$historyid."' AND type='withdraw_request'";
		$history_data = $this->common_model->GetRow('history', $condition);
		$payment_id = $history_data->payment_id;
		$uusersid = $history_data->uusersid;
		$user = $this->common_model->GetUser($uusersid);
	    $useremail = $user->email; 
	    $fullname = $user->fullname;
	    $ac_mode=$history_data->ac_mode;
	    $coinid=$history_data->currency;

	    $condition = "coid ='".$coinid."'";
		$cointable = $this->common_model->GetRow('coin_info',$condition);


		$currency=$cointable->coin_symbol;
		$this->data['history']=$history_data;

		if($ac_mode=='2')
		{	
	    	// payout is success
			$withdraw_data = array(
				'type' => "withdrawal",
				"description" => "withdraw Amount Paid"
			);
			$this->db->where('historyid',$historyid);
			$query_status = $this->db->update('history',$withdraw_data);



			// sent mail to user
			$subject = 'Withdrawal';
			$mailid = '10';
			$mail_subject_data = $this->common_model->getMailTemplate($mailid);
			$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
			$message  = str_replace('[TXTAMT]', $withdraw_amount.''.$currency, $message);
			$message  = str_replace('[WITHDRAWDATE]', date("Y-m-d h:i:sa"), $message);
			$message  = str_replace('[transid]', $history_data->transactionid, $message);
			$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
			$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->userdata('langid')), $message);
			
			if($mail_subject_data->status=='1')
			{
				$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);
			}
			 
			$this->session->set('success_message', lang('language_lang.payout_method_success_message'));
			
		}
		else
		{


			$pay_mode=$cointable->pay_mode;
 

			if($pay_mode=='5')

				$payment_id='7';
			else
				$payment_id='8';

			$payment_condition = "payment_id = '".$payment_id."'";
			$payments = $this->finance_model->PaymentName($payment_condition);
			$methoname = $payments->payment_name;

			$post_data=array("payment_amount" => $history_data->amount, "payment_account" => $history_data->address, "payment_unit" => strtoupper($currency));


			if($payment_id=='7')
			{
				$success_data = $this->bitcoin($post_data);
			}
			else if($payment_id=='8')
			{
				$success_data = $this->perfectmoney($post_data);
			}

			
			if($success_data=='1')
			{
				$withdraw_data = array(
				'type' => "withdrawal",
				"description" => "withdraw Amount Paid"
			);
				$this->db->where('historyid',$historyid);
				$query_status = $this->db->update('history',$withdraw_data);
			// sent mail to user
			$subject = 'Withdrawal';
			$mailid = '10';
			$mail_subject_data = $this->common_model->getMailTemplate($mailid);
			$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
			$message  = str_replace('[TXTAMT]', $withdraw_amount.''.$currency, $message);
			$message  = str_replace('[WITHDRAWDATE]', date("Y-m-d h:i:sa"), $message);
			$message  = str_replace('[transid]', $history_data->transactionid, $message);
			$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
			$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->userdata('langid')), $message);
			
			if($mail_subject_data->status=='1')
			{
				$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);
			}
			$this->session->set('success_message', lang('language_lang.payout_method_success_message'));

			}
			else
			{
				$this->session->set('error_message',$success_data);
			}



		}
	    
	    

	    

   
		

	}


	public function payment()
	{

		$myencrypt = new MyEncrypt;
		$historyid = $myencrypt->decode($this->input->post('id'));
		$hash=$this->input->post('hash');
		if($hash!='')
		{
			$condition = "historyid = '".$historyid."' AND type='withdraw_request'";
			$history_data = $this->common_model->GetRow('history', $condition);
			$payment_id = $history_data->payment_id;
			$uusersid = $history_data->uusersid;
			$user = $this->common_model->GetUser($uusersid);
		    $useremail = $user->email; 
		    $fullname = $user->fullname;
		    $ac_mode=$history_data->ac_mode;
		    $coinid=$history_data->currency;
		    $condition = "coid ='".$coinid."'";
			$cointable = $this->common_model->GetRow('coin_info',$condition);
			$currency=$cointable->coin_symbol;
			$this->data['history']=$history_data;
			if($ac_mode=='1')
	    	{
		    	// payout is success
				$withdraw_data = array(
					'type' => "withdrawal",
					'transhash' =>$hash,
					"description" => "withdraw Amount Paid"
				);
				$this->db->where('historyid',$historyid);
				$query_status = $this->db->update('history',$withdraw_data);

				// sent mail to user
				$subject = 'Withdrawal';
				$mailid = '10';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[FIRSTNAME]', $fullname, $mail_subject_data->message);
				$message  = str_replace('[TXTAMT]', $withdraw_amount.''.$currency, $message);
				$message  = str_replace('[WITHDRAWDATE]', date("Y-m-d h:i:sa"), $message);
				$message  = str_replace('[transid]', $history_data->transactionid, $message);
				$message  = str_replace('#adminemill', $mail_subject_data->from_mail, $message);
				$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->userdata('langid')), $message);
				
				if($mail_subject_data->status=='1')
				{
					$mail_status = $this->sendmail($useremail, $fullname, $subject, $message,$mail_subject_data->from_mail);
				}
				$this->session->set('success_message', lang('language_lang.payout_method_success_message'));
				echo 1;
				
			}
		}
		else
		{
			$this->session->set('error_message', lang('language_lang.payout_method_error_message'));
			echo 0;
			
		}
	    



	}

	public function Deleterequest() {
		
    	// selected withdraw request row


		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$this->session = \Config\Services::session();
		$this->form_validation = \Config\Services::validation();

		$historyid = $myencrypt->decode($this->request->getPost('id'));
		$text=$this->request->getPost('text');

		$condition = "historyid = '".$historyid."' AND type='pool_withdraw_request'";
		$history_data = $this->common_model->GetRow('history', $condition);

		$condition1 = "depositid = '".$historyid."' AND type='pool_withdraw_fee'";
		$history_data1 = $this->common_model->GetRow('history', $condition1);

		$withdraw_data = array(
				'type' => "token",
				"description" => $text
		);
		//$this->db->where('historyid',$historyid);

		//$query_status = $this->db->update('history',$withdraw_data);


		$builder = $this->db->table('history');
		$builder->where('historyid',$historyid);
		$builder->update($withdraw_data);

		$builder = $this->db->table('history');
		$builder->where('historyid',$history_data1->historyid);
		$builder->delete();

		$this->session->setFlashData('success_message', lang('language_lang.payoutcancel_success_message'));
	 	return redirect()->to('admin/finance/pendingpayouts');
	}


	public function Deleterequest1() {
		
    	// selected withdraw request row

		$session = session();
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();

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

		$historyid = $myencrypt->decode($this->request->getPost('id'));
		$text=$this->request->getPost('text');

		$condition = "historyid = '".$historyid."' AND type='withdraw_request'";
		$history_data = $this->common_model->GetRow('history', $condition);

		$condition1 = "depositid = '".$historyid."' AND type='withdraw_fee'";
		$history_data1 = $this->common_model->GetRow('history', $condition1);

		$withdraw_data = array(
				'type' => "token",
				"description" => $text
		);
		$builder = $this->db->table('history');
		$builder->where('historyid',$historyid);
		$builder->update($withdraw_data);

		/*$builder = $this->db->table('history');
		$builder->where('substatus',$history_data1->historyid);
		$builder->delete();*/
		
		$this->db->table('history')->where('substatus',$historyid)->delete();

		$session->setFlashData('success_message', 'Withdraw Request Rejected Successfully');
	 	//return redirect()->to('admin/finance/pendingwithdraw');
	}

	public function pendingwithdraw() {
		

		
		if($this->input->post()) {
			
			// program running time start
			$this->benchmark->mark('mass_pay_start');

			$myencrypt = new MyEncrypt;

			foreach ($this->input->post('history') as $key => $value) {
				
				$historyid = $myencrypt->decode($value);

				$condition = "historyid = '".$historyid."' AND type='withdraw_request'";
				$history_data = $this->common_model->GetRow('history', $condition);

				$payment_id = $history_data->payment_id;
				$uusersid = $history_data->uusersid;

				$user = $this->common_model->GetUser($uusersid);
			    $useremail = $user->email; 
			    $fullname = $user->fullname;
				
				echo $fullname;
				exit;
				

			}
			

		} else {
			// redirect('finance/pendingpayouts');
		}

	}


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

		$this->session = session();
		$this->common_model = model('CommonModel');
		
		$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;
		}
		
		$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
		
		
		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',$this->session->get('langid')));  
		$mail->AddReplyTo($from_mail,site_info_lang('site_name',$this->session->get('langid')));
		$mail->AddBCC($from_mail, site_info_lang('site_name',$this->session->get('langid')));
		
		$mail->Subject = $subject;
		$mail->msgHTML($message);
		$mail->AddAddress($useremail, $useremail);
		
		if(!$mail->Send()) {
		return false;
		} else {
		return true;
		}
		
	}
	

}