<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Api extends CI_Controller {

	public function __construct() 
	{
		parent::__construct();
		
		$this->load->model('member_model');
    }
	
	public function capital($casino_username = NULL)
	{
		set_time_limit(0);
		
		$capital = 0;
		$query = $this->db->query("SELECT b.package_price FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.casino_username = ? LIMIT 1", array($casino_username));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$capital = $row->package_price;
		}
		
		echo $capital;
	}
	
	public function deposit()
	{
		set_time_limit(0);
		
		$post = file_get_contents('php://input');
		
		if( ! empty($post))
		{
			$output = array(
				'errorCode' => 100, 
				'errorMessage' => '',
			);
				
			$arr = json_decode($post, TRUE);
			
			$secret_key = TW_SECRET_KEY;
			$merchant_id = (isset($arr['merchant_id']) ? trim($arr['merchant_id']) : '');
			$signature = (isset($arr['signature']) ? trim($arr['signature']) : '');
			$username = (isset($arr['username']) ? trim($arr['username']) : '');
			$amount = (isset($arr['amount']) ? trim($arr['amount']) : '');
			
			//Verify merchant
			if($merchant_id == TW_MERCHANT_ID) {
				//Verify signature
				if( ! empty($signature)) {
					$verify_sign = md5($merchant_id . $username . $amount . $secret_key);
						
					if($signature == $verify_sign) {
						if($amount > 0) {
							$query = $this->db->query("SELECT a.member_id, a.username, b.v_unit FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.casino_username = ? LIMIT 1", array($username));
							if($query->num_rows() > 0) {
								$row = $query->row();
								
								$DBdata = array(
									'transaction_type' => 1,
									'payment_method' => 5,
									'currency_id' => 1,
									'transaction_amount' => $amount,
									'to_member_id' => $row->member_id,
									'to_member_username' => $row->username,
									'from_debit_balance' => $row->v_unit,
									'debit_amount' => $amount,
									'to_debit_balance' => ($row->v_unit + $amount),
									'currency_rate' => 1,
									'status' => 1,
									'transaction_date' => time()
								);
								
								$this->db->trans_start();
								
								$this->db->insert('sw_member_topup', $DBdata);
								
								$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
							
								$this->member_model->insert_member_log($row->member_id, LOG_TOPUP, json_encode($DBdata));
								
								$this->db->trans_complete();
								
								$rs = $this->db->trans_status();
								
								if($rs) {
									$output['errorCode'] = 0;
									$output['errorMessage'] = 'Deposited successfully';
								}
								else {
									$output['errorCode'] = 105;
									$output['errorMessage'] = 'Deposite failed';
								}
							}
							else {
								$output['errorCode'] = 103;
								$output['errorMessage'] = 'Invalid username';
							}
						}
						else {
							$output['errorCode'] = 104;
							$output['errorMessage'] = 'Invalid amount';
						}
					}
					else {
						$output['errorCode'] = 102;
						$output['errorMessage'] = 'Invalid signature';
					}
				}
				else {
					$output['errorCode'] = 101;
					$output['errorMessage'] = 'Signature is empty';
				}
			}
			else {
				$output['errorCode'] = 106;
				$output['errorMessage'] = 'Invalid merchant';
			}
			
			//Output
			$this->output
					->set_status_header(200)
					->set_content_type('application/json', 'utf-8')
					->set_output(json_encode($output))
					->_display();
		}
		else
		{
			echo show_404();
		}
		
		exit();
	}
	
	public function fpay_deposit()
	{
		set_time_limit(0);
		
		$post = file_get_contents('php://input');
		
		if( ! empty($post))
		{
			$output = array(
				'errorCode' => 100, 
				'errorMessage' => '',
			);
				
			$arr = json_decode($post, TRUE);
			
			$secret_key = TW_SECRET_KEY;
			$merchant_id = (isset($arr['merchant_id']) ? trim($arr['merchant_id']) : '');
			$signature = (isset($arr['signature']) ? trim($arr['signature']) : '');
			$username = (isset($arr['username']) ? trim($arr['username']) : '');
			$amount = (isset($arr['amount']) ? trim($arr['amount']) : '');
			
			//Verify merchant
			if($merchant_id == TW_MERCHANT_ID) {
				//Verify signature
				if( ! empty($signature)) {
					$verify_sign = md5($merchant_id . $username . $amount . $secret_key);
						
					if($signature == $verify_sign) {
						if($amount > 0) {
							$query = $this->db->query("SELECT a.member_id, a.username, b.v_unit FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.casino_username = ? LIMIT 1", array($username));
							if($query->num_rows() > 0) {
								$row = $query->row();
								
								$currency = $this->member_model->get_currency_rate();
								
								#Populate submitted data
								$DBdata = array(
									'transaction_type' => 1,
									'payment_method' => 6,
									'to_member_id' => $row->member_id,
									'to_member_username' => $row->username,
									'from_debit_balance' => $row->v_unit,
									'debit_amount' => $amount,
									'to_debit_balance' => ($row->v_unit + $amount),
									'transaction_amount' => ($amount * $currency[3]['in']),
									'order_no' => date("Ymdhms").sprintf("%05d", rand(1, 99999)),
									'currency_id' => 3,
									'currency_rate' => $currency[3]['in'],
									'status' => 0,
									'transaction_date' => time()
								);
								
								$this->db->trans_start();
								
								$this->db->insert('sw_member_topup', $DBdata);
								
								$this->member_model->insert_member_log($row->member_id, LOG_TOPUP, json_encode($DBdata));
								
								$this->db->trans_complete();
								
								$rs = $this->db->trans_status();
								
								if($rs) {
									$output['errorCode'] = 0;
									$output['errorMessage'] = 'success';
									$output['order_no'] = $DBdata['order_no'];
								}
								else {
									$output['errorCode'] = 105;
									$output['errorMessage'] = 'failed';
								}
							}
							else {
								$output['errorCode'] = 103;
								$output['errorMessage'] = 'Invalid username';
							}
						}
						else {
							$output['errorCode'] = 104;
							$output['errorMessage'] = 'Invalid amount';
						}
					}
					else {
						$output['errorCode'] = 102;
						$output['errorMessage'] = 'Invalid signature';
					}
				}
				else {
					$output['errorCode'] = 101;
					$output['errorMessage'] = 'Signature is empty';
				}
			}
			else {
				$output['errorCode'] = 106;
				$output['errorMessage'] = 'Invalid merchant';
			}	
			
			//Output
			$this->output
					->set_status_header(200)
					->set_content_type('application/json', 'utf-8')
					->set_output(json_encode($output))
					->_display();
		}
		else
		{
			echo show_404();
		}
		
		exit();
	}
	
	public function fpay_callback()
	{
		set_time_limit(0);
		
		$post = file_get_contents('php://input');
		
		if( ! empty($post))
		{
			$output = array(
				'errorCode' => 100, 
				'errorMessage' => '',
			);
				
			$arr = json_decode($post, TRUE);
			
			$payment_method = 6;
			$secret_key = TW_SECRET_KEY;
			$merchant_id = (isset($arr['merchant_id']) ? trim($arr['merchant_id']) : '');
			$signature = (isset($arr['signature']) ? trim($arr['signature']) : '');
			$order_no = (isset($arr['order_no']) ? trim($arr['order_no']) : '');
			$status = (isset($arr['status']) ? trim($arr['status']) : '');
			
			//Verify merchant
			if($merchant_id == TW_MERCHANT_ID) {
				//Verify signature
				if( ! empty($signature)) {
					$verify_sign = md5($merchant_id . $order_no . $status . $secret_key);
						
					if($signature == $verify_sign) {
						$this->db->trans_start();
						
						if($status == 'success') {
							$this->member_model->update_pending_topup($payment_method, 1, $order_no, '');
						}
						else {
							$this->member_model->update_pending_topup($payment_method, 2, $order_no, '');
						}
						
						$this->db->trans_complete();
								
						$rs = $this->db->trans_status();
						
						if($rs) {
							$output['errorCode'] = 0;
							$output['errorMessage'] = 'success';
						}
						else {
							$output['errorCode'] = 105;
							$output['errorMessage'] = 'failed';
						}
					}
					else {
						$output['errorCode'] = 102;
						$output['errorMessage'] = 'Invalid signature';
					}
				}
				else {
					$output['errorCode'] = 101;
					$output['errorMessage'] = 'Signature is empty';
				}
			}
			else {
				$output['errorCode'] = 106;
				$output['errorMessage'] = 'Invalid merchant';
			}		
			
			//Output
			$this->output
					->set_status_header(200)
					->set_content_type('application/json', 'utf-8')
					->set_output(json_encode($output))
					->_display();
		}
		else
		{
			echo show_404();
		}
		
		exit();
	}
	
	public function fpay_check_status()
	{
		set_time_limit(0);
		
		$query = $this->db->query("SELECT payment_method, order_no, transaction_date FROM sw_member_topup WHERE transaction_type = 1 AND payment_method = 6 AND status = 0 LIMIT 10");
		if($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$current_timespan = time();
				$diff_time = ($current_timespan - $row->transaction_date);
				
				$post = array(
								'username' => PG_FPAY_USERNAME,
								'id' => $row->order_no
							);
					
				$url = PG_FPAY_URL . '/merchant/check_status';

				$curl = curl_init($url);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl, CURLOPT_HEADER, false);
				curl_setopt($curl, CURLOPT_POST, true);
				curl_setopt($curl, CURLOPT_TIMEOUT, 400); 
				curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
				curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data"));

				$response = curl_exec($curl);
				curl_close($curl);
				
				$json_arr = json_decode($response, true);
				
				if($json_arr["status"] === true) {
					if($json_arr["order_status"] == 'completed') {
						$this->member_model->update_pending_topup($row->payment_method, 1, $row->order_no, '');
					}
					else if($diff_time >= 1200 || $json_arr["order_status"] == 'fail') {
						$this->member_model->update_pending_topup($row->payment_method, 2, $row->order_no, '');
					}
				}
				else {
					if($diff_time >= 1200) {
						$this->member_model->update_pending_topup($row->payment_method, 2, $row->order_no, '');
					}
				}
			}
		}
	}
	
	public function pg_deposit($method = NULL)
	{
		set_time_limit(0);
		
		$post = file_get_contents('php://input');
		
		if( ! empty($post))
		{
			$output = array(
				'errorCode' => 100, 
				'errorMessage' => '',
			);
				
			$arr = json_decode($post, TRUE);
			
			$secret_key = TW_SECRET_KEY;
			$merchant_id = (isset($arr['merchant_id']) ? trim($arr['merchant_id']) : '');
			$signature = (isset($arr['signature']) ? trim($arr['signature']) : '');
			$username = (isset($arr['username']) ? trim($arr['username']) : '');
			$amount = (isset($arr['amount']) ? trim($arr['amount']) : '');
			
			//Verify merchant
			if($merchant_id == TW_MERCHANT_ID) {
				//Verify signature
				if( ! empty($signature)) {
					$verify_sign = md5($merchant_id . $username . $amount . $secret_key);
						
					if($signature == $verify_sign) {
						if($amount > 0) {
							$query = $this->db->query("SELECT a.member_id, a.username, b.v_unit FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.casino_username = ? LIMIT 1", array($username));
							if($query->num_rows() > 0) {
								$row = $query->row();
								
								$currency = $this->member_model->get_currency_rate();
								$currency_id = 3;
								
								switch(strtolower($method)) {
									case 'fpay': $payment_method = 6; break;
									case 'gspay': $payment_method = 8; break;
									case 'fastpay': $payment_method = 9; break;
									case 'eeziepay': $payment_method = 10; break;
									case 'onepay': $payment_method = 12; $currency_id = 1;break;
									default: $payment_method = 6; break;
								}
								
								$numbers = range(1, 99999);
								shuffle($numbers);
								$rand_num = array_slice($numbers, 0, 1);
								
								#Populate submitted data
								$DBdata = array(
									'transaction_type' => 1,
									'payment_method' => $payment_method,
									'to_member_id' => $row->member_id,
									'to_member_username' => $row->username,
									'from_debit_balance' => $row->v_unit,
									'debit_amount' => $amount,
									'to_debit_balance' => ($row->v_unit + $amount),
									'transaction_amount' => ($amount * $currency[$currency_id]['in']),
									'order_no' => date("Ymdhms") . $row->member_id . sprintf("%05d", $rand_num[0]),
									'currency_id' => $currency_id,
									'currency_rate' => $currency[$currency_id]['in'],
									'status' => 0,
									'transaction_date' => time()
								);
								
								$this->db->trans_start();
								
								$this->db->insert('sw_member_topup', $DBdata);
								
								$this->member_model->insert_member_log($row->member_id, LOG_TOPUP, json_encode($DBdata));
								
								$this->db->trans_complete();
								
								$rs = $this->db->trans_status();
								
								if($rs) {
									$output['errorCode'] = 0;
									$output['errorMessage'] = 'success';
									$output['order_no'] = $DBdata['order_no'];
								}
								else {
									$output['errorCode'] = 105;
									$output['errorMessage'] = 'failed';
								}
							}
							else {
								$output['errorCode'] = 103;
								$output['errorMessage'] = 'Invalid username';
							}
						}
						else {
							$output['errorCode'] = 104;
							$output['errorMessage'] = 'Invalid amount';
						}
					}
					else {
						$output['errorCode'] = 102;
						$output['errorMessage'] = 'Invalid signature';
					}
				}
				else {
					$output['errorCode'] = 101;
					$output['errorMessage'] = 'Signature is empty';
				}
			}
			else {
				$output['errorCode'] = 106;
				$output['errorMessage'] = 'Invalid merchant';
			}	
			
			//Output
			$this->output
					->set_status_header(200)
					->set_content_type('application/json', 'utf-8')
					->set_output(json_encode($output))
					->_display();
		}
		else
		{
			echo show_404();
		}
		
		exit();
	}
	
	public function pg_callback($method = NULL)
	{
		set_time_limit(0);
		
		$post = file_get_contents('php://input');
		
		if( ! empty($post))
		{
			$output = array(
				'errorCode' => 100, 
				'errorMessage' => '',
			);
				
			$arr = json_decode($post, TRUE);
			
			switch(strtolower($method)) {
				case 'fpay': $payment_method = 6; break;
				case 'gspay': $payment_method = 8; break;
				case 'fastpay': $payment_method = 9; break;
				case 'eeziepay': $payment_method = 10; break;
				case 'onepay': $payment_method = 12; break;
				default: $payment_method = 6; break;
			}
								
			$secret_key = TW_SECRET_KEY;
			$merchant_id = (isset($arr['merchant_id']) ? trim($arr['merchant_id']) : '');
			$signature = (isset($arr['signature']) ? trim($arr['signature']) : '');
			$order_no = (isset($arr['order_no']) ? trim($arr['order_no']) : '');
			$status = (isset($arr['status']) ? trim($arr['status']) : '');
			
			//Verify merchant
			if($merchant_id == TW_MERCHANT_ID) {
				//Verify signature
				if( ! empty($signature)) {
					$verify_sign = md5($merchant_id . $order_no . $status . $secret_key);
						
					if($signature == $verify_sign) {
						$this->db->trans_start();
						
						if($status == 'success') {
							$this->member_model->update_pending_topup($payment_method, 1, $order_no, '');
						}
						else {
							$this->member_model->update_pending_topup($payment_method, 2, $order_no, '');
						}
						
						$this->db->trans_complete();
								
						$rs = $this->db->trans_status();
						
						if($rs) {
							$output['errorCode'] = 0;
							$output['errorMessage'] = 'success';
						}
						else {
							$output['errorCode'] = 105;
							$output['errorMessage'] = 'failed';
						}
					}
					else {
						$output['errorCode'] = 102;
						$output['errorMessage'] = 'Invalid signature';
					}
				}
				else {
					$output['errorCode'] = 101;
					$output['errorMessage'] = 'Signature is empty';
				}
			}
			else {
				$output['errorCode'] = 106;
				$output['errorMessage'] = 'Invalid merchant';
			}		
			
			//Output
			$this->output
					->set_status_header(200)
					->set_content_type('application/json', 'utf-8')
					->set_output(json_encode($output))
					->_display();
		}
		else
		{
			echo show_404();
		}
		
		exit();
	}
	
	public function crypto_deposit()
	{
		set_time_limit(0);
		
		$post = file_get_contents('php://input');
		
		if( ! empty($post))
		{
			$output = array(
				'errorCode' => 100, 
				'errorMessage' => '',
			);
				
			$arr = json_decode($post, TRUE);
			
			$secret_key = PG_TRONGRID_KEY;
			$merchant_id = (isset($arr['merchant_id']) ? trim($arr['merchant_id']) : '');
			$signature = (isset($arr['signature']) ? trim($arr['signature']) : '');
			$username = (isset($arr['username']) ? trim($arr['username']) : '');
			$coin_id = (isset($arr['coin_id']) ? trim($arr['coin_id']) : '');
			$amount = (isset($arr['amount']) ? trim($arr['amount']) : '');
			
			//Verify merchant
			if($merchant_id == PG_TRONGRID_AGENT_ID) {
				//Verify signature
				if( ! empty($signature)) {
					$verify_sign = md5($merchant_id . $username . $coin_id . $amount . $secret_key);
						
					if($signature == $verify_sign) {
						if($coin_id == 1 || $coin_id == 2) {
							if($amount > 0) {
								$query = $this->db->query("SELECT a.member_id, a.username, a.platform_type, b.v_unit FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.username = ? LIMIT 1", array($username));
								if($query->num_rows() > 0) {
									$row = $query->row();
									
									$currency = $this->member_model->get_currency_rate();
									
									switch($coin_id) {
										case 2: $actual_coin_id = 21; $payment_method = 7; break;
										case 1: $actual_coin_id = 5; $payment_method = 4; break;
									}
									
									if($coin_id == 2 && $row->platform_type == 2) {
										$actual_coin_id = 20;
									}
									
									$actual_amount = ($amount / $currency[$actual_coin_id]['in']);
									
									#Populate submitted data
									$DBdata = array(
										'transaction_type' => 1,
										'payment_method' => $payment_method,
										'to_member_id' => $row->member_id,
										'to_member_username' => $row->username,
										'from_debit_balance' => $row->v_unit,
										'debit_amount' => $actual_amount,
										'to_debit_balance' => ($row->v_unit + $actual_amount),
										'transaction_amount' => $amount,
										'order_no' => date("Ymdhms").sprintf("%05d", rand(1, 99999)),
										'currency_id' => $actual_coin_id,
										'currency_rate' => $currency[$actual_coin_id]['in'],
										'status' => 1,
										'transaction_date' => time()
									);
									
									$this->db->trans_start();
									
									$this->db->insert('sw_member_topup', $DBdata);
									
									$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
									
									$this->member_model->insert_member_log($row->member_id, LOG_TOPUP, json_encode($DBdata));
									
									$this->db->trans_complete();
									
									$rs = $this->db->trans_status();
									
									if($rs) {
										$output['errorCode'] = 0;
										$output['errorMessage'] = 'success';
									}
									else {
										$output['errorCode'] = 105;
										$output['errorMessage'] = 'failed';
									}
								}
								else {
									$output['errorCode'] = 103;
									$output['errorMessage'] = 'Invalid username';
								}
							}
							else {
								$output['errorCode'] = 104;
								$output['errorMessage'] = 'Invalid amount';
							}	
						}
						else {
							$output['errorCode'] = 107;
							$output['errorMessage'] = 'Invalid coin id';
						}
					}
					else {
						$output['errorCode'] = 102;
						$output['errorMessage'] = 'Invalid signature';
					}
				}
				else {
					$output['errorCode'] = 101;
					$output['errorMessage'] = 'Signature is empty';
				}
			}
			else {
				$output['errorCode'] = 106;
				$output['errorMessage'] = 'Invalid merchant';
			}	
			
			//Output
			$this->output
					->set_status_header(200)
					->set_content_type('application/json', 'utf-8')
					->set_output(json_encode($output))
					->_display();
		}
		else
		{
			echo show_404();
		}
		
		exit();
	}
	
	public function onepay_check_status()
	{
		set_time_limit(0);
		
		$query = $this->db->query("SELECT payment_method, order_no, transaction_date FROM sw_member_topup WHERE transaction_type = 1 AND payment_method = 12 AND status = 0 LIMIT 10");
		if($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$current_timespan = time();
				$diff_time = ($current_timespan - $row->transaction_date);
				
				$arr = array(
					'appid' => PG_ONEPAY_APP_ID,
					'out_trade_no' => $row->order_no
				);
				
				ksort($arr);
				$SignParams = "";
				foreach ($arr as $key => $val) {
					$SignParams = $SignParams . $key . "=" . $val . "&";
				}
				
				$arr['sign'] = strtoupper(md5($SignParams . "key=" . PG_ONEPAY_KEY));
				$data_string = http_build_query($arr);  
				
				$url = PG_ONEPAY_PAY_URL . '/index/getorder';
				$ch = curl_init($url);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                      
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
				curl_setopt($ch, CURLOPT_TIMEOUT, 60);
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);		
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                    	
				curl_setopt($ch, CURLOPT_HTTPHEADER, 
					array(
						'charset=UTF-8',
						'Content-Type: application/x-www-form-urlencoded'
					)
				);   	
				$response = curl_exec($ch);
				curl_close($ch);
				
				$json_arr = json_decode($response, true);
				
				if(isset($json_arr["code"]) && $json_arr["code"] == 200) {
					if(isset($json_arr['data'][0]['status']) && $json_arr['data'][0]['status'] == 4) {
						$this->member_model->update_pending_topup($row->payment_method, 1, $row->order_no, '');
					}
					else if($diff_time >= 1200 || $json_arr["order_status"] == 'fail') {
						$this->member_model->update_pending_topup($row->payment_method, 2, $row->order_no, '');
					}
				}
				else {
					if($diff_time >= 1200) {
						$this->member_model->update_pending_topup($row->payment_method, 2, $row->order_no, '');
					}
				}
			}
		}
	}
}

/* End of file api.php */
/* Location: ./application/controllers/api.php */