<?php

class Member_Model extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function insert_member_log($member_id = NULL, $log_type = NULL, $user_data = NULL)
    {
        #Populate submitted data
		$DBdata = array(
		   'member_id' => $member_id,
		   'log_type' => $log_type,
		   'ip_address' => $this->input->ip_address(),
		   'user_agent' => substr($this->input->user_agent(), 0, 120),
		   'log_date' => time(),
		   'user_data' => $user_data
		);
		
		$this->db->insert('sw_member_logs', $DBdata);
    }
	
	function get_member_account_details()
    {
        $query = $this->db->query("SELECT a.*, b.v_unit, b.v_unit2, b.v_unit3, b.v_unit4 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.member_id = ? LIMIT 1", array($this->session->userdata('member_id')))->row_array();
	    
	    return $query;
    }
	
	function get_member_insurance_status()
	{
		$status = 0;
		$insurance_date = date('Y-m-d');
		$query = $this->db->query("SELECT member_transaction_id FROM sw_member_buy_insurances WHERE from_member_id = ? AND insurance_date = ? LIMIT 1", array($this->session->userdata('member_id'), $insurance_date));
		if($query->num_rows() > 0) {
			$status = 1;
		}
		
		return $status;
	}
	
	function register_member()
	{
		$this->lang->load('account_general', get_language());
	
		$password = trim($this->input->post('password', TRUE));
		$confirm_password = trim($this->input->post('confirm_password', TRUE));
		$security_password = $password;
		$confirm_security_password = $password;
		
        #Populate submitted data
	    $DBdata = array(
			'username' => strtolower(trim($this->input->post('username', TRUE))),
			'password_origin' => $password,
			'password' => sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key'))))),
			'security_password_origin' => $security_password,
			'security_password' => sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'package_type' => 0,
			'origin_package_type' => 0,
			'nationality' => trim($this->input->post('nationality', TRUE)),
			'country' => trim($this->input->post('nationality', TRUE)),
			'bank_country' => trim($this->input->post('nationality', TRUE)),
			'contract_start_date' => time(),
			'contract_expiry_date' => strtotime('+' . TENURE_CONTRACT . ' days', time()),
			'active' => 0,
			'member_type' => 2,
			'introducer' => strtolower(trim($this->input->post('introducer', TRUE))),
			'allowed_withdraw' => 1,
			'unlimited_withdraw' => 0,
			'allowed_transfer' =>  1,
			'allowed_convert' =>  1,
			'allowed_topup' => 1,
			'platform_type' => 1,
			'is_claim_only' => 0,
			'registered_by' => $this->session->userdata('member_username'),
			'registered_date' => time()
    	);
		
		#Data validation
		if($DBdata['username'] == '') {
    		return $this->lang->line('registration_username_must_fill_in_message');
		}
		else if( ! preg_match('/^[a-zA-Z0-9_]{3,32}$/', $DBdata['username'])) {
			return $this->lang->line('registration_invalid_username_format_message');
		}
		
		#Check for username availbility
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? LIMIT 1", array($DBdata['username']));
		if($query->num_rows() > 0) {
			return $this->lang->line('registration_username_unavailable_message');
		}
		
		if($password == '') {
    		return $this->lang->line('registration_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/", $password)) {
			return $this->lang->line('registration_invalid_password_format_message');
		} 
		else if ($password != $confirm_password) {
			return $this->lang->line('registration_confirm_password_not_match_message');
		} 
		else if($security_password == '') {
    		return $this->lang->line('registration_security_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/", $security_password)) {
			return $this->lang->line('registration_invalid_security_password_format_message');
		} 
		else if ($security_password != $confirm_security_password) {
			return $this->lang->line('registration_confirm_security_password_not_match_message');	
		}
		
		#Check for introducer availbility
		$query = $this->db->query("SELECT member_id, introducer_parent_ref FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($DBdata['introducer'], 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			if(empty($row->introducer_parent_ref)) {
				$DBdata['introducer_parent_ref'] = ',' . $row->member_id . ',';
			}
			else {
				$DBdata['introducer_parent_ref'] = $row->introducer_parent_ref . $row->member_id . ',';
			}
			
			// #Get platform type
			// $s_arr = explode(',', $DBdata['introducer_parent_ref']);
			// if(in_array(13, $s_arr)) {
				// $DBdata['platform_type'] = 2;
			// }
			// else if(in_array(14, $s_arr)) {
				// $DBdata['is_claim_only'] = 1;
			// }
		}
		else {
			return $this->lang->line('registration_introducer_unavailable_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_members', $DBdata);
		$db_data['member_id'] = $this->db->insert_id();
		
		$this->db->insert('sw_member_wallets', $db_data);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_ADD_MEMBER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
	}
	
	function get_member_invest()
	{
		$query = $this->db->query("SELECT reinvest_package_type, reinvest_package_date FROM sw_member_reinvest WHERE member_id = ? ORDER BY member_reinvest_id DESC LIMIT 100", array($this->session->userdata('member_id')));
		
		return $query;
	}
	
	function get_direct_downlines()
	{
		$query = $this->db->query("SELECT count(member_id) AS total FROM sw_members WHERE introducer = ? AND member_type = ? AND active = ? ORDER BY registered_date DESC", array($this->session->userdata('member_username'), 2, 1))->row_array();
		
		return $query;
	}
	
	function get_all_downlines()
	{
		$query = $this->db->query("SELECT count(a.member_id) AS total, SUM(b.package_price) AS sales FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.member_type = 2 AND a.active = 1 AND a.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%'")->row_array();
		
		return $query;
	}
	
	function check_security_password()
	{
		$security_password = trim($this->input->post('security_password', TRUE));
		
		#Check for existing security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password));
		if($query->num_rows() > 0) {
			return TRUE;
		}
		else {
			return FALSE;
		}
	}
	
	function get_downlines()
	{
		$arr['level_1'] = array();
		$arr['level_2'] = array();
		$arr['level_3'] = array();
		$max_level = 0;
		$parent_id = $this->session->userdata('member_id');
		
		$query = $this->db->query("SELECT ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) AS level FROM sw_members a LEFT JOIN sw_members b ON a.introducer = b.username WHERE a.member_id = ? LIMIT 1", array($parent_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			if($row->level > 0) {
				$max_level = ($row->level + 3);
			}
			else {
				$max_level = (1 + 3);
			}
		}	
		
		$query = $this->db->query("SELECT LOWER(a.username) AS username, ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) AS level FROM sw_members a LEFT JOIN sw_members b ON a.introducer = b.username WHERE a.introducer_parent_ref LIKE '%,$parent_id,%' AND ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) <= $max_level ORDER BY ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) ASC");
		if($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				if(($max_level - $row->level) == 2) {
					array_push($arr['level_1'], array('username' => $row->username));
				}
				else if(($max_level - $row->level) == 1) {
					array_push($arr['level_2'], array('username' => $row->username));
				}
				else if(($max_level - $row->level) == 0) {
					array_push($arr['level_3'], array('username' => $row->username));
				}
			}
		}	
		
		return $arr;
	}
	
	function get_small_area_sales()
	{
		$parent_id = $this->session->userdata('member_id');
		
		//Prepare member list
		$member_lists = array();	
		$member_query = $this->db->query("SELECT member_id, package_value FROM sw_members WHERE member_id = $parent_id OR introducer_parent_ref LIKE '%,$parent_id,%'");
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				$member_lists[$member_row->member_id] = array('total_sales' => $member_row->package_value);
			}
		}
		
		//Prepare group sales
		$member_query = $this->db->query("SELECT package_value, introducer_parent_ref FROM sw_members WHERE member_id = $parent_id OR introducer_parent_ref LIKE '%,$parent_id,%'");
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				if($member_row->introducer_parent_ref != '') {
					$arr = explode(',', $member_row->introducer_parent_ref);
					
					for($i=0; $i<sizeof($arr); $i++) {
						if($arr[$i] != '' AND $arr[$i] > 0) {
							$member_lists[$arr[$i]]['total_sales'] = ($member_lists[$arr[$i]]['total_sales'] + $member_row->package_value);
						}
					}
				}
			}
		}
		
		//Get small area sales
		$small_area_sales = 0;
		$member_query = $this->db->query("SELECT member_id FROM sw_members WHERE introducer = ?", array($this->session->userdata('member_username')));
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				if($member_lists[$member_row->member_id]['total_sales'] < $small_area_sales || $small_area_sales == 0) {
					$small_area_sales = $member_lists[$member_row->member_id]['total_sales'];
				}
			}
		}
		
		return $small_area_sales;
	}
	
	function get_member_total_income()
	{
		$total = 0;
		$query = $this->db->query("SELECT SUM(v_unit2) AS total FROM sw_member_income_summary WHERE member_id = ?", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$total = ($total + $row->total);
		}
		
		$query = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 2));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$total = ($total - $row->total);
		}
		
		return $total;
	}
	
	function get_member_today_income()
	{
		$total = 0;
		$today_date = date('Y-m-d');
		$query = $this->db->query("SELECT SUM(v_unit2) AS total FROM sw_member_income_summary WHERE member_id = ? AND income_date = ? LIMIT 1", array($this->session->userdata('member_id'), $today_date));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$total = ($total + $row->total);
		}
		
		$start_date = strtotime(date('Y-m-d 00:00:00'));
		$end_date = strtotime(date('Y-m-d 23:59:59'));
		$query = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_type = ? AND transaction_date >= ? AND transaction_date <= ?", array($this->session->userdata('member_id'), 2, $start_date, $end_date));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$total = ($total - $row->total);
		}
		
		return $total;
	}
	
	function get_member_topup_package()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_topup_package WHERE from_member_id = ?", array($this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'buy/index/';
		$config['uri_segment'] = 3;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT transaction_type, transaction_date, credit_amount, transaction_amount, status FROM sw_member_topup_package WHERE from_member_id = ? ORDER BY member_transaction_id DESC $sql", array($this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_member_convert()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_converts WHERE from_member_id = ?", array($this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'convert/index/';
		$config['uri_segment'] = 3;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT transaction_type, transaction_date, credit_amount, debit_amount, status FROM sw_member_converts WHERE from_member_id = ? ORDER BY member_transaction_id DESC $sql", array($this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_member_transfer()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM (SELECT member_transaction_id FROM sw_member_transfers WHERE from_member_id = ? AND (transaction_type = 1 OR transaction_type = 4) UNION ALL SELECT member_transaction_id FROM sw_member_transfers WHERE to_member_id = ? AND (transaction_type = 1 OR transaction_type = 4)) x", array($this->session->userdata('member_id'), $this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'transfer/index/';
		$config['uri_segment'] = 3;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT * FROM (SELECT member_transaction_id, transaction_type, to_member_username AS username, transaction_date, credit_amount As amount, status, 1 AS type FROM sw_member_transfers WHERE from_member_id = ? AND (transaction_type = 1 OR transaction_type = 4) UNION ALL SELECT member_transaction_id, transaction_type, from_member_username AS username, transaction_date, debit_amount As amount, status, 2 AS type FROM sw_member_transfers WHERE to_member_id = ? AND (transaction_type = 1 OR transaction_type = 4)) x ORDER BY transaction_date DESC, member_transaction_id DESC $sql", array($this->session->userdata('member_id'), $this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_member_topup()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM (SELECT member_transaction_id FROM sw_member_topup WHERE to_member_id = ? AND transaction_type IN (1,3) UNION ALL SELECT member_transaction_id FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_type IN (1,3)) x", array($this->session->userdata('member_id'), $this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'topup/index/';
		$config['uri_segment'] = 3;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT * FROM (SELECT member_transaction_id, transaction_type, payment_method, to_member_username, transaction_date, remark_2, from_debit_balance AS cash_in, to_debit_balance AS cash_out, debit_amount AS amount, status, 1 AS type FROM sw_member_topup WHERE to_member_id = ? AND transaction_type IN (1,3) UNION ALL SELECT member_transaction_id, transaction_type, 0 AS payment_method, to_member_username, transaction_date, remark_2, from_credit_balance AS cash_in, to_credit_balance AS cash_out, credit_amount AS amount, status, 2 AS type FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_type IN (1,3)) x ORDER BY transaction_date DESC, member_transaction_id DESC $sql", array($this->session->userdata('member_id'), $this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_member_withdrawal()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND transaction_type = 1", array($this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'withdrawal/index/';
		$config['uri_segment'] = 3;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT currency_id, from_member_username, transaction_date, credit_amount, currency_rate, charges, withdrawal_amount, status FROM sw_member_withdraw WHERE from_member_id = ? AND transaction_type = 1 ORDER BY member_transaction_id DESC $sql", array($this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_member_buy_insurance()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_buy_insurances WHERE from_member_id = ?", array($this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'insurance/index/';
		$config['uri_segment'] = 3;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['buy_list_pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT insurance_date, credit_amount, status FROM sw_member_buy_insurances WHERE from_member_id = ? ORDER BY member_transaction_id DESC $sql", array($this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_member_claim_insurance()
	{
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_claim_insurances WHERE from_member_id = ?", array($this->session->userdata('member_id')))->row();
		$data['total_rows'] = $query->total;
		
		$config['base_url'] = base_url() . 'insurance/index/claim/';
		$config['uri_segment'] = 4;
		$config['total_rows'] = $data['total_rows'];
		$config['per_page'] = 20;
		$config['cur_page'] = 0;
			
		$this->pagination->initialize($config);
			
		$data['claim_list_pagination'] = $this->pagination->create_links();
		
		$sql = '';
		if($data['total_rows'] > 0) {	
			if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])) && $this->uri->segment(3) == 'claim')
				$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
			else 
				$sql = ' LIMIT 0, ' . $config['per_page'];
		}
		
		$data['query'] = $this->db->query("SELECT transaction_date, claim_amount, remark, claim_slip_1, claim_slip_2, claim_slip_3, claim_slip_4, claim_slip_5, claim_slip_6, status FROM sw_member_claim_insurances WHERE from_member_id = ? ORDER BY member_transaction_id DESC $sql", array($this->session->userdata('member_id')));
		
		return $data;
	}
	
	function get_setting_rates()
	{
		$query = $this->db->query("SELECT * FROM sw_setting LIMIT 1")->row_array();
	    
	    return $query;
	}
	
	function change_login_password()
    {
		$this->lang->load('account_general', get_language());
	
		$old_password = trim($this->input->post('old_login_password', TRUE));
		$new_password = trim($this->input->post('login_password', TRUE));
		$confirm_password = trim($this->input->post('confirm_login_password', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'password_origin' => $new_password,
			'password' => sha1(md5(sha1(md5($new_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
    	);
		
		#Data validation
		if($old_password == '') {
    		return $this->lang->line('profile_old_password_must_fill_in_message');
    	}
		else if($new_password == '') {
    		return $this->lang->line('profile_new_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$new_password)) {
			return $this->lang->line('profile_new_password_format_message');
    	}
		else if($new_password != $confirm_password) {
    		return $this->lang->line('profile_new_password_not_match_message');
    	}
		
		#Check for existing password
		$encrypted_password = sha1(md5(sha1(md5($old_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND password = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('profile_invalid_old_password_message');
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CHANGE_LOGIN_PASSWORD, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function change_security_password()
    {
		$this->lang->load('account_general', get_language());
	
		$old_password = trim($this->input->post('old_security_password', TRUE));
		$new_password = trim($this->input->post('security_password', TRUE));
		$confirm_password = trim($this->input->post('confirm_security_password', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'security_password_origin' => $new_password,
			'security_password' => sha1(md5(sha1(md5($new_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
    	);
		
		#Data validation
		if($old_password == '') {
    		return $this->lang->line('profile_old_password_must_fill_in_message');
    	}
		else if($new_password == '') {
    		return $this->lang->line('profile_new_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$new_password)) {
			return $this->lang->line('profile_new_password_format_message');
    	}
		else if($new_password != $confirm_password) {
    		return $this->lang->line('profile_new_password_not_match_message');
    	}
		
		#Check for existing security password
		$encrypted_password = sha1(md5(sha1(md5($old_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('profile_invalid_old_password_message');
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CHANGE_SECURITY_PASSWORD, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function update_profile()
    {
		$this->lang->load('account_general', get_language());
		
		$disclaimer = trim($this->input->post('disclaimer', TRUE));
		
		#Populate submitted data
		$DBdata = array(
			'full_name' => trim($this->input->post('full_name', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			'wallet_address' => trim($this->input->post('wallet_address', TRUE)),
			'is_profile_locked' => 1,
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
		);
	
		// if($this->session->userdata('member_platform_type') == 1 && ($this->session->userdata('member_country') == 'CN' || $this->session->userdata('member_country') == 'HK' || $this->session->userdata('member_country') == 'MY')) {
			$DBdata['account_holder_name'] = trim($this->input->post('account_holder_name', TRUE));
			$DBdata['bank_name'] = trim($this->input->post('bank_name', TRUE));
			$DBdata['bank_account_no'] = trim($this->input->post('bank_account_no', TRUE));
			$DBdata['bank_address'] = trim($this->input->post('bank_address', TRUE));
			$DBdata['bank_country'] = trim($this->input->post('bank_country', TRUE));
			
			#Data validation
			if($DBdata['account_holder_name'] == '') {
				return $this->lang->line('registration_account_holder_name_must_fill_in_message');
			}
			else if($DBdata['bank_name'] == '') {
				return $this->lang->line('registration_bank_name_must_fill_in_message');
			}
			else if($DBdata['bank_account_no'] == '') {
				return $this->lang->line('registration_bank_account_no_must_fill_in_message');
			}
			// else if($DBdata['bank_address'] == '') {
				// return $this->lang->line('registration_bank_address_must_fill_in_message');
			// }
		// }
		
		#Data validation
		if($DBdata['wallet_address'] == '') {
			if($this->session->userdata('member_platform_type') == 2) {
				return $this->lang->line('registration_ping_wallet_address_must_fill_in_message');
			}
			else {
				return $this->lang->line('registration_usdt_wallet_address_must_fill_in_message');
			}
		}
		else if($DBdata['full_name'] == '') {
    		return $this->lang->line('registration_full_name_must_fill_in_message');
		}
		else if($DBdata['mobile_no'] == '') {
    		return $this->lang->line('registration_mobile_no_must_fill_in_message');
		}
		else if($DBdata['email'] == '') {
    		return $this->lang->line('registration_email_must_fill_in_message');
		}
		else if (!isEmail($DBdata['email'])) {
    		return $this->lang->line('registration_invalid_email_message');
		}
		// else if($disclaimer == '') {
    		// return $this->lang->line('registration_disclaimer_must_fill_in_message');
		// }
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_EDIT_PROFILE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function account_binding()
    {
		$this->lang->load('account_general', get_language());
		
		#Populate submitted data
		$DBdata = array(
			'casino_username' => trim($this->input->post('casino_username', TRUE)),
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
		);
	
		//CALL API - check valid player & set player type
		$response = $this->api_get_balance($DBdata['casino_username']);
		$result_array = json_decode($response, TRUE);
		if(isset($result_array['status']) && $result_array['status'] == 0) {
			$player_type = 3;
			if($this->session->userdata('member_platform_type') == 2) {
				$player_type = 4;
			}
			
			$this->api_update_player_type($DBdata['casino_username'], $player_type);
		}
		else {
			return $this->lang->line('profile_invalid_casino_username_message');
		}
		
		#Check for duplicate
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE casino_username = ? LIMIT 1", array($DBdata['casino_username']));
		if($query->num_rows() > 0) {
			return $this->lang->line('profile_casino_username_already_binded_message');
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_ACCOUNT_BINDING, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function member_convert()
    {
		$this->lang->load('account_general', get_language());
	
		$transaction_type = trim($this->input->post('transaction_type', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => (($transaction_type == 2) ? 2 : 1),
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'to_member_id' => $this->session->userdata('member_id'),
			'to_member_username' => $this->session->userdata('member_username'),
			'credit_amount' => $transaction_amount,
			'debit_amount' => $transaction_amount,
			'status' => 1,
			'transaction_date' => time()
		);
		
		if($DBdata['transaction_type'] == 2) {
			$query = $this->db->query("SELECT package_type FROM sw_members WHERE member_id = ? AND casino_username != '' LIMIT 1", array($DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				if($row->package_type <= 0) {
					return $this->lang->line('convert_buy_package_message');
				}
			}
			else {
				return $this->lang->line('buy_binding_casino_account_message');
			}
		}
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('convert_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/", $transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('convert_invalid_amount_message');
    	}
		else if($security_password == '') {
    		return $this->lang->line('convert_security_password_must_fill_in_message');
    	}
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('convert_invalid_security_password_message');
		}
		
		if($DBdata['transaction_type'] == 2) {
			#Check for available balance
			$query = $this->db->query("SELECT v_unit, v_unit3 FROM sw_member_wallets WHERE v_unit >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
				$DBdata['from_debit_balance'] = $row->v_unit3;
				$DBdata['to_debit_balance'] = ($row->v_unit3 + $transaction_amount);
			}
			else {
				return $this->lang->line('convert_insufficient_amount_message');
			}
		}
		else {
			#Check for available balance
			$query = $this->db->query("SELECT v_unit, v_unit2 FROM sw_member_wallets WHERE v_unit2 >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit2;
				$DBdata['to_credit_balance'] = ($row->v_unit2 - $transaction_amount);
				$DBdata['from_debit_balance'] = $row->v_unit;
				$DBdata['to_debit_balance'] = ($row->v_unit + $transaction_amount);
			}
			else {
				return $this->lang->line('convert_insufficient_amount_message');
			}
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_converts', $DBdata);
		
		if($DBdata['transaction_type'] == 2) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?), v_unit3 = (v_unit3 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['debit_amount'], $DBdata['from_member_id']));
		}
		else {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit + ?), v_unit2 = (v_unit2 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['credit_amount'], $DBdata['from_member_id']));
		}
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CONVERT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function member_transfer()
    {
		$this->lang->load('account_general', get_language());
	
		$transaction_type = trim($this->input->post('transaction_type', TRUE));
		$member_username = trim($this->input->post('member_username', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => (($transaction_type == 1 || $transaction_type == 4) ? $transaction_type : 1),
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'credit_amount' => $transaction_amount,
			'debit_amount' => $transaction_amount,
			'status' => 1,
			'transaction_date' => time()
		);
		
		$setting = $this->member_model->get_setting_rates();
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('transfer_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/", $transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('transfer_invalid_amount_message');
    	}
		else if($transaction_amount < $setting['min_transfer']) {
			return str_replace('_MIN_', number_format($setting['min_transfer'], 2, '.', ''), $this->lang->line('transfer_min_request_message'));
		}
		else if($member_username == '') {
    		return $this->lang->line('transfer_member_username_must_fill_in_message');
		}
		else if($security_password == '') {
    		return $this->lang->line('transfer_security_password_must_fill_in_message');
    	}
		
		#Check for member username availability
		$query = $this->db->query("SELECT member_id, username FROM sw_members WHERE member_id != ? AND username = ? LIMIT 1", array($DBdata['from_member_id'], $member_username));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			if($this->session->userdata('member_platform_type') == 2) {
				$sub_query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND introducer_parent_ref LIKE '%," . $row->member_id . ",%' LIMIT 1", array($DBdata['from_member_id']));
				if($sub_query->num_rows() > 0) {
					$DBdata['to_member_id'] = $row->member_id;
					$DBdata['to_member_username'] = $row->username;
				}
				else {
					$sub_query2 = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND introducer_parent_ref LIKE '%," . $DBdata['from_member_id'] . ",%' LIMIT 1", array($row->member_id));
					if($sub_query2->num_rows() > 0) {
						$DBdata['to_member_id'] = $row->member_id;
						$DBdata['to_member_username'] = $row->username;
					} 
					else {
						return $this->lang->line('transfer_invalid_member_username_message');
					}
				}
			}
			else {
				$DBdata['to_member_id'] = $row->member_id;
				$DBdata['to_member_username'] = $row->username;
			}
		}
		else {
			return $this->lang->line('transfer_invalid_member_username_message');
		}
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('transfer_invalid_security_password_message');
		}
		
		if($transaction_type == 4) {
			#Check for available balance
			$query = $this->db->query("SELECT v_unit4 FROM sw_member_wallets WHERE v_unit4 >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit4;
				$DBdata['to_credit_balance'] = ($row->v_unit4 - $transaction_amount);
			}
			else {
				return $this->lang->line('transfer_insufficient_amount_message');
			}
			
			$query = $this->db->query("SELECT v_unit4 FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_debit_balance'] = $row->v_unit4;
				$DBdata['to_debit_balance'] = ($row->v_unit4 + $transaction_amount);
			}
		}
		else {
			#Check for available balance
			$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE v_unit >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
			}
			else {
				return $this->lang->line('transfer_insufficient_amount_message');
			}
			
			$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_debit_balance'] = $row->v_unit;
				$DBdata['to_debit_balance'] = ($row->v_unit + $transaction_amount);
			}
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_transfers', $DBdata);
		
		if($transaction_type == 4) {
			#Credit
			$this->db->query("UPDATE sw_member_wallets SET v_unit4 = (v_unit4 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit4 = (v_unit4 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
		}
		else {
			#Credit
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			#Debit
			$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->insert_member_log($this->session->userdata('member_id'), LOG_TRANSFER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function get_package_list()
    {
		$query = $this->db->query("SELECT * FROM sw_packages ORDER BY package_id DESC");
		
		return $query;
	}
	
	function member_get_balance($casino_username = NULL)
	{
		$balance = 0;
		
		//CALL API - get balance
		$response = $this->api_get_balance($casino_username);
		$result_array = json_decode($response, TRUE);
		if(isset($result_array['status']) && $result_array['status'] == 0) {
			$balance = $result_array['balance'];
		}
		
		$balance = number_format($balance, 2, '.', '');
		
		return $balance;
	}
	
	function member_buy_package()
	{
		$this->lang->load('account_general', get_language());
	
		$amount_1 = trim($this->input->post('transaction_amount', TRUE));
		$amount_2 = trim($this->input->post('transaction_amount_4', TRUE));
		$package_type = trim($this->input->post('package_type', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
		if($this->session->userdata('member_package_type') < $package_type) {
			#Populate submitted data
			$DBdata = array(
				'reinvest_type' => 1,
				'reinvest_package_type' => $package_type,
				'reinvest_package_date' => time(),
				// 'reinvest_expiry_date' => strtotime('+' . TENURE_CONTRACT . ' days', time()),
				'reinvest_active' => 1,
				'member_id' => $this->session->userdata('member_id')
			);
			
			$casino_username = '';
			$query = $this->db->query("SELECT casino_username FROM sw_members WHERE member_id = ? LIMIT 1", array($DBdata['member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$casino_username = $row->casino_username;
			}
			
			if($casino_username == '') {
				return $this->lang->line('buy_binding_casino_account_message');
			}
			
			#Data validation
			if($security_password == '') {
				return $this->lang->line('buy_security_password_fill_in_message');
			}
			
			#Check for security password
			$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
			$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['member_id'], $encrypted_password));
			if($query->num_rows() == 0) {
				return $this->lang->line('buy_invalid_security_password_message');
			}
			
			#Check for package type availbility
			$package_price = 0;
			$query = $this->db->query("SELECT package_price FROM sw_packages WHERE package_id = ? LIMIT 1", array($DBdata['reinvest_package_type']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$package_price = $row->package_price;
			}
			else {
				return $this->lang->line('buy_package_type_no_found_message');
			}
			
			#Check for origin package type
			$origin_package_price = 0;
			$query = $this->db->query("SELECT package_price FROM sw_packages WHERE package_id = ? LIMIT 1", array($this->session->userdata('member_package_type')));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$origin_package_price = $row->package_price;
			}
			
			$current_package_price = ($package_price - $origin_package_price);
			
			$amount_1 = (($amount_1 > 0) ? $amount_1 : 0);
			$amount_2 = (($amount_2 > 0) ? $amount_2 : 0);
			$total_amount_use = ($amount_1 + $amount_2);
			
			if($total_amount_use != $current_package_price) {
				return $this->lang->line('buy_invalid_total_amount_message');
			}
			
			#Check for available balance
			$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE member_id = ? AND v_unit >= ? LIMIT 1", array($DBdata['member_id'], $amount_1));
			if($query->num_rows() == 0) {
				return $this->lang->line('buy_insufficient_amount_message_3');
			}
			
			$query = $this->db->query("SELECT v_unit4 FROM sw_member_wallets WHERE member_id = ? AND v_unit4 >= ? LIMIT 1", array($DBdata['member_id'], $amount_2));
			if($query->num_rows() == 0) {
				return $this->lang->line('buy_insufficient_amount_message_4');
			}
			
			#Check for member details
			$introducer_parent_ref = '';
			$query = $this->db->query("SELECT introducer_parent_ref FROM sw_members WHERE member_id = ? LIMIT 1", array($DBdata['member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$introducer_parent_ref = $row->introducer_parent_ref;
			}
			
			$this->db->trans_start();
			
			$this->db->insert('sw_member_reinvest', $DBdata);
			
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?), v_unit4 = (v_unit4 - ?) WHERE member_id = ? LIMIT 1", array($amount_1, $amount_2, $DBdata['member_id']));
			
			if($this->session->userdata('member_package_type') == 0) {
				$this->db->query("UPDATE sw_members SET allowed_withdraw = ?, active = ?, package_type = ?, origin_package_type = ? WHERE member_id = ? LIMIT 1", array(1, 1, $DBdata['reinvest_package_type'], $DBdata['reinvest_package_type'], $DBdata['member_id']));
			}
			else {
				$this->db->query("UPDATE sw_members SET allowed_withdraw = ?, active = ?, package_type = ? WHERE member_id = ? LIMIT 1", array(1, 1, $DBdata['reinvest_package_type'], $DBdata['member_id']));
			}
			
			$this->insert_member_log($this->session->userdata('member_id'), LOG_MEMBER_REINVEST, json_encode($DBdata));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata('member_package_type', $DBdata['reinvest_package_type']);
			
				//CALL API - topup credit
				if($casino_username != '') {
					$response = $this->api_topup_credit($casino_username, $current_package_price);
					$result_array = json_decode($response, TRUE);
					if(isset($result_array['status']) && $result_array['status'] == 0) {
						$SDBdata = array(
							'amount' => $current_package_price,
							'member_id' => $DBdata['member_id'],
							'transaction_date' => time(),
						);
						$this->db->insert('sw_member_sales', $SDBdata);
					
						$this->db->query("UPDATE sw_members SET total_invest = (total_invest + ?) WHERE member_id = ? LIMIT 1", array($current_package_price, $DBdata['member_id']));
					}
				}
				
				//Get all package details
				$packages = array();
				$package_query = $this->db->query("SELECT * FROM sw_packages");
				if($package_query->num_rows() > 0) {
					foreach($package_query->result() as $package_row) {
						$packages[$package_row->package_id] = array(
																	'package_price' => $package_row->package_price,
																	'intro_commission' => $package_row->intro_commission
																);									
					}
				}
				
				$member_lists = array();	
				$member_query = $this->db->query("SELECT a.member_id, a.username, a.member_type, a.package_type, a.active, b.v_unit2 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id)");
				if($member_query->num_rows() > 0) {
					foreach($member_query->result() as $member_row) {
						$member_lists[$member_row->member_id] = array(
																	'member_id' => $member_row->member_id,
																	'member_type' => $member_row->member_type,
																	'username' => $member_row->username,
																	'v_unit2' => $member_row->v_unit2,
																	'rate' => 0
																);	
						
						if($member_row->package_type > 0 && $member_row->active == 1) {
							$member_lists[$member_row->member_id]['rate'] = $packages[$member_row->package_type]['intro_commission'];
						}
					}
				}
				
				//Intro Bonus
				$server_time = time();
				$income_date = date('Y-m-d', $server_time);
				$current_rate = 0;
				$arr = explode(',', $introducer_parent_ref);
				for($i=(sizeof($arr) - 1);$i>0;$i--) {
					if( ! empty($arr[$i])) {
						if($current_rate == 10) {
							break;
						}
						else {
							$rate = $member_lists[$arr[$i]]['rate'];
							
							// if($member_lists[$arr[$i]]['member_id'] == 116 || $member_lists[$arr[$i]]['member_id'] == 124 || $member_lists[$arr[$i]]['member_id'] == 205 || $member_lists[$arr[$i]]['member_id'] == 256 || $member_lists[$arr[$i]]['member_id'] == 257 || $member_lists[$arr[$i]]['member_id'] == 863 || $member_lists[$arr[$i]]['member_id'] == 864 || $member_lists[$arr[$i]]['member_id'] == 865 || $member_lists[$arr[$i]]['member_id'] == 866 || $member_lists[$arr[$i]]['member_id'] == 867 || $member_lists[$arr[$i]]['member_id'] == 868 || $member_lists[$arr[$i]]['member_id'] == 1881 || $member_lists[$arr[$i]]['member_id'] == 9448 || $member_lists[$arr[$i]]['member_id'] == 9789 || $member_lists[$arr[$i]]['member_id'] == 9794 || $member_lists[$arr[$i]]['member_id'] == 13727 || $member_lists[$arr[$i]]['member_id'] == 13729 || $member_lists[$arr[$i]]['member_id'] == 16030 || $member_lists[$arr[$i]]['member_id'] == 16032 || $member_lists[$arr[$i]]['member_id'] == 19579 || $member_lists[$arr[$i]]['member_id'] == 19640) {
								// $rate = 10;
							// }
							// else if($member_lists[$arr[$i]]['member_id'] == 1600) {
								// $rate = 8;
							// }
							
							if($rate > 0) {
								if($current_rate < $rate) {
									$upgrade_rate = $rate;
									
									if($current_rate > 0) {
										$rate = ($rate - $current_rate);
									}
									
									$current_rate = $upgrade_rate;
								}
								else if($current_rate >= $rate) {
									$rate = 0;
								}
							}
						
							$bonus = (($current_package_price * $rate) / 100);
						
							if($bonus > 0) {
								$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($bonus, $member_lists[$arr[$i]]['member_id']));
						
								//Transaction log
								//transaction_type 1 = Intro Bonus, 2 = Algebra Bonus, 3 = Differential Bonus, 4 = Same Bonus, 5 = Pool Bonus
								$trans_data = array(
									'transaction_type' => 1,
									'from_member_id' => $this->session->userdata('member_id'),
									'from_member_username' => $this->session->userdata('member_username'),
									'to_member_id' => $member_lists[$arr[$i]]['member_id'],
									'to_member_username' => $member_lists[$arr[$i]]['username'],
									'from_v_unit2' => $member_lists[$arr[$i]]['v_unit2'],
									'v_unit2_amount' => $bonus,
									'to_v_unit2' => ($member_lists[$arr[$i]]['v_unit2'] + $bonus),
									'status' => 1,
									'transaction_date' => $server_time
								);	
								$this->db->insert('sw_member_transactions', $trans_data);
								
								//Income summary
								$income_query = $this->db->query("SELECT member_id FROM sw_member_income_summary WHERE member_id = ? AND income_date = ? LIMIT 1", array($member_lists[$arr[$i]]['member_id'], $income_date));
								if($income_query->num_rows() == 0) {
									$income_data = array(
										'income_date' => $income_date,
										'intro_bonus' => $bonus,
										'v_unit2' => $bonus,
										'member_id' => $member_lists[$arr[$i]]['member_id']
									);	
									$this->db->insert('sw_member_income_summary', $income_data);
								}
								else {
									$this->db->query("UPDATE sw_member_income_summary SET intro_bonus = (intro_bonus + ?), v_unit2 = (v_unit2 + ?) WHERE income_date = ? AND member_id = ? LIMIT 1", array($bonus, $bonus, $income_date, $member_lists[$arr[$i]]['member_id']));
								}
							}
						}	
					}
				}
				
				return STATUS_200;
			}
			else {
				return $this->lang->line('unknown_error');
			}
		}
		else {
			return $this->lang->line('buy_package_type_no_found_message');
		}	
	}
	
	function member_topup_package()
	{
		$this->lang->load('account_general', get_language());
	
		if($this->session->userdata('member_package_type') > 0) {
			$security_password = trim($this->input->post('security_password', TRUE));
			
			$setting = $this->member_model->get_setting_details();
			
			#Populate submitted data
			$DBdata = array(
				'transaction_type' => 1,
				'from_member_id' => $this->session->userdata('member_id'),
				'from_member_username' => $this->session->userdata('member_username'),
				'credit_amount' => 0,
				'transaction_amount' => 0,
				'status' => 1,
				'transaction_date' => time()
			);
			
			$casino_username = '';
			$query = $this->db->query("SELECT casino_username FROM sw_members WHERE member_id = ? LIMIT 1", array($DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$casino_username = $row->casino_username;
			}
			
			if($casino_username == '') {
				return $this->lang->line('buy_binding_casino_account_message');
			}
			
			#Data validation
			if($security_password == '') {
				return $this->lang->line('buy_security_password_fill_in_message');
			}
			
			#Check for security password
			$introducer = '';
			$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
			$query = $this->db->query("SELECT member_id, introducer FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$introducer = $row->introducer;
			}
			else {
				return $this->lang->line('buy_invalid_security_password_message');
			}
			
			#Get package price
			$current_package_price = 0;
			$query = $this->db->query("SELECT package_price FROM sw_packages WHERE package_id = ? LIMIT 1", array($this->session->userdata('member_package_type')));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$current_package_price = $row->package_price;
			}
			
			$current_balance = $this->member_get_balance($casino_username);
			$transaction_amount = ($current_package_price - $current_balance);
			
			if($transaction_amount <= 0) {
				return $this->lang->line('buy_invalid_amount_message');
			}
			else {
				$DBdata['credit_amount'] = $transaction_amount;
				$DBdata['transaction_amount'] = $transaction_amount;
			}
			
			#Check for available balance
			$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE member_id = ? AND v_unit >= ? LIMIT 1", array($DBdata['from_member_id'], $transaction_amount));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
			}
			else {
				return $this->lang->line('buy_insufficient_amount_message_2');
			}
			
			#Get introducer details
			$upline_id = 0;
			$upline_username = '';
			$upline_v_unit2 = 0;
			$query = $this->db->query("SELECT a.member_id, a.username, b.v_unit2 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.username = ? LIMIT 1", array($introducer));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$upline_id = $row->member_id;
				$upline_username = $row->username;
				$upline_v_unit2 = $row->v_unit2;
			}
			
			$this->db->trans_start();
			
			$this->db->insert('sw_member_topup_package', $DBdata);
			
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			$this->insert_member_log($this->session->userdata('member_id'), LOG_TOPUP_PACKAGE, json_encode($DBdata));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				//CALL API - topup credit
				if($casino_username != '') {
					$response = $this->api_topup_credit($casino_username, $transaction_amount);
					$result_array = json_decode($response, TRUE);
					if(isset($result_array['status']) && $result_array['status'] == 0) {
						$SDBdata = array(
							'amount' => $transaction_amount,
							'member_id' => $DBdata['from_member_id'],
							'transaction_date' => time(),
						);
						$this->db->insert('sw_member_sales', $SDBdata);
						
						$this->db->query("UPDATE sw_members SET total_invest = (total_invest + ?) WHERE member_id = ? LIMIT 1", array($transaction_amount, $DBdata['from_member_id']));
					}
				}
				
				// //Intro Bonus
				// if($upline_id > 0) {
					// $server_time = time();
					// $income_date = date('Y-m-d', $server_time);
					// $bonus = (($transaction_amount * 5) / 100);
							
					// if($bonus > 0) {
						// $this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($bonus, $upline_id));
				
						// //Transaction log
						// //transaction_type 1 = Intro Bonus, 2 = Algebra Bonus, 3 = Differential Bonus, 4 = Same Bonus, 5 = Pool Bonus
						// $trans_data = array(
							// 'transaction_type' => 1,
							// 'from_member_id' => $this->session->userdata('member_id'),
							// 'from_member_username' => $this->session->userdata('member_username'),
							// 'to_member_id' => $upline_id,
							// 'to_member_username' => $upline_username,
							// 'from_v_unit2' => $upline_v_unit2,
							// 'v_unit2_amount' => $bonus,
							// 'to_v_unit2' => ($upline_v_unit2 + $bonus),
							// 'status' => 1,
							// 'transaction_date' => $server_time
						// );	
						// $this->db->insert('sw_member_transactions', $trans_data);
						
						// //Income summary
						// $income_query = $this->db->query("SELECT member_id FROM sw_member_income_summary WHERE member_id = ? AND income_date = ? LIMIT 1", array($upline_id, $income_date));
						// if($income_query->num_rows() == 0) {
							// $income_data = array(
								// 'income_date' => $income_date,
								// 'intro_bonus' => $bonus,
								// 'v_unit2' => $bonus,
								// 'member_id' => $upline_id
							// );	
							// $this->db->insert('sw_member_income_summary', $income_data);
						// }
						// else {
							// $this->db->query("UPDATE sw_member_income_summary SET intro_bonus = (intro_bonus + ?), v_unit2 = (v_unit2 + ?) WHERE income_date = ? AND member_id = ? LIMIT 1", array($bonus, $bonus, $income_date, $upline_id));
						// }
					// }
				// }	
				
				return STATUS_200;
			}
			else {
				return $this->lang->line('unknown_error');
			}
		}
		else {
			return $this->lang->line('buy_no_package_message');
		}	
	}
	
	function get_member_buy_package()
	{
		$query = $this->db->query("SELECT * FROM sw_member_invests WHERE member_transaction_id = ? AND member_id = ? LIMIT 1", array($this->session->userdata('order_id'), $this->session->userdata('member_id')))->row_array();
	    
	    return $query;
	}
	
	function get_member_income()
	{
		if($_POST) {
			$tmp_from_date = trim($this->input->post('from_date', TRUE));
			$tmp_to_date = trim($this->input->post('to_date', TRUE));
			$from_date = strtotime(date('Y-m-d 00:00:00', strtotime($tmp_from_date)));
			$to_date = strtotime(date('Y-m-d 23:59:59', strtotime($tmp_to_date)));
			
			$this->session->set_userdata('search_from_date', $tmp_from_date);
			$this->session->set_userdata('search_to_date', $tmp_to_date);
					
			$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM (SELECT member_transaction_id FROM sw_member_transactions WHERE to_member_id = ? AND transaction_date >= ? AND transaction_date <= ? UNION ALL SELECT member_transaction_id FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_date >= ? AND transaction_date <= ? AND transaction_type = 2 UNION ALL SELECT member_transaction_id FROM sw_member_topup WHERE to_member_id = ? AND transaction_date >= ? AND transaction_date <= ? AND transaction_type = 2) x", array($this->session->userdata('member_id'), $from_date, $to_date, $this->session->userdata('member_id'), $from_date, $to_date, $this->session->userdata('member_id'), $from_date, $to_date))->row();
			$data['total_rows'] = $query->total;
			
			$config['base_url'] = base_url() . 'income/search/';
			$config['uri_segment'] = 3;
			$config['total_rows'] = $data['total_rows'];
			$config['per_page'] = 20;
			$config['cur_page'] = 0;
				
			$this->pagination->initialize($config);
				
			$data['pagination'] = $this->pagination->create_links();
			
			$sql = '';
			if($data['total_rows'] > 0) {	
				if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
					$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
				else 
					$sql = ' LIMIT 0, ' . $config['per_page'];
			}
			
			$data['query'] = $this->db->query("SELECT * FROM (SELECT member_transaction_id, transaction_type, from_member_username, v_unit2_amount, transaction_date, status, 1 AS type FROM sw_member_transactions WHERE to_member_id = ? AND transaction_date >= ? AND transaction_date <= ? UNION ALL SELECT member_transaction_id, transaction_type, to_member_username AS from_member_username, credit_amount AS v_unit2_amount, transaction_date, status, 2 AS type FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_date >= ? AND transaction_date <= ? AND transaction_type = 2 UNION ALL SELECT member_transaction_id, transaction_type, to_member_username AS from_member_username, debit_amount AS v_unit2_amount, transaction_date, status, 3 AS type FROM sw_member_topup WHERE to_member_id = ? AND transaction_date >= ? AND transaction_date <= ? AND transaction_type = 2) x ORDER BY transaction_date DESC, member_transaction_id DESC $sql", array($this->session->userdata('member_id'), $from_date, $to_date, $this->session->userdata('member_id'), $from_date, $to_date, $this->session->userdata('member_id'), $from_date, $to_date));
		}
		else {
			$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM (SELECT member_transaction_id FROM sw_member_transactions WHERE to_member_id = ? UNION ALL SELECT member_transaction_id FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_type = 2 UNION ALL SELECT member_transaction_id FROM sw_member_topup WHERE to_member_id = ? AND transaction_type = 2) x", array($this->session->userdata('member_id'), $this->session->userdata('member_id'), $this->session->userdata('member_id')))->row();
			$data['total_rows'] = $query->total;
			
			$config['base_url'] = base_url() . 'income/index/';
			$config['uri_segment'] = 3;
			$config['total_rows'] = $data['total_rows'];
			$config['per_page'] = 20;
			$config['cur_page'] = 0;
				
			$this->pagination->initialize($config);
				
			$data['pagination'] = $this->pagination->create_links();
			
			$sql = '';
			if($data['total_rows'] > 0) {	
				if($this->uri->segment($config['uri_segment']) && is_numeric($this->uri->segment($config['uri_segment'])))
					$sql = ' LIMIT ' . $this->uri->segment($config['uri_segment']) . ', ' . $config['per_page'];
				else 
					$sql = ' LIMIT 0, ' . $config['per_page'];
			}
			
			$data['query'] = $this->db->query("SELECT * FROM (SELECT member_transaction_id, transaction_type, from_member_username, v_unit2_amount, transaction_date, status, 1 AS type FROM sw_member_transactions WHERE to_member_id = ? UNION ALL SELECT member_transaction_id, transaction_type, to_member_username AS from_member_username, credit_amount AS v_unit2_amount, transaction_date, status, 2 AS type FROM sw_member_adjustment WHERE to_member_id = ? AND transaction_type = 2 UNION ALL SELECT member_transaction_id, transaction_type, to_member_username AS from_member_username, debit_amount AS v_unit2_amount, transaction_date, status, 3 AS type FROM sw_member_topup WHERE to_member_id = ? AND transaction_type = 2) x ORDER BY transaction_date DESC, member_transaction_id DESC $sql", array($this->session->userdata('member_id'), $this->session->userdata('member_id'), $this->session->userdata('member_id')));
		}
		
		return $data;
	}
	
	function get_setting_details()
	{
		$query = $this->db->query("SELECT * FROM sw_setting LIMIT 1")->row_array();
	    
	    return $query;
	}
	
	function member_to_withdraw()
    {
		$this->lang->load('account_general', get_language());
	
		$currency_id = trim($this->input->post('currency_id', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
		$setting = $this->member_model->get_setting_details();
		$currency = $this->get_currency_rate();
		
		#Populate submitted data
		$DBdata = array(
			'transaction_type' => 1,
			'currency_id' => (($currency_id == 1 || $currency_id == 2 || $currency_id == 3 || $currency_id == 5 || $currency_id == 20) ? $currency_id : 5),
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'credit_amount' => $transaction_amount,
			'status' => 0,
			'transaction_date' => time()
		);
		
		$DBdata['currency_rate'] = $currency[$DBdata['currency_id']]['out'];
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('withdraw_amount_must_fill_in_message');
    	} 
		
		// if($currency_id == 3) {
			// if ( ! preg_match("/^([0-9]+)$/",$transaction_amount) || $transaction_amount < $setting['min_withdraw_2']) {
				// return $this->lang->line('withdraw_invalid_amount_message');
			// }
		// }
		// else {
			if ( ! preg_match("/^([0-9]+)$/",$transaction_amount) || $transaction_amount < $setting['min_withdraw']) {
				return $this->lang->line('withdraw_invalid_amount_message');
			}
		// }
		
		if($security_password == '') {
    		return $this->lang->line('withdraw_security_password_must_fill_in_message');
    	}
		
		#Check for daily withdrawal limit
		$total_withdrawal_amount = $DBdata['credit_amount'];
		$today_datetime = strtotime(date('Y-m-d 00:00:00'));
		$query = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND transaction_date >= ? AND status < ?", array($DBdata['from_member_id'], $today_datetime, 2));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$total_withdrawal_amount = ($total_withdrawal_amount + $row->total);
		}
		
		if($total_withdrawal_amount > $setting['max_withdraw_per_day']) {
			return str_replace('_MAX_', $setting['max_withdraw_per_day'], $this->lang->line('withdraw_maximum_per_day_amount'));
		}
		
		$DBdata['charges'] = (($DBdata['credit_amount'] * $setting['withdrawal_rate']) / 100);
		
		if($currency_id == 5 || $currency_id == 20) {
			$DBdata['charges'] = $setting['usdt_withdrawal_fee'];
		}
		
		$DBdata['withdrawal_amount'] = (($DBdata['credit_amount'] * $DBdata['currency_rate']) - $DBdata['charges']);
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('withdraw_invalid_security_password_message');
		}
		
		#Check for available balance
		$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE v_unit >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['from_credit_balance'] = $row->v_unit;
			$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
		}
		else {
			return $this->lang->line('withdraw_insufficient_amount_message');
		}
		
		#Check for bank details
		$query = $this->db->query("SELECT bank_name, bank_account_no, account_holder_name, bank_address, bank_country, bank_swift_code, wallet_address FROM sw_members WHERE member_id = ? LIMIT 1", array($DBdata['from_member_id']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			if($currency_id == 5 || $currency_id == 20) {
				$DBdata['wallet_address'] = $row->wallet_address;
				if($row->wallet_address == '') {
					if($this->session->userdata('member_platform_type') == 2) {
						return $this->lang->line('withdraw_invalid_ping_wallet_address_message');
					}
					else {
						return $this->lang->line('withdraw_invalid_usdt_wallet_address_message');
					}
				}
			}
			else {
				$DBdata['to_bank_name'] = $row->bank_name;
				$DBdata['to_bank_account_no'] = $row->bank_account_no;
				$DBdata['to_account_holder_name'] = $row->account_holder_name;
				$DBdata['to_bank_address'] = $row->bank_address;
				$DBdata['to_bank_country'] = $row->bank_country;
				$DBdata['to_bank_swift_code'] = $row->bank_swift_code;
				
				if($row->bank_name == '' || $row->bank_account_no == '' || $row->account_holder_name == '') {
					return $this->lang->line('withdraw_invalid_bank_details_message');
				}
			}	
		}
		else {
			return $this->lang->line('withdraw_invalid_account_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_withdraw', $DBdata);
		
		#Credit
		$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_WITHDRAWAL, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			if($currency_id == 20) {
				return STATUS_202;
			}
			else if($currency_id == 5) {
				return STATUS_201;
			}
			else {
				return STATUS_200;
			}	
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function get_member_topup_address()
	{
		$address_arr = array();

		$query = $this->db->query("SELECT member_id, username, usdt_trc20_address FROM sw_members WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			if($row->usdt_trc20_address != '') {
				$address_arr['usdt_trc20_address'] = $row->usdt_trc20_address;
			}
			else {
				//Get USDT TRC20 address
				// $arr = $this->coinpayments_api_call('get_callback_address', array('currency' => 'USDT.TRC20', 'ipn_url' => base_url() . 'callback/coinpayment/', 'label' => $row->username));
				// $address1 = (isset($arr['result']['address']) ? $arr['result']['address'] : '');
				
				$array_param = array(
					"agent_id" => PG_TRONGRID_AGENT_ID,
					"username" => $row->username
				);
				
				$array_param['signature'] = md5(implode('', $array_param) . PG_TRONGRID_KEY);
				
				$response = $this->curl_json(PG_TRONGRID_URL, $array_param);
				$result_array = json_decode($response, TRUE);
				
				$address1 = (isset($result_array['address']) ? $result_array['address'] : '');
				
				if($address1 != '') {
					$address_arr['usdt_trc20_address'] = $address1;
					$this->db->query("UPDATE sw_members SET usdt_trc20_address = ? WHERE member_id = ? LIMIT 1", array($address1, $row->member_id));
				}
			}
		}
		
		return $address_arr;
	}
	
	function get_pending_topup_details($order_no = NULL)
	{
		$query = $this->db->query("SELECT * FROM sw_member_topup WHERE to_member_id = ? AND order_no = ?  AND status = ? LIMIT 1", array($this->session->userdata('member_id'), $order_no, 0))->row_array();
		
		return $query;
	}
	
	function member_topup()
    {
		$this->lang->load('account_general', get_language());
	
		$payment_method = trim($this->input->post('payment_method', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
		$setting = $this->get_setting_details();
		$currency = $this->get_currency_rate();
		
		#Populate submitted data
		$DBdata = array(
			'transaction_type' => 1,
			'payment_method' => $payment_method,
			'to_member_id' => $this->session->userdata('member_id'),
			'to_member_username' => $this->session->userdata('member_username'),
			'debit_amount' => $transaction_amount,
			'transaction_amount' => 0,
			'order_no' => date("Ymdhms").sprintf("%05d", rand(1, 99999)),
			'status' => 0,
			'transaction_date' => time()
		);
		
		#Data validation
		if($payment_method <= 0) {
    		return '0|' . $this->lang->line('topup_payment_method_must_fill_in_message');
    	} 
		else if($transaction_amount == '') {
    		return '0|' . $this->lang->line('topup_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/",$transaction_amount) || $transaction_amount < $setting['min_topup']) {
			return '0|' . $this->lang->line('topup_invalid_amount_message');
    	}
		else if($security_password == '') {
    		return '0|' . $this->lang->line('topup_security_password_must_fill_in_message');
    	}
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['to_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return '0|' . $this->lang->line('topup_invalid_security_password_message');
		}
		
		if($payment_method == 1) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_1', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYTRUST_IBAN_MBB;
			}
		}
		else if($payment_method == 2) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_2', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYLAH_IBAN_MBB;
			}
		}
		else if($payment_method == 11) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_1', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYTRUST_IBAN_BCA;
			}
		}
		else if($payment_method == 13) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_1', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYTRUST_IBAN_SCB;
			}
		}
		else if($payment_method == 14) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_1', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYTRUST_IBAN_VCB;
			}
		}
		else if($payment_method == 15) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_2', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYLAH_IBAN_SCB;
			}
		}
		else if($payment_method == 16) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_2', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYLAH_IBAN_VCB;
			}
		}
		else if($payment_method == 17) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_2', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_PAYLAH_IBAN_BCA;
			}
		}
		else if($payment_method == 18) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_1', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_SUREPAY_IBAN_DBS;
			}
		}
		else if($payment_method == 19) {
			$DBdata['bank_code'] = trim($this->input->post('bank_code_3', TRUE));
			
			if(empty($DBdata['bank_code'])) {
				$DBdata['bank_code'] = PG_SUREPAY_IBAN_KBANK;
			}
		}
		
		switch($payment_method) {
			case 1: 
			case 2: 
			case 6: $DBdata['currency_id'] = 3; $DBdata['currency_rate'] = $currency[3]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[3]['in']); break;
			case 3: 
			case 12: $DBdata['currency_id'] = 1; $DBdata['currency_rate'] = $currency[1]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[1]['in']); break;
			case 4: $DBdata['currency_id'] = 5; $DBdata['currency_rate'] = $currency[5]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[5]['in']); break;
			case 13: 
			case 15: 
			case 19: $DBdata['currency_id'] = 6; $DBdata['currency_rate'] = $currency[6]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[6]['in']); break;
			case 18: $DBdata['currency_id'] = 8; $DBdata['currency_rate'] = $currency[8]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[8]['in']); break;
			case 14: 
			case 16: $DBdata['currency_id'] = 9; $DBdata['currency_rate'] = $currency[9]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[9]['in']); break;
			case 11: 
			case 17: $DBdata['currency_id'] = 11; $DBdata['currency_rate'] = $currency[11]['in']; $DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $currency[11]['in']); break;
		}
		
		#Check for available balance
		$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['from_debit_balance'] = $row->v_unit;
			$DBdata['to_debit_balance'] = ($row->v_unit + $DBdata['debit_amount']);
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_topup', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_TOPUP, json_encode($DBdata));
		
		$pg_data = array(
							'payment_method' => $payment_method,
							'currency_id' => $DBdata['currency_id'],
							'input' => json_encode($DBdata),
							'output' => '',
							'ptime' => time()
						);
		$this->db->insert('sw_payment_gateway_logs', $pg_data);
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			if($payment_method == 1 || $payment_method == 11 || $payment_method == 13 || $payment_method == 14) {
				return STATUS_200 . '|' . base_url() . 'payment/paytrust/' . $DBdata['order_no'] . '/';
			}
			else if($payment_method == 2 || $payment_method == 15 || $payment_method == 16 || $payment_method == 17) {
				return STATUS_200 . '|' . base_url() . 'payment/paylah/' . $DBdata['order_no'] . '/';
			}
			else if($payment_method == 3) {
				return STATUS_200 . '|' . base_url() . 'payment/sfpay/' . $DBdata['order_no'] . '/';
			}
			else if($payment_method == 6) {
				return STATUS_200 . '|' . base_url() . 'payment/fpay/' . $DBdata['order_no'] . '/';
			}
			else if($payment_method == 12) {
				return STATUS_200 . '|' . base_url() . 'payment/onepay/' . $DBdata['order_no'] . '/';
			}
			else if($payment_method == 18 || $payment_method == 19) {
				return STATUS_200 . '|' . base_url() . 'payment/surepay/' . $DBdata['order_no'] . '/';
			}
			else {
				return '0|' . $this->lang->line('unknown_error');
			}
		}
		else {
			return '0|' . $this->lang->line('unknown_error');
		}
    }
	
	function update_pending_topup($payment_method = NULL, $status = NULL, $orderno = NULL, $output = NULL)
	{
		switch($payment_method) {
			case 1:
			case 2: 
			case 6:
			case 8:
			case 9:
			case 10: $currency_id = 3; break;
			case 3: 
			case 12: $currency_id = 1; break;
			case 4: $currency_id = 5; break;
			case 13: 
			case 15: 
			case 19: $currency_id = 6; break;
			case 18: $currency_id = 8; break;
			case 14: 
			case 16: $currency_id = 9; break;
			case 11: 
			case 17: $currency_id = 11; break;
		}
		
		$pg_data = array(
							'payment_method' => $payment_method,
							'currency_id' => $currency_id,
							'output' => $output,
							'ptime' => time()
						);
		$this->db->insert('sw_payment_gateway_logs', $pg_data);
		
		$query = $this->db->query("SELECT a.member_transaction_id, a.debit_amount, a.to_member_id, b.v_unit FROM sw_member_topup a, sw_member_wallets b WHERE (a.to_member_id = b.member_id) AND a.order_no = ? AND a.status = ? LIMIT 1", array($orderno, 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$final_amount = ($row->v_unit + $row->debit_amount);
			$this->db->query("UPDATE sw_member_topup SET from_debit_balance = ?, to_debit_balance = ?, status = ? WHERE member_transaction_id = ? LIMIT 1", array($row->v_unit, $final_amount, $status, $row->member_transaction_id));
			
			if($status == 1) {
				$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit + ?) WHERE member_id = ? LIMIT 1", array($row->debit_amount, $row->to_member_id));
			}
		}
	}
	
	function member_claim_insurance()
    {
		$this->lang->load('account_general', get_language());
	
		$today_date = date('Y-m-d');
		$remark = trim($this->input->post('remark', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'claim_amount' => 0,
			'remark' => $remark,
			'insurance_date' => $today_date,
			'status' => 0,
			'transaction_date' => time()
		);
		
		#Data validation
		$max_file_size = 2097152;
		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
		if(isset($_FILES['claim_slip_1']['size']) AND $_FILES['claim_slip_1']['size'] > 0) 
		{
			if( ! in_array($_FILES['claim_slip_1']['type'], $allowed_types)) 
			{
				return $this->lang->line('insurance_invalid_claim_picture_message');
			}
			else if($_FILES['claim_slip_1']['size'] > $max_file_size)
			{
				return $this->lang->line('insurance_exceeded_size_limit_message');
			}
			else
			{
				$DBdata['claim_slip_1'] = md5($this->session->userdata('member_id') . 'CLAIM_1' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		else {
			return $this->lang->line('insurance_claim_picture_must_fill_in_message');
		}
		
		if(isset($_FILES['claim_slip_2']['size']) AND $_FILES['claim_slip_2']['size'] > 0) 
		{
			if( ! in_array($_FILES['claim_slip_2']['type'], $allowed_types)) 
			{
				return $this->lang->line('insurance_invalid_claim_picture_message');
			}
			else if($_FILES['claim_slip_2']['size'] > $max_file_size)
			{
				return $this->lang->line('insurance_exceeded_size_limit_message');
			}
			else
			{
				$DBdata['claim_slip_2'] = md5($this->session->userdata('member_id') . 'CLAIM_2' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		
		if(isset($_FILES['claim_slip_3']['size']) AND $_FILES['claim_slip_3']['size'] > 0) 
		{
			if( ! in_array($_FILES['claim_slip_3']['type'], $allowed_types)) 
			{
				return $this->lang->line('insurance_invalid_claim_picture_message');
			}
			else if($_FILES['claim_slip_3']['size'] > $max_file_size)
			{
				return $this->lang->line('insurance_exceeded_size_limit_message');
			}
			else
			{
				$DBdata['claim_slip_3'] = md5($this->session->userdata('member_id') . 'CLAIM_3' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		
		if(isset($_FILES['claim_slip_4']['size']) AND $_FILES['claim_slip_4']['size'] > 0) 
		{
			if( ! in_array($_FILES['claim_slip_4']['type'], $allowed_types)) 
			{
				return $this->lang->line('insurance_invalid_claim_picture_message');
			}
			else if($_FILES['claim_slip_4']['size'] > $max_file_size)
			{
				return $this->lang->line('insurance_exceeded_size_limit_message');
			}
			else
			{
				$DBdata['claim_slip_4'] = md5($this->session->userdata('member_id') . 'CLAIM_4' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		
		if(isset($_FILES['claim_slip_5']['size']) AND $_FILES['claim_slip_5']['size'] > 0) 
		{
			if( ! in_array($_FILES['claim_slip_5']['type'], $allowed_types)) 
			{
				return $this->lang->line('insurance_invalid_claim_picture_message');
			}
			else if($_FILES['claim_slip_5']['size'] > $max_file_size)
			{
				return $this->lang->line('insurance_exceeded_size_limit_message');
			}
			else
			{
				$DBdata['claim_slip_5'] = md5($this->session->userdata('member_id') . 'CLAIM_5' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		
		if(isset($_FILES['claim_slip_6']['size']) AND $_FILES['claim_slip_6']['size'] > 0) 
		{
			if( ! in_array($_FILES['claim_slip_6']['type'], $allowed_types)) 
			{
				return $this->lang->line('insurance_invalid_claim_picture_message');
			}
			else if($_FILES['claim_slip_6']['size'] > $max_file_size)
			{
				return $this->lang->line('insurance_exceeded_size_limit_message');
			}
			else
			{
				$DBdata['claim_slip_6'] = md5($this->session->userdata('member_id') . 'CLAIM_6' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		
		#Check for valid insurance
		$query = $this->db->query("SELECT member_transaction_id FROM sw_member_buy_insurances WHERE from_member_id = ? AND insurance_date = ? LIMIT 1", array($this->session->userdata('member_id'), $today_date));
		if($query->num_rows() == 0) {
			return $this->lang->line('insurance_not_buy_insurance_message');
		}
		
		#Check for double claim
		$query = $this->db->query("SELECT member_transaction_id FROM sw_member_claim_insurances WHERE from_member_id = ? AND insurance_date = ? AND status < ? LIMIT 1", array($this->session->userdata('member_id'), $today_date, 2));
		if($query->num_rows() > 0) {
			return $this->lang->line('insurance_claim_already_submitted_message');
		}
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('insurance_invalid_security_password_message');
		}
		
		$query = $this->db->query("SELECT b.package_price FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$DBdata['claim_amount'] = $row->package_price;
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_claim_insurances', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CLAIM_INSURANCE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->load->library('image_lib');
			
			if(isset($_FILES['claim_slip_1']['size']) AND $_FILES['claim_slip_1']['size'] > 0)
			{
				$config['source_image'] = $_FILES['claim_slip_1']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'claims/' . $DBdata['claim_slip_1'];
				$config['maintain_ratio'] = TRUE;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['claim_slip_2']['size']) AND $_FILES['claim_slip_2']['size'] > 0)
			{
				$config['source_image'] = $_FILES['claim_slip_2']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'claims/' . $DBdata['claim_slip_2'];
				$config['maintain_ratio'] = TRUE;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['claim_slip_3']['size']) AND $_FILES['claim_slip_3']['size'] > 0)
			{
				$config['source_image'] = $_FILES['claim_slip_3']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'claims/' . $DBdata['claim_slip_3'];
				$config['maintain_ratio'] = TRUE;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['claim_slip_4']['size']) AND $_FILES['claim_slip_4']['size'] > 0)
			{
				$config['source_image'] = $_FILES['claim_slip_4']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'claims/' . $DBdata['claim_slip_4'];
				$config['maintain_ratio'] = TRUE;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['claim_slip_5']['size']) AND $_FILES['claim_slip_5']['size'] > 0)
			{
				$config['source_image'] = $_FILES['claim_slip_5']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'claims/' . $DBdata['claim_slip_5'];
				$config['maintain_ratio'] = TRUE;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['claim_slip_6']['size']) AND $_FILES['claim_slip_6']['size'] > 0)
			{
				$config['source_image'] = $_FILES['claim_slip_6']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'claims/' . $DBdata['claim_slip_6'];
				$config['maintain_ratio'] = TRUE;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function coinpayments_api_call($cmd, $req = array()) 
	{ 
		// Fill these in from your API Keys page 
		$public_key = PG_CP_PUBLIC_KEY; 
		$private_key = PG_CP_PRIVATE_KEY; 
		 
		// Set the API command and required fields 
		$req['version'] = 1; 
		$req['cmd'] = $cmd; 
		$req['key'] = $public_key; 
		$req['format'] = 'json'; //supported values are json and xml 
		 
		// Generate the query string 
		$post_data = http_build_query($req, '', '&'); 
		 
		// Calculate the HMAC signature on the POST data 
		$hmac = hash_hmac('sha512', $post_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) { 
				// We are on 32-bit PHP, so use the bigint as string option. If you are using any API calls with Satoshis it is highly NOT recommended to use 32-bit PHP 
				$dec = json_decode($data, TRUE, 512, JSON_BIGINT_AS_STRING); 
			} else { 
				$dec = json_decode($data, TRUE); 
			} 
			if ($dec !== NULL && count($dec)) { 
				return $dec; 
			} else { 
				// If you are using PHP 5.5.0 or higher you can use json_last_error_msg() for a better error message 
				return array('error' => 'Unable to parse JSON result ('.json_last_error().')'); 
			} 
		} else { 
			return array('error' => 'cURL error: '.curl_error($ch)); 
		} 
	}
	
	function get_member_downline($username = NULL)
    {
		$root_member_id = $this->session->userdata('member_id');
		$member_lists = array();	
		$member_query = $this->db->query("SELECT member_id, username, full_name, package_type, active FROM sw_members WHERE introducer_parent_ref LIKE '%,$root_member_id,%' OR member_id = ?", array($this->session->userdata('member_id')));
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				$member_lists[$member_row->member_id] = array('username' => $member_row->username, 'full_name' => $member_row->full_name, 'package_type' => $member_row->package_type, 'active' => $member_row->active, 'total_intro' => 0);	
			}
		}
		
		$member_query = $this->db->query("SELECT introducer_parent_ref FROM sw_members WHERE introducer_parent_ref LIKE '%,$root_member_id,%' OR member_id = ?", array($this->session->userdata('member_id')));
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				if($member_row->introducer_parent_ref != '') {
					$arr = explode(',', $member_row->introducer_parent_ref);
					
					for($i=0; $i<sizeof($arr); $i++) {
						if($arr[$i] != '' AND $arr[$i] > 0) {
							if(isset($member_lists[$arr[$i]])) {
								$member_lists[$arr[$i]]['total_intro'] = ($member_lists[$arr[$i]]['total_intro'] + 1);
							}
						}
					}
				}
			}
		}
		
		$html = '';
		if($username != '') {
			$query = $this->db->query("SELECT member_id, username, full_name, package_type, member_type, active FROM sw_members WHERE introducer = ?", array($username));
			if($query->num_rows() > 0) {
				$html .= '<ul class="nested active" data-switch="1" style="padding: 0;">';
				
				foreach($query->result() as $row) {
					$text_color = (($row->active == 0) ? 'text-secondary' : 'text-success');
					if($member_lists[$row->member_id]['total_intro'] > 0) {
						$html .= '<li class="' . $text_color . '"><span class="caret" id="ht-' . $row->member_id . '" onclick="get_downline(' . $row->member_id . ', \'' . $row->username . '\')" data-value="0">' . $row->username . ' (' . $this->lang->line(get_package($row->package_type)) . ') ' . '</span></li>';
					}
					else {
						// $html .= '<li>' . $row->username . ' (' . (($row->member_type == 2) ? $this->lang->line(get_package($row->package_type)) : 0) . ') ' . '</li>';
						$html .= '<li class="' . $text_color . '">' . $row->username . ' (' . $this->lang->line(get_package($row->package_type)) . ') </li>';
					}
				}
				
				$html .= '</ul>';
			}	
		}	
		
		return $html;
    }
	
	function get_member_message()
	{
		$query = $this->db->query("SELECT message, message_type, created_date FROM sw_member_messages WHERE member_id = ? ORDER BY message_id DESC LIMIT 100", array($this->session->userdata('member_id')));
		
		return $query;
	}
	
	function get_user_unread_message()
	{
		$query = $this->db->query("SELECT COUNT(message_id) AS total FROM sw_member_messages WHERE member_read = ? AND member_id = ?", array(1, $this->session->userdata('member_id')))->row();
		$total = $query->total;
		
		return $total;
	}
	
	function member_read_message()
	{
		$this->db->query("UPDATE sw_member_messages SET member_read = ? WHERE member_id = ?", array(0, $this->session->userdata('member_id')));
	}
	
	function get_message_content($message_id = NULL)
	{
		$query = $this->db->query("SELECT subject, message, created_date FROM sw_member_messages WHERE message_id = ? LIMIT 1", array($message_id))->row_array();
		
		return $query;
	}
	
	public function reset_password()
	{
		$this->lang->load('account_general', get_language());
		
		$username = trim($this->input->post('username', TRUE));
		$email = trim($this->input->post('email', TRUE));
		
		#Data validation
		if($username == '') {
    		return '2|' . $this->lang->line('registration_username_must_fill_in_message');
		}
		else if($email == '') {
    		return '2|' . $this->lang->line('registration_email_must_fill_in_message');
		}
		
		// session_start();

		// if (isset($_SESSION['captcha'])) {
			// $captcha_code = $this->input->post('captcha', TRUE);

			// if ($_SESSION['captcha'] != $captcha_code) {
				// echo $this->lang->line('login_invalid_captcha_message');
				// exit();
			// }
			// else {
				// unset($_SESSION['captcha']);
			// }

		// }
		
		#Check for email availbility
		$query = $this->db->query("SELECT member_id, username, full_name, email FROM sw_members WHERE username = ? AND email = ? LIMIT 1", array($username, $email));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$password = rand(100000, 999999);
			$security_password = rand(100000, 999999);
			
			#Populate submitted data
			$DBdata = array(
				'password_origin' => $password,
				'password' => sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key'))))),
				'security_password_origin' => $security_password,
				'security_password' => sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key'))))),
				'modified_by' => $row->username,
				'modified_date' => time()
			);
			
			$this->db->trans_start();
			
			$this->db->where('member_id', $row->member_id);
			$this->db->limit(1);
			$this->db->update('sw_members', $DBdata);
			
			$this->insert_member_log($row->member_id, LOG_FORGOT_PASSWORD, json_encode($DBdata));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
		
			if($rs) {
				#Send an new password email to member 
				$this->load->config('email');
				$this->load->library('email');

				$form = $this->config->item('no_reply_email');
				
				$e_subject = $this->lang->line('forgot_password_email_subject');

				$e_body = str_replace(array('%f', '%s', '%t'), array($row->full_name, $password, $security_password), $this->lang->line('forgot_password_email_body'));

				// if(substr($row->email, -6, 6) == 'qq.com') {
					// $headers = "From: $form \r\n";
					// $headers .= "MIME-Version: 1.0\r\n";
					// $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
					// $result = mail($row->email, $e_subject, $e_body, $headers);
				// }
				// else {
					$result = $this->email
							->from($form)
							->to($row->email)
							->subject($e_subject)
							->message($e_body)
							->send();
				// }
				
				if($result) {
					return '1|' . str_replace(array('%f'), array($row->email), $this->lang->line('forgot_password_reset_password_message'));
				}
				else {
					return '2|' . $this->lang->line('forgot_password_email_send_failed_message');
				}
			}
			else {
				return '2|' . $this->lang->line('forgot_password_email_send_failed_message');
			}
		}
		else
		{
			return '2|' . $this->lang->line('forgot_password_unregister_email_message');
		}
	}
	function get_currency_rate_list()
	{
		$query = $this->db->query("SELECT * FROM sw_currencies WHERE currency_id <= 19 ORDER BY currency_id ASC");
		
		return $query;
	}
	
	function get_currency_rate()
	{
		$currency_arr = array();
		$query = $this->db->query("SELECT currency_id, t_currency_rate, w_currency_rate FROM sw_currencies ORDER BY currency_id ASC");
		if($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$currency_arr[$row->currency_id]['in'] = $row->t_currency_rate;
				$currency_arr[$row->currency_id]['out'] = $row->w_currency_rate;
			}
		}

		return $currency_arr;	
	}
	
	function api_create_account($username = NULL, $password = NULL)
	{
		$arr = array(
			"username" => $username,
			"password" => $password,
			"nickname" => $username,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'MemberRegisterDV',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"player" => array(
				"username" => $arr['username'],
				"password" => $arr['password'],
				"nickname" => $arr['nickname'],
			)
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_topup_credit($username = NULL, $amount = NULL)
	{
		$arr = array(
			"username" => $username,
			"amount" => $amount,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'CreditBalance',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"amount" => $arr['amount'],
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_get_balance($username = NULL) 
	{
		$arr = array(
			"username" => $username,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'GetBalanceDV',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_update_player_type($username = NULL, $player_type = NULL) 
	{
		$arr = array(
			"username" => $username,
			"player_type" => $player_type,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'UpdatePlayerType',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"player_type" => $arr['player_type'],
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function curl_json($url = NULL, $arr = NULL) 
	{
		$data_string = json_encode($arr);  
		
		$ch = curl_init($url);  	
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                      
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		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/json',
				'Content-Length: ' . strlen($data_string)
			)
		);   	
		$response = curl_exec($ch);
		curl_close($ch);
		
		return $response;
	}
}