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

class Payout 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() {

	}

	protected function webmoney($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}

	protected function etherum($post_data)	
	{
		$this->common_model = model('CommonModel');
		$payee_account = $post_data['payee_account'];
		$payment_amount = $post_data['payment_amount'];
		$payment_cur = strtoupper($post_data['currency_unit']);
		$condition = "payment_key in('address') AND payment_id = '20'";
		$payment_data = $this->common_model->GetPaymentsName($condition);

		$condition = "payment_key in('private_key') AND payment_id = '20'";
		$payment_data1 = $this->common_model->GetPaymentsName($condition);

		$sender=$payment_data[0]->payment_value;
		$pri=$payment_data1[0]->payment_value;

		$url = "https://api.cryptonator.com/api/ticker/".$payment_cur."-eth";
        $json = file_get_contents($url);
        $data_api = json_decode($json, TRUE);
        $data_amts=$data_api['ticker']['price'];
        $toatalbtc= $data_amts*$data['payment_amount'];

		return false;
		
	}

	protected function solidtrustpay($post_data) {
		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}

	protected function skrill($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}

	protected function pexpay($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}

	protected function perfectmoney($post_data){
		
		$this->common_model = model('CommonModel');

		if($post_data) {

			$condition = "payment_key in('account_number') AND payment_id = '10'";
			$payment_data = $this->common_model->GetPaymentsName($condition);

			foreach ($payment_data as $row) {
				$form_data[$row->payment_key] = $row->payment_value;
			}

			$PassPhrase = 'Arm@123456';
			$login_id = '6401844';
			$payer_account = $form_data['account_number'];
				
			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			
			$f=fopen("https://perfectmoney.is/acct/confirm.asp?AccountID=".$login_id."&PassPhrase=".$PassPhrase."&Payer_Account=".$payer_account."&Payee_Account=".$payee_account."&Amount=".$payment_amount, "rb");


			if($f===false){
				$error_message = 'error openning url';
			}

			
			$out=array(); $out="";
			while(!feof($f)) $out.=fgets($f);
           
			fclose($f);


			// searching for hidden fields
			if(!preg_match_all("/<input name='(.*)' type='hidden' value='(.*)'>/", $out, $result, PREG_SET_ORDER)){
			   $error_message = 'Ivalid output';
			}

			$ar="";
			foreach($result as $item ){
  			     $key=$item[1];
			      $ar=$item[2];
			}


			if($ar) {
				$data = array(
					'payment' => 'perfectmoney',
					'post_content' => json_encode($ar),
					'datetime' => date('Y-m-d H:i:s')
				);
				$this->db->insert('ipn_process', $data);
				return $ar;
			} else {

				$data = array(
					'payment' => 'perfectmoney',
					'post_content' => $error_message.' '.$out,
					'datetime' => date('Y-m-d H:i:s')
				);
				$this->db->insert('ipn_process', $data);
				return FALSE;
			}

		}
	}

	protected function payza($post_data) {

		if($post_data) {

			// print_r($post_data);

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);
		
			$PaymentMerchantPassword = 'Arm@123456';
			$PaymentMerchantApi = 'yanceyker89@gmail.com';
			$PaymentMerchantKey = 'bxV1iiE3QosdNjLu';

			// $this->load->library('MassPayClient');
			$payza = new MassPayClient($PaymentMerchantApi,$PaymentMerchantPassword);

			$payer_amount = str_replace(",","",number_format($payment_amount,2));
			$payments[0]['receiver'] = $payee_account;
			$payments[0]['amount'] = $payer_amount;
			$payments[0]['note'] = 'You Withdraw request is payout';

			$post_data = $payza->buildPostVariables($payments, $payment_cur);

			$send_payment = $payza->send();
			$payza->parseResponse($send_payment);
			$send_payment1 = $payza->getResponse();
			
			if($send_payment1['RETURNCODE']==100) {
				
				return $send_payment1;
				
			} else {

				$data = array(
					'payment' => 'payza',
					'post_content' => 'failure'.json_encode($send_payment1),
					'datetime' => date('Y-m-d H:i:s')
				);
				$this->db->insert('ipn_process', $data);
				
			}
			exit;
		}
	}

	protected function paypal($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = number_format($post_data['payment_amount'],2);

			$PaymentMerchantPassword = 'WB8NCKEJM2BN2D5X';
			$PaymentMerchantApi = 'phpbalamurugan-facilitator_api1.gmail.com';
			$PaymentMerchantKey = 'AFcWxV21C7fd0v3bYYYRCpSSRl31AaJQwBXY1IwIGYQ3wBJvT0BYNW0H';

			$this->load->library('PaypalApi');
			$paypal = new PaypalApi($PaymentMerchantApi, $PaymentMerchantPassword, $PaymentMerchantKey);

			$send_payment = $paypal->pay($payee_account, $payment_amount, "You Withdraw request is payout");
			// print_r($send_payment);
			
			if("SUCCESS" == strtoupper($send_payment["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($send_payment["ACK"])) {

				$data = array(
					'payment' => 'paypal',
					'post_content' => 'success'.json_encode($send_payment),
					'datetime' => date('Y-m-d H:i:s')
				);
				$this->db->insert('ipn_process', $data);

				return $send_payment;

			} else {

				$data = array(
					'payment' => 'paypal',
					'post_content' => 'failure'.json_encode($send_payment),
					'datetime' => date('Y-m-d H:i:s')
				);
				$this->db->insert('ipn_process', $data);
				
			}
		}
	}

	protected function payeer($post_data){

		if($post_data) {

			//list of payouts
			$payouts = $this->input->post('payouts');
			$accountNumber = 'P33860849';
			$apiId = '212991180';
			$apiKey = 'MonD0NmEJ8IvqJdN';

			$this->load->library('CPayeer');
			$payeer = new CPayeer($accountNumber,$apiId,$apiKey);

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			// $payment_amount = '0.01';
			$payment_cur = strtoupper($post_data['currency_unit']);

			$currency_up=strtolower($payment_cur);
			
			if ($payeer->isAuth())
			{
				$initOutput = $payeer->initOutput(array(
					'ps' => $payee_account,
					'sumIn' => $payment_amount,
					'curIn' => $payment_cur,
					'sumOut' => $payment_amount,
					'curOut' => $payment_cur,
					'param_ACCOUNT_NUMBER' => $accountNumber
				));

				if ($initOutput)
				{
					$historyId = $payeer->output();
					if ($historyId > 0)
					{
						return $historyId;
					}
					else
					{
						$data = array(
							'payment' => 'payeer',
							'post_content' => 'failure'.json_encode($payeer->getErrors()),
							'datetime' => date('Y-m-d H:i:s')
						);
						$this->db->insert('ipn_process', $data);
						
					}
				}
				else
				{
					$data = array(
						'payment' => 'payeer',
						'post_content' => 'Not Auth'.json_encode($payeer->getErrors()),
						'datetime' => date('Y-m-d H:i:s')
					);
					$this->db->insert('ipn_process', $data);
				}
			}
			else
			{
				$data = array(
					'payment' => 'payeer',
					'post_content' => 'Not Auth2'.json_encode($payeer->getErrors()),
					'datetime' => date('Y-m-d H:i:s')
				);
				$this->db->insert('ipn_process', $data);
			}

		} else {
			redirect('user/withdraw');
		}
	}

	protected function okpay($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}

	protected function hdmoney($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}

	protected function bitcoin($data,$mode='',$coin='')
	 {
	 	
		if($mode=='block')
		{
			if($data)
			{	

				$condition = "payment_key in('api_key','ipn_secret_block') AND payment_id = '2'";
				$payment_data = $this->common_model->GetPaymentsName($condition);

				foreach ($payment_data as $row) {
					// $myencrypt->decode()
					$form_data[$row->payment_key] = $row->payment_value;
				}
					
					$getcurrency = $this->db->query("select * from coin_info where coid = '".$data['currency_unit']."'");
					$Get = $getcurrency->result();
					if(strtoupper($Get[0]->coin_symbol)!='BTC')
					{
						$getfilecompare = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=".strtoupper($Get[0]->coin_symbol)."&tsyms=BTC");
                		$getval  = json_decode($getfilecompare,TRUE);
                		$calbtc  = $getval['BTC'];
                		$orignal_amt = $calbtc * $data['payment_amount']; 	


					}
					else
					{
						$orignal_amt = $data['payment_amount'];
					}

				$accountid = $form_data['api_key'];				
				$secret    = $form_data['ipn_secret_block'];
				$json_url  = 'https://block.io/api/v2/withdraw?api_key='.$accountid.'&amounts='.$orignal_amt.'&to_addresses='.$data['payee_account'].'&pin='.$secret;

				$ch =  curl_init($json_url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
				curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
				curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
				$payout_data = curl_exec($ch);				

				if($payout_data) 
				{
					$json_data = json_decode($payout_data);
					$json_data1 = json_encode($payout_data);					
					if($json_data) 
					{
						if($json_data->status=='success') 
						{
							$ipn_data = array(
							'payment' => 'bitcoin',
							'post_content' => ($json_data1!="" ? $json_data1 : ''),
							'datetime' => date('Y-m-d H:i:s')
							);

							$this->db->insert('ipn_process', $ipn_data);

							$txid = array(
								'transhash' => $json_data->data->txid,
								'btc_amount' => $orignal_amt
								);
							$this->db->where('historyid = "'.$data['history_id'].'"');		
							$this->db->update('history', $txid);					

							return TRUE;
						}
						else
						{
							$ipn_data = array(
							'payment' => 'bitcoin',
							'post_content' => ($json_data1!="" ? $json_data1 : ''),
							'datetime' => date('Y-m-d H:i:s')
							);
							$this->db->insert('ipn_process', $ipn_data);
			        		return FALSE;
						}
					}
					else
					{
						$ipn_data = array(
						'payment' => 'bitcoin',
						'post_content' => 'Unable to parse JSON result ('.json_last_error().')',
						'datetime' => date('Y-m-d H:i:s')
						);
						$this->db->insert('ipn_process', $ipn_data);
						return FALSE;
					}
				}
				else
				{
					$ipn_data = array(
					'payment' => 'bitcoin',
					'post_content' => 'cURL error: '.curl_error($ch),
					'datetime' => date('Y-m-d H:i:s')
					);
					$this->db->insert('ipn_process', $ipn_data);
					return FALSE;
				}
			}
			else
			{
				return FALSE;
			}		

		}
		else
		{
			if($data) 
			{
			
				$condition = "payment_key in('public_key','private_key') AND payment_id = '7'";
				$payment_data = $this->common_model->GetPaymentsName($condition);

				foreach ($payment_data as $row) {
					// $myencrypt->decode()
					$form_data[$row->payment_key] = $row->payment_value;
				}

				$url ='https://blockchain.info/tobtc?currency=USD&value='.$data['payment_amount'];
				$content = file_get_contents($url);
				$json = json_decode($content, true);
				$toatalbtc = number_format($json,8);
				// Set the API command and required fields 
			    $req['version'] = 1; 
			    $req['cmd'] = 'create_withdrawal';
			    $req['key'] = $form_data['public_key']; 
			    $req['amount'] = $toatalbtc;
			    $req['currency'] = 'BTC';
			    $req['address'] = $data['payee_account'];
			    $req['format'] = 'json';
			    $mt = explode(' ', microtime());
				$req['nonce'] = $mt[1].substr($mt[0], 2, 6);
				// Generate the query string 
		    	$post_data = http_build_query($req, '', '&'); 
		    	// Calculate the HMAC signature on the POST data 
		    	$hmac = hash_hmac('sha512', $post_data, $form_data['private_key']); 
		    	// Create cURL handle and initialize (if needed) 
		    	static $ch = NULL; 
		    	if ($ch === NULL) 
		    	{ 
		        	$ch = curl_init('https://www.coinpayments.net/api.php'); 
		        	curl_setopt($ch, CURLOPT_FAILONERROR, TRUE); 
		        	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
		        	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
		    	} 
		    	curl_setopt($ch, CURLOPT_HTTPHEADER, array('HMAC: '.$hmac)); 
		    	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 
		    	// Execute the call and close cURL handle      
		    	$data = curl_exec($ch);                 
		   		 // Parse and return data if successful. 
		    	if ($data !== FALSE) { 
		        if (PHP_INT_SIZE < 8 && version_compare(PHP_VERSION, '5.4.0') >= 0) {
		            $dec = json_decode($data, TRUE, 512, JSON_BIGINT_AS_STRING); 
		        } else { 
		            $dec = json_decode($data, TRUE); 
		        }

		        if ($dec !== NULL && count($dec)) {
			        if($dec['error']=='ok'){
			        	return TRUE;
			        	
			        } else {
			        	$ipn_data = array(
							'payment' => 'bitcoin',
							'post_content' => json_encode($dec),
							'datetime' => date('Y-m-d H:i:s')
						);
						$this->db->insert('ipn_process', $ipn_data);
			        	return $dec['error'];
			        	}
		        	
		        	} 
		        	else 
		        	{
		        		$ipn_data = array(
						'payment' => 'bitcoin',
						'post_content' => 'Unable to parse JSON result ('.json_last_error().')',
						'datetime' => date('Y-m-d H:i:s')
						);
						$this->db->insert('ipn_process', $ipn_data);
						return $dec['error'];
		        	} 
		    	} 	
		    	else 
		    	{ 
		    		$ipn_data = array(
					'payment' => 'bitcoin',
					'post_content' => 'cURL error: '.curl_error($ch),
					'datetime' => date('Y-m-d H:i:s')
					);
					$this->db->insert('ipn_process', $ipn_data);
					return $dec['error'];
		    	}
			
			} 
			else
			{
				return FALSE;
			}
		}

	}

	protected function advcash($data) {

		$condition = "payment_key in('ac_account_email','ac_sci_name','ac_api_pwd') AND payment_id = '13'";
		$payment_data = $this->common_model->GetPaymentsName($condition);

		foreach ($payment_data as $row) {
			$form_data[$row->payment_key] = $row->payment_value;
		}

		$payment_cur = ($data['currency_unit']) ? strtoupper($data['currency_unit']) : 'USD';

		$ac_account_email = $form_data['ac_account_email'];
		$ac_sci_name = $form_data['ac_sci_name'];
		$secret = $form_data['ac_api_pwd'];
		
		$this->load->library('MerchantWebService');
		$merchantWebService = new MerchantWebService();

		$arg0 = new authDTO();
		$arg0->apiName = $ac_sci_name;
		$arg0->accountEmail = $ac_account_email;
		$arg0->authenticationToken = $merchantWebService->getAuthenticationToken($secret);


		$arg1 = new sendMoneyRequest();
		$arg1->amount = $data['payment_amount'];
		$arg1->currency = $payment_cur;
		// $arg1->email = "receiver_email";
		// $arg1->walletId = "U000000000000";
		$arg1->walletId = $data['payee_account'];
		$arg1->note = "note";
		$arg1->savePaymentTemplate = false;

		$validationSendMoney = new validationSendMoney();
		$validationSendMoney->arg0 = $arg0;
		$validationSendMoney->arg1 = $arg1;

		$sendMoney = new sendMoney();
		$sendMoney->arg0 = $arg0;
		$sendMoney->arg1 = $arg1;

		try {
		    $merchantWebService->validationSendMoney($validationSendMoney);
		    $sendMoneyResponse = $merchantWebService->sendMoney($sendMoney);
		    
		    $ipn_data = array(
				'payment' => 'bitcoin',
				'post_content' => 'SUCCESS: '.$sendMoneyResponse->return,
				'datetime' => date('Y-m-d H:i:s')
			);
			$this->db->insert('ipn_process', $ipn_data);
			return $sendMoneyResponse->return;
		} catch (Exception $e) {
		    $ipn_data = array(
				'payment' => 'bitcoin',
				'post_content' => 'ERROR: '.$e->getMessage().' Trance'.$e->getTraceAsString(),
				'datetime' => date('Y-m-d H:i:s')
			);
			$this->db->insert('ipn_process', $ipn_data);
			return FALSE;
		}
				 
	}

	protected function bankwire($post_data) {

		if($post_data) {

			$payee_account = $post_data['payee_account'];
			$payment_amount = $post_data['payment_amount'];
			$payment_cur = strtoupper($post_data['currency_unit']);

			return false;
		}
	}


	protected function sendmail($useremail, $fullname, $subject, $message, $toadmin='') {

		$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'];   
		}


		$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);

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

		if($toadmin) {

			$mail->SetFrom($useremail, $fullname);  
        	$mail->AddReplyTo($useremail, $fullname);
        	$mail->AddAddress($mail_data['admin_email'], site_info_lang('site_name',$this->session->userdata('langid')));

		} else {

			$mail->SetFrom($mail_data['admin_email'], site_info_lang('site_name',$this->session->userdata('langid')));  
        	$mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',$this->session->userdata('langid')));
        	$mail->AddAddress($useremail, $fullname);

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


	protected function sendmail1($useremail, $fullname, $subject, $message, $toadmin='') {

		$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->isSendmail();

		} 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'];   
		}


		$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);

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

		if($toadmin) {

			$mail->SetFrom($useremail, $fullname);  
        	$mail->AddReplyTo($useremail, $fullname);
        	$mail->AddAddress($mail_data['admin_email'], site_info_lang('site_name',$this->session->userdata('langid')));

		} else {

			$mail->SetFrom($mail_data['admin_email'], site_info_lang('site_name',$this->session->userdata('langid')));  
        	$mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',$this->session->userdata('langid')));
        	$mail->AddAddress($useremail, $fullname);

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



}