<?php

class User_Model extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function insert_user_log($user_id = NULL, $log_type = NULL, $user_data = NULL)
    {
        #Populate submitted data
		$DBdata = array(
		   'user_id' => $user_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_user_logs', $DBdata);
    }
	
	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));
		$direct_sponsor = $this->session->userdata('username');
		
        #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' => $password,
			'security_password' => sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key'))))),
			'full_name' => trim($this->input->post('full_name', TRUE)),
			'dob' => date('Y-m-d', strtotime(trim($this->input->post('dob', TRUE)) . ' 00:00:00')),
			'gender' => trim($this->input->post('gender', TRUE)),
			'id_type' => trim($this->input->post('id_type', TRUE)),
			'id_no' => trim($this->input->post('id_no', TRUE)),
			'nationality' => trim($this->input->post('nationality', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'address' => trim($this->input->post('address', TRUE)),
			'city' => trim($this->input->post('city', TRUE)),
			'postal_code' => trim($this->input->post('postal_code', TRUE)),
			'state' => trim($this->input->post('state', TRUE)),
			'country' => trim($this->input->post('country', TRUE)),
			'origin_package_type' => trim($this->input->post('package_type', TRUE)),
			'package_type' => trim($this->input->post('package_type', TRUE)),
			'bank_name' => trim($this->input->post('bank_name', TRUE)),
			'bank_account_no' => trim($this->input->post('bank_account_no', TRUE)),
			'account_holder_name' => trim($this->input->post('account_holder_name', TRUE)),
			'bank_address' => trim($this->input->post('bank_address', TRUE)),
			'bank_country' => trim($this->input->post('bank_country', TRUE)),
			'bank_swift_code' => trim($this->input->post('bank_swift_code', TRUE)),
			'wallet_address' => trim($this->input->post('wallet_address', TRUE)),
			'contract_start_date' => time(),
			'contract_expiry_date' => strtotime('+' . TENURE_CONTRACT . ' days', time()),
			'active' => trim($this->input->post('active', TRUE)),
			'member_type' => trim($this->input->post('member_type', TRUE)),
			'introducer' => strtolower(trim($this->input->post('introducer', TRUE))),
			'allowed_withdraw' => trim($this->input->post('allowed_withdraw', TRUE)),
			'unlimited_withdraw' => trim($this->input->post('unlimited_withdraw', TRUE)),
			'allowed_transfer' => trim($this->input->post('allowed_transfer', TRUE)),
			'allowed_convert' => trim($this->input->post('allowed_convert', TRUE)),
			'allowed_topup' => trim($this->input->post('allowed_topup', TRUE)),
			'allowed_game' => trim($this->input->post('allowed_game', TRUE)),
			'total_invest' => 1,
			'allowed_invest' => 1,
			'insurance_date' => strtotime('+1 month', time()),
			'registered_by' => $direct_sponsor,
			'registered_date' => time()
    	);
		
		if($DBdata['gender'] == '') {
			$DBdata['gender'] = 1;
		}
		
		if($DBdata['id_type'] == '') {
			$DBdata['id_type'] = 1;
		}
		
		if($DBdata['username'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_username_must_fill_in_message')));
    		return false;
		}
		else if( ! preg_match('/^[a-z0-9]{6,16}$/', $DBdata['username'])) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_username_format_message')));
    		return false;
		}
		
		#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) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_username_unavailable_message')));
    		return false;
		}
		
		if($password == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_password_must_fill_in_message')));
    		return false;
		} 
		else if ( ! preg_match("/^[A-Za-z0-9!#$^*]{6,15}$/", $password)) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_password_format_message')));
    		return false;
		} 
		else if ($password != $confirm_password) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_confirm_password_not_match_message')));
    		return false;
		}
		
		#Check for introducer availbility
		$intro_type = 0;
		$introducer_id = 0;
		$query = $this->db->query("SELECT a.member_id, a.introducer_parent_ref FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.username = ? LIMIT 1", array($DBdata['introducer']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$intro_type = 1;
			$introducer_id = $row->member_id;
			
			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 . ',';
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_introducer_unavailable_message')));
			return false;
		}
		
		if($DBdata['full_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_full_name_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['package_type'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_must_fill_in_message')));
    		return false;
		}
		
		#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['package_type']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$package_price = $row->package_price;
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_no_found_message')));
    		return false;
		}
		
		if($DBdata['member_type'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_member_type_must_fill_in_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$DBdata['current_package_amt'] = $package_price;
		$DBdata['current_extra_amt'] = ($package_price * 0);
		$DBdata['total_capital'] = ($DBdata['current_package_amt'] + $DBdata['current_extra_amt'] );
		$DBdata['total_rolling'] = ($DBdata['current_package_amt'] * 5);
		
		$this->db->insert('sw_members', $DBdata);
		
		// if($DBdata['member_type'] == 2) {
			// $db_data['v_unit'] = ($package_price * 0.1);
		// }
		
		$db_data['member_id'] = $this->db->insert_id();
		
		$this->db->insert('sw_member_wallets', $db_data);
		
		//Insert game withdrawal
		$mgw_data = array(
			'from_member_id' => $db_data['member_id'],
			'from_member_username' => $DBdata['username'],
			'deposit_date' => time(),
			'deposit_amount' => $DBdata['current_package_amt'],
			'deposit_bonus' => $DBdata['current_extra_amt'],
		);	
		$this->db->insert('sw_member_game_withdrawals', $mgw_data);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_ADD_MEMBER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			// //CALL API - create account asiagaming1688
			// $response = $this->api_create_account(1, $DBdata['username'], $DBdata['password_origin'], $DBdata['package_type']);
			// $result_array = json_decode($response, TRUE);
			// if(isset($result_array['status']) && $result_array['status'] == 0) {
				// $this->db->query("UPDATE sw_members SET casino_plyid_1 = ? WHERE member_id = ? LIMIT 1", array($result_array['player_id'], $db_data['member_id']));
			// }
			
			//CALL API - create account luckyb3t
			$response_2 = $this->api_create_account(2, $DBdata['username'], $DBdata['password_origin'], $DBdata['package_type']);
			$result_array_2 = json_decode($response_2, TRUE);
			if(isset($result_array_2['status']) && $result_array_2['status'] == 0) {
				$this->db->query("UPDATE sw_members SET casino_plyid_2 = ? WHERE member_id = ? LIMIT 1", array($result_array_2['player_id'], $db_data['member_id']));
			}
			
			// //CALL API - topup credit asiagaming1688
			// if(isset($result_array['player_id']) && $result_array['player_id'] > 0) {
				// $this->api_topup_credit(1, $DBdata['username'], $package_price);
			// }
			
			//CALL API - topup credit luckyb3t
			if(isset($result_array_2['player_id']) && $result_array_2['player_id'] > 0) {
				$this->api_topup_credit(2, $DBdata['username'], $DBdata['total_capital']);
			}
			
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_successful_message')));
			return true;
		}
		else {
			return false;
		}
	}
	
	function get_member_details($member_id = NULL)
	{
		$query = $this->db->query("SELECT a.*, b.v_unit, b.v_unit2, b.v_unit3, b.v_unit4, b.v_unit5, b.v_unit6, b.v_unit7, b.v_unit8 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.member_id = ? LIMIT 1", array($member_id))->row_array();
	    
	    return $query;
	}
	
	function update_member_details($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$password = trim($this->input->post('password', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'full_name' => trim($this->input->post('full_name', TRUE)),
			'dob' => date('Y-m-d', strtotime(trim($this->input->post('dob', TRUE)) . ' 00:00:00')),
			'gender' => trim($this->input->post('gender', TRUE)),
			'id_type' => trim($this->input->post('id_type', TRUE)),
			'id_no' => trim($this->input->post('id_no', TRUE)),
			'nationality' => trim($this->input->post('nationality', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'address' => trim($this->input->post('address', TRUE)),
			'city' => trim($this->input->post('city', TRUE)),
			'postal_code' => trim($this->input->post('postal_code', TRUE)),
			'state' => trim($this->input->post('state', TRUE)),
			'country' => trim($this->input->post('country', TRUE)),
			'bank_name' => trim($this->input->post('bank_name', TRUE)),
			'bank_account_no' => trim($this->input->post('bank_account_no', TRUE)),
			'account_holder_name' => trim($this->input->post('account_holder_name', TRUE)),
			'bank_address' => trim($this->input->post('bank_address', TRUE)),
			'bank_country' => trim($this->input->post('bank_country', TRUE)),
			'bank_swift_code' => trim($this->input->post('bank_swift_code', TRUE)),
			'wallet_address' => trim($this->input->post('wallet_address', TRUE)),
			'active' => trim($this->input->post('active', TRUE)),
			'allowed_withdraw' => trim($this->input->post('allowed_withdraw', TRUE)),
			'unlimited_withdraw' => trim($this->input->post('unlimited_withdraw', TRUE)),
			'allowed_transfer' => trim($this->input->post('allowed_transfer', TRUE)),
			'allowed_convert' => trim($this->input->post('allowed_convert', TRUE)),
			'allowed_topup' => trim($this->input->post('allowed_topup', TRUE)),
			'allowed_game' => trim($this->input->post('allowed_game', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		if($DBdata['gender'] == '') {
			$DBdata['gender'] = 1;
		}
		
		if($DBdata['id_type'] == '') {
			$DBdata['id_type'] = 1;
		}
		
		if($password != '') {
			$DBdata['password_origin'] = $password;
			$DBdata['password'] = sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key')))));
			
			if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/", $password)) {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_password_format_message')));
				return false;
			}
		}
		
		if($security_password != '') {
			$DBdata['security_password_origin'] = $security_password;
			$DBdata['security_password'] = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		}
		
		if($DBdata['full_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_full_name_must_fill_in_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_MEMBER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_update_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_member_package($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'special_package_type' => trim($this->input->post('special_package_type', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		if($DBdata['special_package_type'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_must_fill_in_message')));
    		return false;
		}
		
		#Check for package type availbility
		$query = $this->db->query("SELECT package_id FROM sw_packages WHERE package_id = ? LIMIT 1", array($DBdata['special_package_type']));
		if($query->num_rows() == 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_no_found_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_MEMBER_PACKAGE_UPGRADE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_upgrade_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_member_level($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
		
		$special_level = trim($this->input->post('special_level', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'special_level' => (($special_level > 0 && $special_level < 5) ? $special_level : 0),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_MEMBER_LEVEL_UPGRADE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_level_upgrade_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_member_insurance_date($member_id = NULL)
    {
		set_time_limit(0);
		
		$this->lang->load('account_general', get_language());
	
		$insurance_date = strtotime(trim($this->input->post('insurance_date', TRUE)));
		$security_key = trim($this->input->post('security_key', TRUE));
		
		if($insurance_date == '') {
    		$insurance_date = strtotime(date('Y-m-d'));
		}
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		#Get origin introducer
		$old_insurance_date = '';
		$query = $this->db->query("SELECT insurance_date FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$old_insurance_date = $row->insurance_date;
		}
		
		$this->db->trans_start();
		
		$this->db->query("UPDATE sw_members SET insurance_date = ? WHERE member_id = ? LIMIT 1", array($insurance_date, $member_id));
		
		$db_data = array(
			'old_insurance_date' => $old_insurance_date,
			'new_insurance_date' => $insurance_date
		);
		$this->insert_user_log($this->session->userdata('user_id'), LOG_CHANGE_INSURANCE_DATE, json_encode($db_data));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_updated_insurance_date_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_member_reinvest($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$security_key = trim($this->input->post('security_key', TRUE));
		
        #Populate submitted data
	    $DBdata = array(
			'reinvest_type' => 1,
			'reinvest_package_type' => trim($this->input->post('reinvest_package_type', TRUE)),
			'reinvest_package_date' => time(),
			'member_id' => $member_id,
    	);
		
		if($DBdata['reinvest_package_type'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_must_fill_in_message')));
    		return false;
		}
		
		#Check for package type availbility
		$package_price = 0;
		// $addon_game_point = 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;
			// $addon_game_point = ($package_price * 0.1);
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_no_found_message')));
    		return false;
		}

		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		#Check for allow invest
		$query = $this->db->query("SELECT member_transaction_id FROM sw_member_game_withdrawals WHERE from_member_id = ? AND withdrawal_status = ? LIMIT 1", array($member_id, 0));
		if($query->num_rows() > 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_still_have_rolling_message')));
			return false;
		}
		
		$member_username = '';
		$query = $this->db->query("SELECT username FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$member_username = $row->username;
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_reinvest', $DBdata);
		
		$current_package_amt = $package_price;
		$current_extra_amt = ($package_price * 0);
		$total_capital = ($current_package_amt + $current_extra_amt);
		$total_rolling = ($current_package_amt * 5);
		
		$this->db->query("UPDATE sw_members SET total_invest = (total_invest + ?), total_reinvest = (total_reinvest + ?), allowed_invest = ?, current_package_amt = ?, current_extra_amt = ?, total_capital = ?, total_rolling = ? WHERE member_id = ? LIMIT 1", array(1, $current_package_amt, 1, $current_package_amt, $current_extra_amt, $total_capital, $total_rolling, $member_id));
		// $this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit + ?) WHERE member_id = ? LIMIT 1", array($addon_game_point, $member_id));
		
		//Insert game withdrawal
		$mgw_data = array(
			'from_member_id' => $member_id,
			'from_member_username' => $member_username,
			'deposit_date' => time(),
			'deposit_amount' => $current_package_amt,
			'deposit_bonus' => $current_extra_amt,
		);	
		$this->db->insert('sw_member_game_withdrawals', $mgw_data);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_MEMBER_REINVEST, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			// //CALL API - update player type asiagaming1688
			// $this->api_update_player_type(1, $member_username, $DBdata['reinvest_package_type']);
			
			//CALL API - update player type luckyb3t
			$this->api_update_player_type(2, $member_username, $DBdata['reinvest_package_type']);
			
			// //CALL API - topup credit asiagaming1688
			// $this->api_topup_credit(1, $member_username, $package_price);
			
			//CALL API - topup credit luckyb3t
			$this->api_topup_credit(2, $member_username, $total_capital);
			
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_reinvest_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_member_username($member_id = NULL)
    {
		set_time_limit(0);
		
		$this->lang->load('account_general', get_language());
	
		$username = trim($this->input->post('username', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
		
		if($username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_username_must_fill_in_message')));
    		return false;
		}
		else if( ! preg_match('/^[a-zA-Z0-9_]{6,32}$/', $username)) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_username_format_message')));
    		return false;
		}
		
		#Check for username availbility
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? AND member_id != ? LIMIT 1", array($username, $member_id));
		if($query->num_rows() > 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_username_unavailable_message')));
    		return false;
		}
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		#Get origin username
		$origin_username = '';
		$query = $this->db->query("SELECT username FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$origin_username = $row->username;
		}
		
		$this->db->trans_start();
		
		if($origin_username != '' AND $username != $origin_username) {
			$this->db->query("UPDATE sw_members SET username = ? WHERE username = ? LIMIT 1", array($username, $origin_username));
			$this->db->query("UPDATE sw_members SET introducer = ? WHERE introducer = ?", array($username, $origin_username));
			$this->db->query("UPDATE sw_members SET registered_by = ? WHERE registered_by = ?", array($username, $origin_username));
			$this->db->query("UPDATE sw_members SET modified_by = ? WHERE modified_by = ?", array($username, $origin_username));
			$db_data = array(
				'old_username' => $origin_username,
				'new_username' => $username
			);
			$this->insert_user_log($this->session->userdata('user_id'), LOG_CHANGE_MEMBER_USERNAME, json_encode($db_data));
		}
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_updated_username_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_existing_member_package($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$security_key = trim($this->input->post('security_key', TRUE));
		
        #Populate submitted data
	    $DBdata = array(
			'package_type' => trim($this->input->post('package_type', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		if($DBdata['package_type'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_must_fill_in_message')));
    		return false;
		}
		
		#Check for package type availbility
		$query = $this->db->query("SELECT package_id FROM sw_packages WHERE package_id = ? LIMIT 1", array($DBdata['package_type']));
		if($query->num_rows() == 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_package_type_no_found_message')));
    		return false;
		}
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$new_insurance_date = strtotime('+1 month', time());
		$this->db->query("UPDATE sw_members SET insurance_date = ? WHERE member_id = ? LIMIT 1", array($new_insurance_date, $member_id));
		
		$db_data = array(
			'member_id' => $member_id,
			'package_type' => $DBdata['package_type'],
			'modified_by' => $DBdata['modified_by'],
			'modified_date' => $DBdata['modified_date']
		);
		$this->insert_user_log($this->session->userdata('user_id'), LOG_CHANGE_MEMBER_PACKAGE, json_encode($db_data));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_updated_package_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_existing_member_type($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$security_key = trim($this->input->post('security_key', TRUE));
		
        #Populate submitted data
	    $DBdata = array(
			'member_type' => trim($this->input->post('member_type', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		if($DBdata['member_type'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_member_type_must_fill_in_message')));
    		return false;
		}
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$db_data = array(
			'member_id' => $member_id,
			'member_type' => $DBdata['member_type'],
			'modified_by' => $DBdata['modified_by'],
			'modified_date' => $DBdata['modified_date']
		);
		$this->insert_user_log($this->session->userdata('user_id'), LOG_CHANGE_MEMBER_TYPE, json_encode($db_data));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_updated_member_type_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_member_introducer_name($member_id = NULL)
    {
		set_time_limit(0);
		
		$this->lang->load('account_general', get_language());
	
		$introducer = trim($this->input->post('introducer', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
		
		if($introducer == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_introducer_unavailable_message')));
    		return false;
		}
		
		#Check for introducer availbility
		$new_introducer_id = 0;
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? LIMIT 1", array($introducer));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$new_introducer_id = $row->member_id;
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_introducer_unavailable_message')));
    		return false;
		}
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		#Get origin introducer
		$old_introducer_id = 0;
		$old_introducer = '';
		$query = $this->db->query("SELECT a.introducer, b.member_id FROM sw_members a, sw_members b WHERE (a.introducer = b.username) AND a.member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$old_introducer_id = $row->member_id;
			$old_introducer = ((strlen($row->introducer) >= 1) ? $row->introducer : '');
		}
		
		$this->db->trans_start();
		
		$this->db->query("UPDATE sw_members SET introducer = ? WHERE member_id = ? LIMIT 1", array($introducer, $member_id));
		
		$this->_restructure_introducer_structure();
		
		$db_data = array(
			'old_introducer' => $old_introducer,
			'new_introducer' => $introducer
		);
		$this->insert_user_log($this->session->userdata('user_id'), LOG_CHANGE_INTRODUCER_NAME, json_encode($db_data));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_updated_introducer_name_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function reset_member_login_password($member_id = NULL)
	{
		$this->lang->load('account_general', get_language());
		
		$this->db->trans_start();
		
		$rand_num = rand(100000, 999999);
		
		$password = sha1(md5(sha1(md5($rand_num)) . sha1(md5($this->config->item('encryption_key')))));
		
		$this->db->query("UPDATE sw_members SET password_origin = ?, password = ? WHERE member_id = ? LIMIT 1", array($rand_num, $password, $member_id));
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_RESET_MEMBER_LOGIN_PASSWORD, "");
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_reset_successful_message')));
			return true;
		}
		else {
			return false;
		}	
	}
	
	function reset_member_security_password($member_id = NULL)
	{
		$this->lang->load('account_general', get_language());
			
		$this->db->trans_start();
		
		$rand_num = rand(100000, 999999);
		
		$password = sha1(md5(sha1(md5($rand_num)) . sha1(md5($this->config->item('encryption_key')))));
		
		$this->db->query("UPDATE sw_members SET security_password_origin = ?, security_password = ? WHERE member_id = ? LIMIT 1", array($rand_num, $password, $member_id));
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_RESET_MEMBER_SECURITY_PASSWORD, "");
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_reset_successful_message')));
			return true;
		}
		else {
			return false;
		}	
	}
	
	function get_member_downline($username = NULL)
    {
		$this->lang->load('account_general', get_language());
		
		if($username == NULL || $username == '') {
			$default_query = $this->db->query("SELECT username FROM sw_members ORDER BY member_id ASC LIMIT 1")->row_array();
			$username = (isset($default_query['username']) ? $default_query['username'] : '');
		}
		
		$current_level = 1;
		$data = array();
		$tmp = array();
		$query = $this->db->query("SELECT a.member_id, LOWER(a.username) AS username, a.package_type, a.level, a.special_level, LOWER(a.introducer) AS introducer, ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) AS level, b.member_id AS parent_id FROM sw_members a LEFT JOIN sw_members b ON a.introducer = b.username WHERE a.username = ? LIMIT 1", array($username));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$child_parent_id = $row->member_id;
			$max_level = ($row->level + 2);
			
			array_push($data, array('member_id' => $row->member_id, 'username' => $row->username, 'package_type' => $row->package_type, 'level' => $row->level, 'special_level' => $row->special_level, 'parent_id' => 0, 'introducer' => $row->introducer));
			
			$sub_query = $this->db->query("SELECT a.member_id, LOWER(a.introducer) AS introducer, LOWER(a.username) AS username, a.package_type, a.level, a.special_level, ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) AS level, b.member_id AS parent_id FROM sw_members a LEFT JOIN sw_members b ON a.introducer = b.username WHERE a.introducer_parent_ref LIKE '%,$child_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($sub_query->num_rows() > 0) {
				foreach($sub_query->result() as $sub_row) {
					$count = ((isset($tmp[$sub_row->introducer])) ? (sizeof($tmp[$sub_row->introducer]) + 1) : 1);
					$tmp[$sub_row->introducer][$count] = array('member_id' => $sub_row->member_id, 'username' => $sub_row->username, 'package_type' => $sub_row->package_type, 'level' => $sub_row->level, 'special_level' => $sub_row->special_level, 'parent_id' => $sub_row->parent_id, 'introducer' => $sub_row->introducer);
				}
			}	
		}
		
		foreach($tmp as $k => $v) {
			foreach($v as $m => $n) {
				array_push($data, $n);
			}
		}
		
		$i = 1;
		$tmp2 = array();
		$data2 = array();
		foreach($data as $k => $v) {
			if( ! isset($tmp2[$v['username']])) {
				$tmp2[$v['username']] = $i;
			}
		
			$v['new_id'] = $i;
			array_push($data2, $v);
			
			$i++;
		}
		
		$i = 0;
		$json = '';
		foreach($data2 as $k => $v) {
			if($i == 0) {
				$new_parent_id = 0;
				
				if($v['introducer'] != '') {
					$up_arrow = "<p><a href=\"" . base_url() . "member/structure/" . $v['introducer'] . "/\"><img src=\"" . base_url() . "assets/image/arrow-up.png\" /></a></p>";
				}
				else {
					$up_arrow = '';
				}
			}
			else {
				$new_parent_id = (isset($tmp2[$v['introducer']]) ? $tmp2[$v['introducer']] : 0);
				$up_arrow = '';
			}
			
			$s_bg = 'securities_offline'; 
			$ranking = 'L: ' . $this->lang->line(get_level($v['level'])) . (($v['special_level'] > 0) ? ' (* ' . $this->lang->line(get_level($v['special_level'])) . ')' : '');
			$package_type = 'P: ' . $this->lang->line(get_package($v['package_type']));
			
			if($v['member_id'] > 0) {
				$json .= "{id: " . $v['new_id'] . ", name: '" . $up_arrow . "<div class=\"node-inner " . $s_bg . "\"><a href=\"" . base_url() . "member/structure/" . $v['username'] . "/\">" . $v['username'] . "<br />" . $ranking . "<br />" . $package_type . "</a></div>', parent: " . $new_parent_id . "},";
			}
			
			$i++;
		}
		
		return $json;
    }
	
	function member_transfer()
    {
		$this->lang->load('account_general', get_language());
	
		$from_member_username = trim($this->input->post('from_member_username', TRUE));
		$to_member_username = trim($this->input->post('to_member_username', TRUE));
		$currency_id = trim($this->input->post('currency_id', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => $currency_id,
			'from_member_username' => $from_member_username,
			'credit_amount' => $transaction_amount,
			'debit_amount' => $transaction_amount,
			'to_member_username' => $to_member_username,
			'status' => 1,
			'transaction_date' => time()
		);
		
		#Data validation
		if($transaction_amount == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_amount_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9.]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_invalid_amount_message')));
			return false;
    	}
		else if($from_member_username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_from_member_username_must_fill_in_message')));
    		return false;
		}
		else if($to_member_username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_to_member_username_must_fill_in_message')));
    		return false;
		}
		else if($security_key != SECURITY_KEY_HIGH) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_invalid_security_key_message')));
			return false;
		}
		
		#Check for from member email availability
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($from_member_username, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['from_member_id'] = $row->member_id;
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_invalid_from_member_username_message')));
    		return false;
		}
		
		#Check for to member email availability
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($to_member_username, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['to_member_id'] = $row->member_id;
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_invalid_to_member_username_message')));
    		return false;
		}
		
		#Check for available balance
		if($currency_id == 5) {
			$query = $this->db->query("SELECT v_unit5 FROM sw_member_wallets WHERE v_unit5 >= ? 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_unit5;
				$DBdata['to_credit_balance'] = ($row->v_unit5 - $transaction_amount);
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_insufficient_amount_message')));
				return false;
			}
			
			$query = $this->db->query("SELECT v_unit5 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_unit5;
				$DBdata['to_debit_balance'] = ($row->v_unit5 + $transaction_amount);
			}
		}
		else if($currency_id == 4) {
			$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 {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_insufficient_amount_message')));
				return false;
			}
			
			$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 if($currency_id == 3) {
			$query = $this->db->query("SELECT v_unit3 FROM sw_member_wallets WHERE v_unit3 >= ? 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_unit3;
				$DBdata['to_credit_balance'] = ($row->v_unit3 - $transaction_amount);
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_insufficient_amount_message')));
				return false;
			}
			
			$query = $this->db->query("SELECT v_unit3 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_unit3;
				$DBdata['to_debit_balance'] = ($row->v_unit3 + $transaction_amount);
			}
		}
		else if($currency_id == 2) {
			$query = $this->db->query("SELECT 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);
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_insufficient_amount_message')));
				return false;
			}
			
			$query = $this->db->query("SELECT v_unit2 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_unit2;
				$DBdata['to_debit_balance'] = ($row->v_unit2 + $transaction_amount);
			}
		}
		else {
			$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 {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_insufficient_amount_message')));
				return false;
			}
			
			$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($currency_id == 5) {
			#Credit
			$this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
		}
		else if($currency_id == 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 if($currency_id == 3) {
			#Credit
			$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
		}
		else if($currency_id == 2) {
			#Credit
			$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) 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_user_log($this->session->userdata('user_id'), LOG_TRANSFER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('transfer_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function member_topup()
    {
		$this->lang->load('account_general', get_language());
	
		$currency_id = trim($this->input->post('currency_id', TRUE));
		$to_member_username = trim($this->input->post('to_member_username', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$profit = trim($this->input->post('profit', TRUE));
		$currency_rate = trim($this->input->post('currency_rate', TRUE));
		$remark = trim($this->input->post('remark', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
		#Data validation
		if($transaction_amount == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_amount_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9.]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_amount_message')));
			return false;
    	}
		else if($to_member_username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_to_member_username_must_fill_in_message')));
    		return false;
		}
		else if($security_key != SECURITY_KEY_TOPUP) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$arr = explode(',', $to_member_username);
		for($i=0;$i<sizeof($arr);$i++) {
			if($arr[$i] != '') {
				#Check for to member username availability
				$query = $this->db->query("SELECT a.member_id, b.v_unit, b.v_unit2, b.v_unit3, b.v_unit4, b.v_unit5 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.username = ? LIMIT 1", array($arr[$i]));
				if($query->num_rows() > 0) {
					$row = $query->row();
					
					#Populate submitted data
					$DBdata = array(
						'transaction_type' => $currency_id,
						'debit_amount' => $transaction_amount,
						'to_member_id' => $row->member_id,
						'to_member_username' => $arr[$i],
						'profit' => (($profit > 0) ? $profit : 0),
						'currency_rate' => $currency_rate,
						'remark' => (($remark == 'Others') ? trim($this->input->post('remark_others', TRUE)) : $remark),
						'status' => 1,
						'transaction_date' => time()
					);
					
					if($currency_id == 5) {
						$DBdata['from_debit_balance'] = $row->v_unit5;
						$DBdata['to_debit_balance'] = ($row->v_unit5 + $transaction_amount);
					}
					else if($currency_id == 4) {
						$DBdata['from_debit_balance'] = $row->v_unit4;
						$DBdata['to_debit_balance'] = ($row->v_unit4 + $transaction_amount);
					}
					else if($currency_id == 3) {
						$DBdata['from_debit_balance'] = $row->v_unit3;
						$DBdata['to_debit_balance'] = ($row->v_unit3 + $transaction_amount);
					}
					else if($currency_id == 2) {
						$DBdata['from_debit_balance'] = $row->v_unit2;
						$DBdata['to_debit_balance'] = ($row->v_unit2 + $transaction_amount);
					}
					else {
						$DBdata['from_debit_balance'] = $row->v_unit;
						$DBdata['to_debit_balance'] = ($row->v_unit + $transaction_amount);
					}
					
					$this->db->insert('sw_member_topup', $DBdata);
					
					#Debit
					if($currency_id == 5) {
						$this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
					}
					else if($currency_id == 4) {
						$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 if($currency_id == 3) {
						$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
					}
					else if($currency_id == 2) {
						$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
					}
					else {
						$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_user_log($this->session->userdata('user_id'), LOG_TOPUP, json_encode($DBdata));
				}
			}
		}
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('topup_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function member_adjustment()
    {
		$this->lang->load('account_general', get_language());
	
		$currency_id = trim($this->input->post('currency_id', TRUE));
		$to_member_username = trim($this->input->post('to_member_username', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$remark = trim($this->input->post('remark', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => $currency_id,
			'credit_amount' => $transaction_amount,
			'to_member_username' => $to_member_username,
			'remark' => $remark,
			'status' => 1,
			'transaction_date' => time()
		);
		
		#Data validation
		if($transaction_amount == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_amount_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9.]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_invalid_amount_message')));
			return false;
    	}
		else if($to_member_username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_to_member_username_must_fill_in_message')));
    		return false;
		}
		else if($security_key != SECURITY_KEY_HIGH) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_invalid_security_key_message')));
			return false;
		}
		
		#Check for to member username availability
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($to_member_username, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['to_member_id'] = $row->member_id;
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_invalid_to_member_username_message')));
    		return false;
		}
		
		#Check for available balance
		if($currency_id == 5) {
			$query = $this->db->query("SELECT v_unit5 FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit5;
				$DBdata['to_credit_balance'] = ($row->v_unit5 - $transaction_amount);
			}
		}
		else if($currency_id == 4) {
			$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_credit_balance'] = $row->v_unit4;
				$DBdata['to_credit_balance'] = ($row->v_unit4 - $transaction_amount);
			}
		}
		else if($currency_id == 3) {
			$query = $this->db->query("SELECT v_unit3 FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit3;
				$DBdata['to_credit_balance'] = ($row->v_unit3 - $transaction_amount);
			}
		}
		else if($currency_id == 2) {
			$query = $this->db->query("SELECT v_unit2 FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_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);
			}
		}
		else {
			$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_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
			}
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_adjustment', $DBdata);
		
		#Debit
		if($currency_id == 5) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['to_member_id']));
		}
		else if($currency_id == 4) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit4 = (v_unit4 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['to_member_id']));
		}
		else if($currency_id == 3) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['to_member_id']));
		}
		else if($currency_id == 2) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['to_member_id']));
		}
		else {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['to_member_id']));
		}
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_ADJUSTMENT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('adjustment_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function member_platform_adjustment()
    {
		$this->lang->load('account_general', get_language());
	
		$platform_id = trim($this->input->post('platform_id', TRUE));
		$to_member_username = trim($this->input->post('to_member_username', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$remark = trim($this->input->post('remark', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
		#Data validation
		if($transaction_amount == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_amount_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9.]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_invalid_amount_message')));
			return false;
    	}
		else if($to_member_username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_to_member_username_must_fill_in_message')));
    		return false;
		}
		else if($security_key != SECURITY_KEY_HIGH) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_invalid_security_key_message')));
			return false;
		}
		
		#Check for to member username availability
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($to_member_username, 1));
		if($query->num_rows() == 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_invalid_to_member_username_message')));
    		return false;
		}
		
		#Check for available balance
		if($platform_id == 1 || $platform_id == 2) {
			//CALL API - game withdrawal asiagaming1688 or luckyb3t
			$this->api_game_withdrawal($platform_id, $to_member_username);
			
			//CALL API - topup debit asiagaming1688 or luckyb3t
			$response = $this->api_topup_debit($platform_id, $to_member_username, $transaction_amount, $remark);
			$result_array = json_decode($response, TRUE);
			if(isset($result_array['status']) && $result_array['status'] == 0) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('adjustment_platform_adjustment_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $result_array['msg']));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('adjustment_platform_adjustment_failed_message')));
    		return false;
		}
    }
	
	function update_member_setting()
	{
		$type = trim($this->input->post('type', TRUE));
		$member_id = trim($this->input->post('member_id', TRUE));
		
		#Check for member availability
		$query = $this->db->query("SELECT member_id, active, allowed_withdraw, unlimited_withdraw, allowed_transfer, allowed_convert, allowed_topup, allowed_game, casino_plyid_1, casino_plyid_2 FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
		
			$this->db->trans_start();
			
			if($type == 1) {
				if($row->allowed_withdraw == 0) {
					$DBdata = array(
						'allowed_withdraw' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_withdraw = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_withdraw'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
				else {
					$DBdata = array(
						'allowed_withdraw' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_withdraw = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_withdraw'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
			}
			else if($type == 2) {
				if($row->unlimited_withdraw == 0) {
					$DBdata = array(
						'unlimited_withdraw' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET unlimited_withdraw = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['unlimited_withdraw'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
				else {
					$DBdata = array(
						'unlimited_withdraw' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET unlimited_withdraw = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['unlimited_withdraw'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
			}
			else if($type == 3) {
				if($row->allowed_transfer == 0) {
					$DBdata = array(
						'allowed_transfer' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_transfer = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_transfer'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
				else {
					$DBdata = array(
						'allowed_transfer' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_transfer = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_transfer'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
			}
			else if($type == 4) {
				if($row->active == 0) {
					$DBdata = array(
						'active' => 1,
						'allowed_withdraw' => 1,
						'allowed_transfer' => 1,
						'allowed_convert' => 1,
						'allowed_topup' => 1,
						'allowed_game' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET active = ?, allowed_withdraw = ?, allowed_transfer = ?, allowed_convert = ?, allowed_topup = ?, allowed_game = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['active'], $DBdata['allowed_withdraw'], $DBdata['allowed_transfer'], $DBdata['allowed_convert'], $DBdata['allowed_topup'], $DBdata['allowed_game'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
				else {
					$DBdata = array(
						'active' => 0,
						'allowed_withdraw' => 0,
						'allowed_transfer' => 0,
						'allowed_convert' => 0,
						'allowed_topup' => 0,
						'allowed_game' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET active = ?, allowed_withdraw = ?, allowed_transfer = ?, allowed_convert = ?, allowed_topup = ?, allowed_game = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['active'], $DBdata['allowed_withdraw'], $DBdata['allowed_transfer'], $DBdata['allowed_convert'], $DBdata['allowed_topup'], $DBdata['allowed_game'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
			}
			else if($type == 5) {
				if($row->allowed_topup == 0) {
					$DBdata = array(
						'allowed_topup' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_topup = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_topup'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
				else {
					$DBdata = array(
						'allowed_topup' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_topup = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_topup'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
			}
			else if($type == 6) {
				if($row->allowed_convert == 0) {
					$DBdata = array(
						'allowed_convert' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_convert = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_convert'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
				else {
					$DBdata = array(
						'allowed_convert' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_convert = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_convert'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				}
			}
			else if($type == 7) {
				$otherdb1 = $this->load->database('otherdb1', TRUE);
				$otherdb2 = $this->load->database('otherdb2', TRUE);
		
				if($row->allowed_game == 0) {
					$DBdata = array(
						'allowed_game' => 1,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_game = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_game'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				
					$otherdb1->query("UPDATE bctp_players SET active = ? WHERE player_id = ? LIMIT 1", array(1, $row->casino_plyid_1));
					$otherdb2->query("UPDATE bctp_players SET active = ? WHERE player_id = ? LIMIT 1", array(1, $row->casino_plyid_2));
				}
				else {
					$DBdata = array(
						'allowed_game' => 0,
						'modified_by' => $this->session->userdata('username'),
						'modified_date' => time()
					);
					$this->db->query("UPDATE sw_members SET allowed_game = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_game'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
				
					$otherdb1->query("UPDATE bctp_players SET active = ? WHERE player_id = ? LIMIT 1", array(0, $row->casino_plyid_1));
					$otherdb2->query("UPDATE bctp_players SET active = ? WHERE player_id = ? LIMIT 1", array(0, $row->casino_plyid_2));
				}
			}
			
			$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_MEMBER, json_encode($DBdata));
			
			$this->db->trans_complete();
		}
	}
	
	function update_withdrawal_status($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'status' => $status
    	);
		
		$query = $this->db->query("SELECT member_transaction_id, from_member_id, credit_amount, charges FROM sw_member_withdraw WHERE member_transaction_id = ? AND status = ? LIMIT 1", array($transaction_id, 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->where('member_transaction_id', $transaction_id);
			$this->db->where('status', 0);
			$this->db->limit(1);
			$this->db->update('sw_member_withdraw', $DBdata);
			
			if($status == 2) {
				$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($row->credit_amount, $row->from_member_id));
			}
			
			$db_data = array(
				'member_transaction_id' => $row->member_transaction_id,
				'from_member_id' => $row->from_member_id,
				'credit_amount' => $row->credit_amount,
				'charges' => $row->charges,
				'status' => $status
			);
			$this->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_MEMBER_WITHDRAWAL_STATUS, json_encode($db_data));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('withdrawal_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('withdrawal_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('withdrawal_fail_message')));
			return false;
		}
	}
	
	function update_withdrawal_status_platform($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
		
		// $otherdb1 = $this->load->database('otherdb1', TRUE);
		$otherdb2 = $this->load->database('otherdb2', TRUE);
	
		$query = $this->db->query("SELECT a.member_transaction_id, a.deposit_date, a.deposit_amount, a.deposit_bonus, a.p1_w_id, a.p1_w_amount, a.p2_w_id, a.p2_w_amount, a.profit, b.member_id, b.username, b.casino_plyid_1, b.casino_plyid_2, c.v_unit2 FROM sw_member_game_withdrawals a, sw_members b, sw_member_wallets c WHERE ((a.from_member_id = b.member_id) AND (b.member_id = c.member_id)) AND a.member_transaction_id = ? AND a.withdrawal_status = ? LIMIT 1", array($transaction_id, 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->query("UPDATE sw_member_game_withdrawals SET withdrawal_status = ?, updated_by = ?, updated_date = ? WHERE member_transaction_id = ? AND withdrawal_status = ? LIMIT 1", array($status, $this->session->userdata('username'), time(), $transaction_id, 0));
			
			if($status == 1) {
				//Update game point and bonus
				// $actual_amount = (($row->p1_w_amount + $row->p2_w_amount) - $row->deposit_amount);
				$actual_amount = $row->deposit_amount;
				$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($actual_amount, $row->member_id));
				$this->db->query("UPDATE sw_members SET allowed_invest = ?, total_profit = (total_profit + ?) WHERE member_id = ? LIMIT 1", array(0, $row->profit, $row->member_id));
				
				$DBdata = array(
					'from_member_id' => $row->member_id,
					'from_member_username' => $row->username,
					'amount' => $row->profit,
					'status' => 0,
					'transaction_date' => time()
				);
				
				$this->db->insert('sw_member_daily_bonus', $DBdata);
				
				$DBdata2 = array(
					'transaction_type' => 2,
					'payment_method' => 0,
					'transaction_amount' => $actual_amount,
					'to_member_id' => $row->member_id,
					'to_member_username' => $row->username,
					'from_debit_balance' => $row->v_unit2,
					'debit_amount' => $actual_amount,
					'to_debit_balance' => ($row->v_unit2 + $actual_amount),
					'profit' => $row->profit,
					'status' => 1,
					'currency_rate' => 0,
					'transaction_date' => time()
				);
				
				$this->db->insert('sw_member_topup', $DBdata2);
				
				// if($row->p1_w_id > 0) {
					// $otherdb1->query("UPDATE bctp_withdrawals SET status = ?, updated_by = ?, updated_date = ? WHERE withdrawal_id = ? LIMIT 1", array(1, $this->session->userdata('username'), time(), $row->p1_w_id));
				// }
				
				if($row->p2_w_id > 0) {
					$otherdb2->query("UPDATE bctp_withdrawals SET status = ?, updated_by = ?, updated_date = ? WHERE withdrawal_id = ? LIMIT 1", array(1, $this->session->userdata('username'), time(), $row->p2_w_id));
				}
				
				// if($row->p1_w_id > 0 && $row->p2_w_id == 0) {
					// $DBdata3 = array(
						// 'withdrawal_type' => 1,
						// 'amount' => 0,
						// 'player_id' => $row->casino_plyid_2,
						// 'withdrawal_ip' => $this->input->ip_address(),
						// 'transaction_code' => '',
						// 'transaction_code_alias' => '',
						// 'status' => 1,
						// 'created_by' => $this->session->userdata('username'),
						// 'created_date' => time(),
						// 'updated_by' => $this->session->userdata('username'),
						// 'updated_date' => time()
					// );
					
					// $otherdb2->insert('bctp_withdrawals', $DBdata3);
				// }
				// else if($row->p1_w_id == 0 && $row->p2_w_id > 0) {
					// $DBdata3 = array(
						// 'withdrawal_type' => 1,
						// 'amount' => 0,
						// 'player_id' => $row->casino_plyid_1,
						// 'withdrawal_ip' => $this->input->ip_address(),
						// 'transaction_code' => '',
						// 'transaction_code_alias' => '',
						// 'status' => 1,
						// 'created_by' => $this->session->userdata('username'),
						// 'created_date' => time(),
						// 'updated_by' => $this->session->userdata('username'),
						// 'updated_date' => time()
					// );
					
					// $otherdb1->insert('bctp_withdrawals', $DBdata3);
				// }
			}
			else if($status == 2) {
				$mgw_data = array(
					'from_member_id' => $row->member_id,
					'from_member_username' => $row->username,
					'deposit_date' => $row->deposit_date,
					'deposit_amount' => $row->deposit_amount,
					'deposit_bonus' => $row->deposit_bonus,
				);	
				$this->db->insert('sw_member_game_withdrawals', $mgw_data);
		
				// if($row->p1_w_id > 0) {
					// $points_1 = 0;
					// $s_query_1 = $otherdb1->query("SELECT points FROM bctp_players WHERE player_id = ? LIMIT 1", array($row->casino_plyid_1));
					// if($s_query_1->num_rows() > 0) {
						// $s_row_1 = $s_query_1->row();
						// $points_1 = $s_row_1->points;
					// }
					
					// $otherdb1->query("UPDATE bctp_players SET points = (points + ?) WHERE player_id = ? LIMIT 1", array($row->p1_w_amount, $row->casino_plyid_1));
					// $otherdb1->query("UPDATE bctp_withdrawals SET status = ?, updated_by = ?, updated_date = ? WHERE withdrawal_id = ? LIMIT 1", array(2, $this->session->userdata('username'), time(), $row->p1_w_id));
				
					// $DBdata = array(
						// 'transfer_type' => 8,
						// 'username' => $row->username,
						// 'deposit_amount' => $row->p1_w_amount,
						// 'balance_before' => $points_1,
						// 'balance_after' => ($points_1 + $row->p1_w_amount),
						// 'remark' => '',
						// 'report_date' => time(),
						// 'executed_by' => $this->session->userdata('username')
					// );
					
					// $otherdb1->insert('bctp_cash_transfer_report', $DBdata);
				// }
				
				if($row->p2_w_id > 0) {
					$points_2 = 0;
					$s_query_2 = $otherdb2->query("SELECT points FROM bctp_players WHERE player_id = ? LIMIT 1", array($row->casino_plyid_2));
					if($s_query_2->num_rows() > 0) {
						$s_row_2 = $s_query_2->row();
						$points_2 = $s_row_2->points;
					}
					
					$otherdb2->query("UPDATE bctp_players SET points = (points + ?) WHERE player_id = ? LIMIT 1", array($row->p2_w_amount, $row->casino_plyid_2));
					$otherdb2->query("UPDATE bctp_withdrawals SET status = ?, updated_by = ?, updated_date = ? WHERE withdrawal_id = ? LIMIT 1", array(2, $this->session->userdata('username'), time(), $row->p2_w_id));
				
					$DBdata2 = array(
						'transfer_type' => 8,
						'username' => $row->username,
						'deposit_amount' => $row->p2_w_amount,
						'balance_before' => $points_2,
						'balance_after' => ($points_2 + $row->p2_w_amount),
						'remark' => '',
						'report_date' => time(),
						'executed_by' => $this->session->userdata('username')
					);
					
					$otherdb2->insert('bctp_cash_transfer_report', $DBdata2);
				}
			}
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('withdrawal_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('withdrawal_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('withdrawal_fail_message')));
			return false;
		}
	}
	
	function get_game_withdrawal_details($transaction_id = NULL)
	{
		$query = $this->db->query("SELECT * FROM sw_member_game_withdrawals WHERE member_transaction_id = ? LIMIT 1", array($transaction_id))->row_array();
	    
	    return $query;
	}
	
	function update_game_withdrawal_details($transaction_id = NULL, $type = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$security_key = trim($this->input->post('security_key', TRUE));
		
		if($type == 2) {
			#Populate submitted data
			$DBdata = array(
				'p1_w_amount' => trim($this->input->post('p1_w_amount', TRUE)),
				'updated_by' => $this->session->userdata('username'),
				'updated_date' => time()
			);
			
			
			if( ! preg_match("/^([0-9.-]+)$/", $DBdata['p1_w_amount'])) {
				$DBdata['p1_w_amount'] = 0;
			}
			
			$query = $this->db->query("SELECT member_transaction_id, deposit_amount, lend, p2_w_amount FROM sw_member_game_withdrawals WHERE member_transaction_id = ? LIMIT 1", array($transaction_id));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$DBdata['deposit_amount'] = ((($DBdata['p1_w_amount'] + $row->p2_w_amount) - $row->lend) + 200);
				$DBdata['profit'] = (((($DBdata['p1_w_amount'] + $row->p2_w_amount) - $row->lend) + 200) - $row->deposit_amount);
			}
		}
		else {
			#Populate submitted data
			$DBdata = array(
				'profit' => trim($this->input->post('profit', TRUE)),
				'deposit_amount' => trim($this->input->post('deposit_amount', TRUE)),
				'updated_by' => $this->session->userdata('username'),
				'updated_date' => time()
			);
			
			if( ! preg_match("/^([0-9.-]+)$/", $DBdata['profit'])) {
					$DBdata['profit'] = 0;
			}
			
			if( ! preg_match("/^([0-9.-]+)$/", $DBdata['deposit_amount'])) {
				$DBdata['deposit_amount'] = 0;
			}
		}	
		
		if($security_key != SECURITY_KEY_HIGH) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('game_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_transaction_id', $transaction_id);
		$this->db->where('withdrawal_status', 0);
		$this->db->limit(1);
		$this->db->update('sw_member_game_withdrawals', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_PROFIT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('game_profit_update_successful_message')));
				
			return true;
		}
		else {
			return false;
		}
    }
	
	function delete_member($member_id = NULL)
	{
		set_time_limit(0);
		
		$this->lang->load('account_general', get_language());
	
		$security_key = trim($this->input->post('security_key', TRUE));
		
		if($security_key != SECURITY_KEY_FOR_EDIT_MEMBER) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->delete('sw_members');
		
		$this->db->where('member_id', $member_id);
		$this->db->limit(1);
		$this->db->delete('sw_member_wallets');
		
		$this->_restructure_introducer_structure();
		
		$DBdata = array(
			'member_id' => $member_id,
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		$this->insert_user_log($this->session->userdata('user_id'), LOG_DELETE_MEMBER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('registration_deleted_successful_message')));
			return true;
		}
		else {
			return false;
		}
	}
	
	function get_member_reinvest($member_id = NULL)
	{
		$query = $this->db->query("SELECT * FROM sw_member_reinvest WHERE reinvest_type = ? AND member_id = ? ORDER BY reinvest_package_date DESC", array(1, $member_id));
		
		return $query;
	}
	
	function _restructure_introducer_structure()
	{
		//Prepare member list
		$member_lists = array();
		$member_info_lists = array();
		$query = $this->db->query("SELECT member_id, introducer, username FROM sw_members ORDER BY member_id ASC");
		if($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$username = strtolower($row->username);
				$introducer = strtolower($row->introducer);
				
				array_push($member_lists, array('member_id' => $row->member_id, 'username' => $username, 'introducer' => $introducer));
				
				$member_info_lists[$username]['member_id'] = $row->member_id;
				$member_info_lists[$username]['username'] = $username;
				$member_info_lists[$username]['introducer'] = $introducer;
				$member_info_lists[$username]['introducer_parent_ref'] = '';
			}	
		}
		
		for($i=0;$i<sizeof($member_lists);$i++) {
			$username = $member_lists[$i]['username'];
			$introducer = $member_lists[$i]['introducer'];
			
			if(isset($member_info_lists[$introducer]['member_id'])) {
				//Rearrange parent
				$group_upline = $member_info_lists[$introducer]['introducer'];
				
				$search = TRUE;
				while ($search == TRUE) {
					if(isset($member_info_lists[$group_upline]['member_id'])) {
						if($member_info_lists[$username]['introducer_parent_ref'] == '') {
							$member_info_lists[$username]['introducer_parent_ref'] = ',' . $member_info_lists[$group_upline]['member_id'] . ',';
						}
						else {
							$member_info_lists[$username]['introducer_parent_ref'] = ',' . $member_info_lists[$group_upline]['member_id'] . $member_info_lists[$username]['introducer_parent_ref'];
						}
						
						$group_upline = $member_info_lists[$group_upline]['introducer'];
					}
					else {
						$search = FALSE;
					}
				}
				
				if($member_info_lists[$username]['introducer_parent_ref'] == '') {
					$member_info_lists[$username]['introducer_parent_ref'] = ',' . $member_info_lists[$introducer]['member_id'] . ',';
				}
				else {
					$member_info_lists[$username]['introducer_parent_ref'] .= $member_info_lists[$introducer]['member_id'] . ',';
				}
			}
		}
		
		for($i=0;$i<sizeof($member_lists);$i++) {
			$username = $member_lists[$i]['username'];
			$member_id = $member_info_lists[$username]['member_id'];
			$introducer_parent_ref = $member_info_lists[$username]['introducer_parent_ref'];
			$sql = "UPDATE sw_members SET introducer_parent_ref = '$introducer_parent_ref' WHERE member_id = $member_id LIMIT 1";
			$this->db->query($sql);
		}
	}
	
	function get_user_details()
    {
        $query = $this->db->query("SELECT real_name, username, mobile_no, email FROM sw_users WHERE user_id = ? AND username = ? LIMIT 1", array($this->session->userdata('user_id'), $this->session->userdata('username')))->row_array();
	    
	    return $query;
    }
	
	function update_user_details()
    {
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'real_name' => trim($this->input->post('real_name', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		#Data validation
		if($DBdata['real_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_real_name_must_fill_in_message')));
    		return false;
    	}
		else if($DBdata['mobile_no'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_mobile_no_must_fill_in_message')));
    		return false;
    	}
		else if($DBdata['email'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_email_must_fill_in_message')));
    		return false;
		} 
		else if (!isEmail($DBdata['email'])) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_invalid_email_message')));
    		return false;
    	}
		
		$this->db->trans_start();
		
		$this->db->where('user_id', $this->session->userdata('user_id'));
		$this->db->where('username', $this->session->userdata('username'));
		$this->db->limit(1);
		$this->db->update('sw_users', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_PROFILE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('profile_update_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function change_login_password()
    {
		$this->lang->load('account_general', get_language());
	
		$old_password = trim($this->input->post('old_password', TRUE));
		$new_password = trim($this->input->post('new_password', TRUE));
		$confirm_password = trim($this->input->post('confirm_password', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'password' => sha1(md5(sha1(md5($new_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		#Data validation
		if($old_password == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_old_password_must_fill_in_message')));
    		return false;
    	}
		else if($new_password == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_new_password_must_fill_in_message')));
    		return false;
		} else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$new_password)) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_new_password_format_message')));
			return false;
    	}
		else if($new_password != $confirm_password) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_new_password_not_match_message')));
    		return false;
    	}
		
		#Check for existing password
		$encrypted_password = sha1(md5(sha1(md5($old_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT user_id FROM sw_users WHERE user_id = ? AND username = ? AND password = ? LIMIT 1", array($this->session->userdata('user_id'), $this->session->userdata('username'), $encrypted_password));
		if($query->num_rows() == 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('profile_invalid_old_password_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('user_id', $this->session->userdata('user_id'));
		$this->db->where('username', $this->session->userdata('username'));
		$this->db->limit(1);
		$this->db->update('sw_users', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_CHANGE_LOGIN_PASSWORD, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('profile_change_login_password_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function get_user_unread_message()
	{
		$query = $this->db->query("SELECT COUNT(message_id) AS total FROM sw_member_messages WHERE admin_read = ?", array(1))->row();
		$total = $query->total;
		
		return $total;
	}
	
	function user_compose_message()
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'subject' => trim($this->input->post('message_subject', TRUE)),
			'message' => trim($this->input->post('message_message', TRUE)),
			'message_type' => MESSAGE_INBOX,
			'member_read' => 1,
			'admin_read' => 0,
			'member_id' => trim($this->input->post('member_id', TRUE)),
			'created_by' => $this->session->userdata('username'),
			'created_date' => time()
    	);
		
		#Data validation
		if($DBdata['subject'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('message_subject_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('message_message_must_fill_in_message')));
    		return false;
		} 
		
		$this->db->trans_start();
		
		$this->db->query('UPDATE sw_member_messages SET admin_reply = ? WHERE message_id = ? LIMIT 1', array(trim($this->input->post('is_reply', TRUE)), trim($this->input->post('message_id', TRUE))));
		
		$this->db->insert('sw_member_messages', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_MESSAGE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('message_successful_message')));
			return true;
		}
		else {
			return false;
		}
	}
	
	function user_admin_compose_message()
	{
		set_time_limit(0);
		
		$this->lang->load('account_general', get_language());
	
		$subject = trim($this->input->post('message_subject', TRUE));
		$message = trim($this->input->post('message_message', TRUE));
		$include_usernames = trim($this->input->post('include_usernames', TRUE));
		$exclude_usernames = trim($this->input->post('exclude_usernames', TRUE));
		$search_register_date = trim($this->input->post('search_register_date', TRUE));
		$search_start_date = trim($this->input->post('search_start_date', TRUE));
		$search_end_date = trim($this->input->post('search_end_date', TRUE));
		$search_member_type = ($this->input->post('search_member_type', TRUE) != '') ? implode(',', $this->input->post('search_member_type', TRUE)) : '';
		
		#Data validation
		if($subject == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('message_subject_must_fill_in_message')));
    		return false;
		} 
		else if($message == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('message_message_must_fill_in_message')));
    		return false;
		}

		$sql = 'SELECT member_id FROM sw_members WHERE active = 1';
		
		if($include_usernames != '') {
			$arr = explode(',', $include_usernames);
			$arr = implode("','", $arr);
			
			$query = $this->db->query("SELECT member_id FROM sw_members WHERE username IN('" . $arr . "')");
			if($query->num_rows > 0) {
				$ids = '';
				foreach($query->result() as $row) {
					$ids .= $row->member_id . ',';
				}
				
				if($ids != '') {
					$ids = substr($ids, 0, -1);
					$sql .= " AND member_id IN(" . $ids . ")";
				}
			}
			else {
				$sql .= " AND member_id = 9999999999";
			}
		}
		
		if($exclude_usernames != '') {
			$arr = explode(',', $exclude_usernames);
			$arr = implode("','", $arr);
			
			$query = $this->db->query("SELECT member_id FROM sw_members WHERE username IN('" . $arr . "')");
			if($query->num_rows > 0) {
				$ids = '';
				foreach($query->result() as $row) {
					$ids .= $row->member_id . ',';
				}
				
				if($ids != '') {
					$ids = substr($ids, 0, -1);
					$sql .= " AND member_id NOT IN(" . $ids . ")";
				}
			}
		}
		
		if($search_register_date == 2) {
			$start_date = strtotime(date('Y-m-d 00:00:00', strtotime($search_start_date)));
			$end_date = strtotime(date('Y-m-d 23:59:59', strtotime($search_end_date)));
			$sql .= " AND (contract_start_date >= '" .  $start_date . "' AND contract_start_date <= '" .  $end_date . "')";
		}
		
		if($search_member_type != '') {
			$sql .= " AND member_type IN(" . $search_member_type . ")";
		}
		
		//$this->db->trans_start();
		
		$member_lists = array();
		$query = $this->db->query($sql);
		if($query->num_rows > 0) {
			$i=0;
			foreach($query->result() as $row) {
				$member_lists[$i] = $row->member_id;
				$i++;
			}
		}	
		
		for($i=0;$i<sizeof($member_lists);$i++) {
			$DBdata = array(
				'subject' => $subject,
				'message' => $message,
				'message_type' => MESSAGE_INBOX,
				'member_read' => 1,
				'admin_read' => 0,
				'member_id' => $member_lists[$i],
				'created_by' => $this->session->userdata('username'),
				'created_date' => time()
			);
			
			$this->db->insert('sw_member_messages', $DBdata);
			
			$this->insert_user_log($this->session->userdata('user_id'), LOG_MESSAGE, json_encode($DBdata));
		}
		
		//$this->db->trans_complete();
		
		//$rs = $this->db->trans_status();
		
		//if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('message_successful_message')));
			return true;
		//}
		//else {
			//return false;
		//}
	}
	
	function get_member_message_details_by_read($message_id = NULL)
    {
        $query = $this->db->query("SELECT a.message_id, a.subject, a.message, a.admin_read, a.member_id, b.username FROM sw_member_messages a, sw_members b WHERE (a.member_id = b.member_id) AND a.message_id = ? LIMIT 1", array($message_id))->row_array();
	    
		if(isset($query['admin_read']) AND $query['admin_read'] == 1) {
			$this->db->query("UPDATE sw_member_messages SET admin_read = ? WHERE message_id = ? LIMIT 1", array(0, $query['message_id']));
		}
		
	    return $query;
    }
	
	function get_member_message_details_by_reply($message_id = NULL)
    {
        $query = $this->db->query("SELECT a.message_id, a.subject, a.message, a.admin_read, a.member_id, b.username FROM sw_member_messages a, sw_members b WHERE (a.member_id = b.member_id) AND a.message_id = ? LIMIT 1", array($message_id))->row_array();
	    
		if(isset($query['admin_read']) AND $query['admin_read'] == 1) {
			$this->db->query("UPDATE sw_member_messages SET admin_read = ? WHERE message_id = ? LIMIT 1", array(0, $query['message_id']));
		}
		
		if(isset($query['subject']) AND isset($query['message'])) {
			$query['message_subject'] = 'RE: ' . $query['subject'];
			$query['message_message'] = "<br /><br /><br />-------------------------------------<br />" . date('Y-m-d H:i:s', time()) . "<br /><br />" . $query['message'];
		}
		
	    return $query;
    }
	
	function add_admin()
	{
		$this->lang->load('account_general', get_language());
	
		$password = trim($this->input->post('password', TRUE));
		$modules = $this->input->post('modules', TRUE);
		
        #Populate submitted data
	    $DBdata = array(
			'real_name' => trim($this->input->post('real_name', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			'username' => trim($this->input->post('username', TRUE)),
			'password' => sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key'))))),
			'user_type' => ADMIN,
			'status' => trim($this->input->post('status', TRUE)),
			'registered_by' => $this->session->userdata('username'),
			'registered_date' => time()
    	);
		
		#Data validation
		if($DBdata['real_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_real_name_must_fill_in_message')));
    		return false;
    	}
		else if($DBdata['username'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_username_must_fill_in_message')));
    		return false;
    	}
		else if($password == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_password_must_fill_in_message')));
    		return false;
    	}
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$password)) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_password_format_message')));
    		return false;
		}
		else if($password != trim($this->input->post('confirm_password', TRUE))) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_password_not_match_message')));
    		return false;
    	}
		
		#Check for username availability
		$query = $this->db->query("SELECT user_id FROM sw_users WHERE username = ? LIMIT 1", array($DBdata['username']));
		if($query->num_rows() > 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_username_not_available_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_users', $DBdata);
		$new_admin_id = $this->db->insert_id();
		
		if($modules != '') {
			foreach ($modules as $key => $var) {
				$this->db->insert('sw_user_modules', array('user_id' => $new_admin_id, 'module' => $var));
			}
		}
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_ADD_ADMIN, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('admin_successful_message')));
			return true;
		}
		else {
			return false;
		}
	}
	
	function get_admin_details($admin_id = NULL)
	{
		$query = $this->db->query("SELECT * FROM sw_users WHERE user_id = ? AND user_type = ? LIMIT 1", array($admin_id, ADMIN))->row_array();
	    
	    return $query;
	}
	
	function get_admin_modules($admin_id = NULL)
	{
		$arr = array();
		
		$query = $this->db->query("SELECT * FROM sw_user_modules WHERE user_id = ?", array($admin_id));
		if($query->num_rows() > 0) {
			foreach ($query->result() as $row) {
				array_push($arr, $row->module);
			}
		}
		
	    return $arr;
	}
	
	function update_admin_details($admin_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$password = trim($this->input->post('password', TRUE));
		$modules = $this->input->post('modules', TRUE);
		
        #Populate submitted data
		$DBdata = array(
			'real_name' => trim($this->input->post('real_name', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			'status' => trim($this->input->post('status', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		if($DBdata['real_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_real_name_must_fill_in_message')));
    		return false;
    	}
		
		if($password != '') {
    		if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$password)) {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_password_format_message')));
				return false;
			}
			else if($password != trim($this->input->post('confirm_password', TRUE))) {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('admin_password_not_match_message')));
				return false;
			}
    	}
		
		$this->db->trans_start();
		
		$this->db->where('user_id', $admin_id);
		$this->db->limit(1);
		$this->db->update('sw_users', $DBdata);
		
		if($modules != '') {
			#Delete all modules for the admin
			$this->db->query("DELETE FROM sw_user_modules WHERE user_id = '" . $admin_id . "'");
		
			foreach ($modules as $key => $var) {
				$this->db->insert('sw_user_modules', array('user_id' => $admin_id, 'module' => $var));
			}
		}
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_ADMIN, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('admin_update_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function delete_admin($admin_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$this->db->trans_start();
		
		$this->db->where('user_id', $admin_id);
		$this->db->where('user_type', ADMIN);
		$this->db->limit(1);
		$this->db->delete('sw_users');
		
		$this->db->query("DELETE FROM sw_user_modules WHERE user_id = '" . $admin_id . "'");
		
		$DBdata['user_id'] =  $admin_id;
		$this->insert_user_log($this->session->userdata('user_id'), LOG_DELETE_ADMIN, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('admin_delete_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function add_announcement()
	{
		$this->lang->load('account_general', get_language());
		
        #Populate submitted data
	    $DBdata = array(
			'title_en' => trim($this->input->post('title_en', TRUE)),
			'title_zh_cn' => trim($this->input->post('title_zh_cn', TRUE)),
			'title_zh_hk' => trim($this->input->post('title_zh_hk', TRUE)),
			'message_en' => trim($this->input->post('message_en', TRUE)),
			'message_zh_cn' => trim($this->input->post('message_zh_cn', TRUE)),
			'message_zh_hk' => trim($this->input->post('message_zh_hk', TRUE)),
			'status' => trim($this->input->post('status', TRUE)),
			'created_by' => $this->session->userdata('username'),
			'created_date' => time()
    	);
		
		#Data validation
		if($DBdata['title_en'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_title_en_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message_en'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_content_en_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['title_zh_cn'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_title_zh_cn_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message_zh_cn'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_content_zh_cn_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['title_zh_hk'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_title_zh_hk_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message_zh_hk'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_content_zh_hk_must_fill_in_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_announcements', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_ADD_ANNOUNCEMENT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('announcement_successful_message')));
			return true;
		}
		else {
			return false;
		}
	}
	
	function get_announcement_details($announcement_id = NULL)
	{
		$query = $this->db->query("SELECT * FROM sw_announcements WHERE announcement_id = ? LIMIT 1", array($announcement_id))->row_array();
	    
	    return $query;
	}
	
	function update_announcement_details($announcement_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
		$DBdata = array(
			'title_en' => trim($this->input->post('title_en', TRUE)),
			'title_zh_cn' => trim($this->input->post('title_zh_cn', TRUE)),
			'title_zh_hk' => trim($this->input->post('title_zh_hk', TRUE)),
			'message_en' => trim($this->input->post('message_en', TRUE)),
			'message_zh_cn' => trim($this->input->post('message_zh_cn', TRUE)),
			'message_zh_hk' => trim($this->input->post('message_zh_hk', TRUE)),
			'status' => trim($this->input->post('status', TRUE)),
			'updated_by' => $this->session->userdata('username'),
			'updated_date' => time()
    	);
		
		if($DBdata['title_en'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_title_en_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message_en'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_content_en_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['title_zh_cn'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_title_zh_cn_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message_zh_cn'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_content_zh_cn_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['title_zh_hk'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_title_zh_hk_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message_zh_hk'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('announcement_content_zh_hk_must_fill_in_message')));
    		return false;
		}
		
		$this->db->trans_start();
		
		$this->db->where('announcement_id', $announcement_id);
		$this->db->limit(1);
		$this->db->update('sw_announcements', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_ANNOUNCEMENT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('announcement_update_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function delete_announcement($announcement_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$this->db->trans_start();
		
		$this->db->where('announcement_id', $announcement_id);
		$this->db->limit(1);
		$this->db->delete('sw_announcements');
		
		$DBdata['announcement_id'] =  $announcement_id;
		$this->insert_user_log($this->session->userdata('user_id'), LOG_DELETE_ANNOUNCEMENT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('announcement_delete_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function get_service_setting()
    {
        $query = $this->db->query("SELECT * FROM sw_setting LIMIT 1")->row_array();
	    
	    return $query;
    }
	
	function set_service_setting()
	{
		$this->lang->load('account_general', get_language());
		
		$security_key = trim($this->input->post('security_key', TRUE));
		if($security_key != SECURITY_KEY_FOR_SETTING) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('setting_invalid_security_key_message')));
			return false;
		}
	
        #Populate submitted data
	    $DBdata = array(
			'min_convert' => trim($this->input->post('min_convert', TRUE)),
			'min_transfer' => trim($this->input->post('min_transfer', TRUE)),
			'min_topup' => trim($this->input->post('min_topup', TRUE)),
			'min_withdraw' => trim($this->input->post('min_withdraw', TRUE)),
			'max_convert_per_day' => trim($this->input->post('max_convert_per_day', TRUE)),
			'max_transfer_per_day' => trim($this->input->post('max_transfer_per_day', TRUE)),
			'max_transfer_per_day_2' => trim($this->input->post('max_transfer_per_day_2', TRUE)),
			'max_transfer_per_day_3' => trim($this->input->post('max_transfer_per_day_3', TRUE)),
			'max_withdraw_per_day' => trim($this->input->post('max_withdraw_per_day', TRUE)),
			'withdrawal_rate' => trim($this->input->post('withdrawal_rate', TRUE)),
			'modified_by' => $this->session->userdata('username'),
			'modified_date' => time()
    	);
		
		$this->db->trans_start();
		
		$this->db->where('setting_id', 1);
		$this->db->limit(1);
		$this->db->update('sw_setting', $DBdata);
		
		$this->user_model->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_SERVICE_SETTING, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('service_setting_successful_message')));
			return true;
		}
		else {
			return false;
		}
	}
	
	function get_product_details($product_id = NULL)
	{
		$query = $this->db->query("SELECT * FROM sw_products WHERE product_id = ? LIMIT 1", array($product_id))->row_array();
	    
	    return $query;
	}
	
	function add_new_product()
    {
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'product_group_id' => trim($this->input->post('product_group_id', TRUE)),
			'product_category_id' => trim($this->input->post('product_category_id', TRUE)),
			'product_name' => trim($this->input->post('product_name', TRUE)),
			'product_desc' => trim($this->input->post('product_desc', TRUE)),
			'product_price' => trim($this->input->post('product_price', TRUE)),
			'product_qty' => trim($this->input->post('product_qty', TRUE)),
			'product_enable' => trim($this->input->post('product_enable', TRUE)),
			'created_by' => $this->session->userdata('username'),
			'created_date' => time()
    	);
		
		#Data validation
		if($DBdata['product_group_id'] == '' || $DBdata['product_group_id'] <= 0) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_group_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['product_category_id'] == '' || $DBdata['product_category_id'] <= 0) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_category_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['product_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_name_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['product_price'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_price_must_fill_in_message')));
    		return false;	
    	}
		else if($DBdata['product_qty'] == '' || $DBdata['product_qty'] == 0) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_qty_must_fill_in_message')));
    		return false;
    	}
		
		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
		if(isset($_FILES['product_image']['size']) AND $_FILES['product_image']['size'] > 0) 
		{
			if( ! in_array($_FILES['product_image']['type'], $allowed_types)) 
			{
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_image_invalid_message')));
				return false;
			}
			else
			{
				$DBdata['product_image'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 1) . '.jpg';
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_image_must_fill_in_message')));
			return false;
		}
		
		if(isset($_FILES['product_image_2']['size']) AND $_FILES['product_image_2']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_2']['type'], $allowed_types)) 
			{
				$DBdata['product_image_2'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 2) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_3']['size']) AND $_FILES['product_image_3']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_3']['type'], $allowed_types)) 
			{
				$DBdata['product_image_3'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 3) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_4']['size']) AND $_FILES['product_image_4']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_4']['type'], $allowed_types)) 
			{
				$DBdata['product_image_4'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 4) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_5']['size']) AND $_FILES['product_image_5']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_5']['type'], $allowed_types)) 
			{
				$DBdata['product_image_5'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 5) . '.jpg';
			}
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_products', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_ADD_PRODUCT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			if(isset($_FILES['product_image']['size']) AND $_FILES['product_image']['size'] > 0)
			{
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_2']['size']) AND $_FILES['product_image_2']['size'] > 0)
			{
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_2']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_2'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_3']['size']) AND $_FILES['product_image_3']['size'] > 0)
			{
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_3']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_3'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_4']['size']) AND $_FILES['product_image_4']['size'] > 0)
			{
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_4']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_4'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_5']['size']) AND $_FILES['product_image_5']['size'] > 0)
			{
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_5']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_5'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
		
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('product_added_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_product_details($product_id = NULL)
    {
		$this->lang->load('account_general', get_language());
	
		$old_product_image = trim($this->input->post('old_product_image', TRUE));
		
        #Populate submitted data
	    $DBdata = array(
			'product_group_id' => trim($this->input->post('product_group_id', TRUE)),
			'product_category_id' => trim($this->input->post('product_category_id', TRUE)),
			'product_name' => trim($this->input->post('product_name', TRUE)),
			'product_desc' => trim($this->input->post('product_desc', TRUE)),
			'product_price' => trim($this->input->post('product_price', TRUE)),
			'product_qty' => trim($this->input->post('product_qty', TRUE)),
			'product_enable' => trim($this->input->post('product_enable', TRUE)),
			'updated_by' => $this->session->userdata('username'),
			'updated_date' => time()
    	);
		
		#Data validation
		if($DBdata['product_group_id'] == '' || $DBdata['product_group_id'] <= 0) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_group_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['product_category_id'] == '' || $DBdata['product_category_id'] <= 0) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_category_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['product_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_name_must_fill_in_message')));
    		return false;
		}
		else if($DBdata['product_price'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_price_must_fill_in_message')));
    		return false;	
    	}
		else if($DBdata['product_qty'] == '' || $DBdata['product_qty'] == 0) {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_qty_must_fill_in_message')));
    		return false;
    	}
		
		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
		if(isset($_FILES['product_image']['size']) AND $_FILES['product_image']['size'] > 0) 
		{
			if( ! in_array($_FILES['product_image']['type'], $allowed_types)) 
			{
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('product_image_invalid_message')));
				return false;
			}
			else
			{
				$DBdata['product_image'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 1) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_2']['size']) AND $_FILES['product_image_2']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_2']['type'], $allowed_types)) 
			{
				$DBdata['product_image_2'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 2) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_3']['size']) AND $_FILES['product_image_3']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_3']['type'], $allowed_types)) 
			{
				$DBdata['product_image_3'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 3) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_4']['size']) AND $_FILES['product_image_4']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_4']['type'], $allowed_types)) 
			{
				$DBdata['product_image_4'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 4) . '.jpg';
			}
		}
		
		if(isset($_FILES['product_image_5']['size']) AND $_FILES['product_image_5']['size'] > 0) 
		{
			if(in_array($_FILES['product_image_5']['type'], $allowed_types)) 
			{
				$DBdata['product_image_5'] = md5($this->config->item('encryption_key') . time() . rand(100000, 999999) . 5) . '.jpg';
			}
		}
		
		$this->db->trans_start();
		
		$this->db->where('product_id', $product_id);
		$this->db->limit(1);
		$this->db->update('sw_products', $DBdata);
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_PRODUCT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			if(isset($_FILES['product_image']['size']) AND $_FILES['product_image']['size'] > 0)
			{
				if( ! empty($old_product_image) AND file_exists(UPLOAD_PHYSICAL_PATH . $old_product_image))
				{
					unlink(UPLOAD_PHYSICAL_PATH . $old_product_image);
				}
		
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_2']['size']) AND $_FILES['product_image_2']['size'] > 0)
			{
				if( ! empty($old_product_image) AND file_exists(UPLOAD_PHYSICAL_PATH . $old_product_image))
				{
					unlink(UPLOAD_PHYSICAL_PATH . $old_product_image);
				}
		
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_2']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_2'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_3']['size']) AND $_FILES['product_image_3']['size'] > 0)
			{
				if( ! empty($old_product_image) AND file_exists(UPLOAD_PHYSICAL_PATH . $old_product_image))
				{
					unlink(UPLOAD_PHYSICAL_PATH . $old_product_image);
				}
		
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_3']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_3'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_4']['size']) AND $_FILES['product_image_4']['size'] > 0)
			{
				if( ! empty($old_product_image) AND file_exists(UPLOAD_PHYSICAL_PATH . $old_product_image))
				{
					unlink(UPLOAD_PHYSICAL_PATH . $old_product_image);
				}
		
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_4']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_4'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			if(isset($_FILES['product_image_5']['size']) AND $_FILES['product_image_5']['size'] > 0)
			{
				if( ! empty($old_product_image) AND file_exists(UPLOAD_PHYSICAL_PATH . $old_product_image))
				{
					unlink(UPLOAD_PHYSICAL_PATH . $old_product_image);
				}
		
				$this->load->library('image_lib');
				
				$config['source_image'] = $_FILES['product_image_5']['tmp_name'];
				$config['new_image'] = UPLOAD_PHYSICAL_PATH . $DBdata['product_image_5'];
				$config['maintain_ratio'] = TRUE;
				$config['width'] = 600;
				$config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
		
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('product_updated_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function get_member_placement($member_id = NULL)
	{
		$query = $this->db->query("SELECT transaction_type, to_member_id, credit_amount FROM sw_member_placement WHERE to_member_id = ?", array($member_id));
		
		return $query;
	}
	
	function get_product_group_list()
	{
		$query = $this->db->query("SELECT * FROM sw_product_groups ORDER BY product_group_name ASC");
		
		return $query;
	}
	
	function get_paroduct_category_list()
	{
		$query = $this->db->query("SELECT * FROM sw_product_categories ORDER BY product_category_name ASC");
		
		return $query;
	}
	
	function update_game_deposit_status($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'status' => $status
    	);
		
		$query = $this->db->query("SELECT member_transaction_id, from_member_id, to_member_username, credit_amount FROM sw_member_board_game_deposits WHERE member_transaction_id = ? AND status = ? LIMIT 1", array($transaction_id, 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->where('member_transaction_id', $transaction_id);
			$this->db->where('status', 0);
			$this->db->limit(1);
			$this->db->update('sw_member_board_game_deposits', $DBdata);
			
			if($status == 2) {
				$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($row->credit_amount, $row->from_member_id));
			}
			
			$db_data = array(
				'member_transaction_id' => $row->member_transaction_id,
				'from_member_id' => $row->from_member_id,
				'to_member_username' => $row->to_member_username,
				'credit_amount' => $row->credit_amount,
				'status' => $status
			);
			$this->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_MEMBER_GAME_DEPOSIT_STATUS, json_encode($db_data));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('game_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('game_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('game_fail_message')));
			return false;
		}
	}
	
	function update_offline_topup_status($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'status' => $status
    	);
		
		$query = $this->db->query("SELECT member_transaction_id, to_member_id, to_member_username, debit_amount, transaction_amount, currency_rate FROM sw_member_topup WHERE member_transaction_id = ? AND status = ? AND payment_method = ? LIMIT 1", array($transaction_id, 0, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->where('member_transaction_id', $transaction_id);
			$this->db->where('status', 0);
			$this->db->limit(1);
			$this->db->update('sw_member_topup', $DBdata);
			
			if($status == 1) {
				$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 + ?) WHERE member_id = ? LIMIT 1", array($row->debit_amount, $row->to_member_id));
			}
			
			$db_data = array(
				'member_transaction_id' => $row->member_transaction_id,
				'to_member_id' => $row->to_member_id,
				'to_member_username' => $row->to_member_username,
				'debit_amount' => $row->debit_amount,
				'currency_rate' => $row->currency_rate,
				'transaction_amount' => $row->transaction_amount,
				'status' => $status
			);
			$this->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_MEMBER_OFFLINE_TOPUP_STATUS, json_encode($db_data));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('topup_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_fail_message')));
			return false;
		}
	}
	
	function update_usdt_topup_status($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'status' => $status
    	);
		
		$query = $this->db->query("SELECT member_transaction_id, to_member_id, to_member_username, debit_amount, transaction_amount, currency_rate FROM sw_member_topup WHERE member_transaction_id = ? AND status = ? AND payment_method = ? LIMIT 1", array($transaction_id, 0, 2));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->where('member_transaction_id', $transaction_id);
			$this->db->where('status', 0);
			$this->db->limit(1);
			$this->db->update('sw_member_topup', $DBdata);
			
			if($status == 1) {
				$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 + ?) WHERE member_id = ? LIMIT 1", array($row->debit_amount, $row->to_member_id));
			}
			
			$db_data = array(
				'member_transaction_id' => $row->member_transaction_id,
				'to_member_id' => $row->to_member_id,
				'to_member_username' => $row->to_member_username,
				'debit_amount' => $row->debit_amount,
				'currency_rate' => $row->currency_rate,
				'transaction_amount' => $row->transaction_amount,
				'status' => $status
			);
			$this->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_MEMBER_COIN_TOPUP_STATUS, json_encode($db_data));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('topup_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_fail_message')));
			return false;
		}
	}
	
	function update_claim_status($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'status' => $status
    	);
		
		$query = $this->db->query("SELECT member_transaction_id, from_member_id, from_member_username, claim_amount FROM sw_member_claim_insurances WHERE member_transaction_id = ? AND status = ? LIMIT 1", array($transaction_id, 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->where('member_transaction_id', $transaction_id);
			$this->db->where('status', 0);
			$this->db->limit(1);
			$this->db->update('sw_member_claim_insurances', $DBdata);
			
			if($status == 1) {
				
			}
			
			$db_data = array(
				'member_transaction_id' => $row->member_transaction_id,
				'from_member_id' => $row->from_member_id,
				'from_member_username' => $row->from_member_username,
				'claim_amount' => $row->claim_amount,
				'status' => $status
			);
			$this->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_MEMBER_CLAIM_STATUS, json_encode($db_data));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('insurance_claim_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('insurance_claim_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('insurance_claim_fail_message')));
			return false;
		}
	}
	
	function update_missbet_status($transaction_id = NULL, $status = NULL)
	{
		$this->lang->load('account_general', get_language());
		
        #Populate submitted data
	    $DBdata = array(
			'status' => $status
    	);
		
		$query = $this->db->query("SELECT member_transaction_id FROM sw_member_miss_bets WHERE member_transaction_id = ? AND status = ? LIMIT 1", array($transaction_id, 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$this->db->trans_start();
			
			$this->db->where('member_transaction_id', $transaction_id);
			$this->db->where('status', 0);
			$this->db->limit(1);
			$this->db->update('sw_member_miss_bets', $DBdata);
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('insurance_claim_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('insurance_claim_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('insurance_claim_fail_message')));
			return false;
		}
	}
	
	function get_curency_rates()
	{
		$data = array();
		$query = $this->db->query("SELECT * FROM sw_currencies");
		if($query->num_rows() > 0) {
			foreach($query->result() as $row) {
				$data[$row->currency_id]['in'] = $row->t_currency_rate;
				$data[$row->currency_id]['out'] = $row->w_currency_rate;
			}
		}	
		
		return $data;
	}
	
	// function member_platform_topup()
    // {
		// $this->lang->load('account_general', get_language());
	
		// $platform_id = trim($this->input->post('platform_id', TRUE));
		// $transaction_type = trim($this->input->post('transaction_type', TRUE));
		// $to_member_username = trim($this->input->post('to_member_username', TRUE));
		// $transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		// $remark = trim($this->input->post('remark', TRUE));
		// $security_key = trim($this->input->post('security_key', TRUE));
	
		// #Data validation
		// if($transaction_amount == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_amount_must_fill_in_message')));
    		// return false;
    	// } 
		// else if ( ! preg_match("/^([0-9.]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_amount_message')));
			// return false;
    	// }
		// else if($to_member_username == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_to_member_username_must_fill_in_message')));
    		// return false;
		// }
		// else if($security_key != SECURITY_KEY_TOPUP) {
			// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_security_key_message')));
			// return false;
		// }
		
		// #Check for to member username availability
		// $member_id = 0;
		// $query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($to_member_username, 1));
		// if($query->num_rows() > 0) {
			// $row = $query->row();
			// $member_id = $row->member_id;
		// }
		// else {
			// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_to_member_username_message')));
    		// return false;
		// }
		
		// #Check for available balance
		// if($platform_id == 1 || $platform_id == 2) {
			// $this->db->trans_start();
			
			// if($transaction_type == 1) {
				// $this->db->query("UPDATE sw_member_game_withdrawals SET deposit_amount = (deposit_amount + ?) WHERE from_member_id = ? AND processing_status = ? ORDER BY member_transaction_id DESC LIMIT 1", array($transaction_amount, $member_id, 0));
			// }
			
			// $DBdata = array(
				// 'platform_id' => $platform_id,
				// 'transaction_type' => $transaction_type,
				// 'to_member_id' => $member_id,
				// 'to_member_username' => $to_member_username,
				// 'deposit_date' => time(),
				// 'deposit_amount' => $transaction_amount,
				// 'remark' => $remark,
				// 'created_by' => $this->session->userdata('username'),
				// 'created_date' => time()
			// );
			
			// $this->db->insert('sw_member_game_topup', $DBdata);
			
			// $this->db->trans_complete();
			
			// $rs = $this->db->trans_status();
			
			// if($rs) {
				// //CALL API - topup credit asiagaming1688 or luckyb3t
				// $response = $this->api_topup_credit($platform_id, $to_member_username, $transaction_amount, $remark);
				// $result_array = json_decode($response, TRUE);
				// if(isset($result_array['status']) && $result_array['status'] == 0) {
					// $this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('topup_platform_topup_successful_message')));
					// return true;
				// }
				// else {
					// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $result_array['msg']));
					// return false;
				// }
			// }
			// else {
				// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_platform_topup_failed_message')));
				// return false;
			// }			
		// }
		// else {
			// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_platform_topup_failed_message')));
    		// return false;
		// }
    // }
	
	function member_platform_topup()
    {
		$this->lang->load('account_general', get_language());
	
		$platform_id = trim($this->input->post('platform_id', TRUE));
		$transaction_type = trim($this->input->post('transaction_type', TRUE));
		$to_member_username = trim($this->input->post('to_member_username', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$remark = trim($this->input->post('remark', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
		#Data validation
		if($platform_id != 1 && $platform_id != 2 && $platform_id != 3) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_platform_topup_failed_message')));
    		return false;
		}
		else if($transaction_amount == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_amount_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9.]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_amount_message')));
			return false;
    	}
		else if($security_key != SECURITY_KEY_TOPUP) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('topup_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$arr = explode(',', $to_member_username);
		for($i=0;$i<sizeof($arr);$i++) {
			if($arr[$i] != '') {
				#Check for to member username availability
				$query = $this->db->query("SELECT member_id, username FROM sw_members WHERE username = ? AND active = ? LIMIT 1", array($arr[$i], 1));
				if($query->num_rows() > 0) {
					$row = $query->row();
					
					if($transaction_type == 1) {
						$this->db->query("UPDATE sw_member_game_withdrawals SET deposit_amount = (deposit_amount + ?) WHERE from_member_id = ? AND processing_status = ? ORDER BY member_transaction_id DESC LIMIT 1", array($transaction_amount, $row->member_id, 0));
					}
					
					$DBdata = array(
						'platform_id' => $platform_id,
						'transaction_type' => $transaction_type,
						'to_member_id' => $row->member_id,
						'to_member_username' => $row->username,
						'deposit_date' => time(),
						'deposit_amount' => $transaction_amount,
						'remark' => $remark,
						'created_by' => $this->session->userdata('username'),
						'created_date' => time()
					);
					
					$this->db->insert('sw_member_game_topup', $DBdata);
					
					if($platform_id == 1 || $platform_id == 2) {
						//CALL API - topup credit asiagaming1688 or luckyb3t
						$this->api_topup_credit($platform_id, $row->username, $transaction_amount, $remark);
					}
					else if($platform_id == 3) {
						$query_ext = $this->db->query("SELECT member_transaction_id, deposit_amount FROM sw_member_game_withdrawals WHERE from_member_username = ? AND withdrawal_status = ? LIMIT 1", array($arr[$i], 0));
						if($query_ext->num_rows() > 0) {
							$row_ext = $query_ext->row();
							
							$this->db->query("UPDATE sw_member_game_withdrawals SET lend = (lend + ?) WHERE member_transaction_id = ? LIMIT 1", array($row_ext->deposit_amount, $row_ext->member_transaction_id));
						}	
					}
				}
			}
		}
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('topup_platform_topup_successful_message')));
			return true;
		}
		else {
			return false;
		}
    }
	
	function update_freeze_status($member_id = NULL, $status = NULL)
	{
		#Check for member availability
		$query = $this->db->query("SELECT member_id, casino_plyid_1, casino_plyid_2 FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
		
			$this->db->trans_start();
			
			// $otherdb1 = $this->load->database('otherdb1', TRUE);
			$otherdb2 = $this->load->database('otherdb2', TRUE);
	
			$DBdata = array(
				'allowed_game' => (($status == 1) ? 1 : 0),
				'modified_by' => $this->session->userdata('username'),
				'modified_date' => time()
			);
			
			$this->db->query("UPDATE sw_members SET allowed_game = ?, modified_by = ?, modified_date = ? WHERE member_id = ? LIMIT 1", array($DBdata['allowed_game'], $DBdata['modified_by'], $DBdata['modified_date'], $row->member_id));
			
			// $otherdb1->query("UPDATE bctp_players SET active = ? WHERE player_id = ? LIMIT 1", array($DBdata['allowed_game'], $row->casino_plyid_1));
			$otherdb2->query("UPDATE bctp_players SET active = ? WHERE player_id = ? LIMIT 1", array($DBdata['allowed_game'], $row->casino_plyid_2));
			
			$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_MEMBER, json_encode($DBdata));
			
			$this->db->trans_complete();
			
			$rs = $this->db->trans_status();
			
			if($rs) {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('withdrawal_successful_message')));
				return true;
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('withdrawal_fail_message')));
				return false;
			}
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('withdrawal_fail_message')));
			return false;
		}
	}
	
	public function update_wallet($member_id = NULL)
	{
		$username = '';
		$casino_plyid_2 = 0;
		$last_withdrawal_date = 0;
    	$v_unit6 = 0;
		$v_unit7 = 0;
		$v_unit8 = 0;
		
		$query = $this->db->query("SELECT username, casino_plyid_2 FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$username = $row->username;
			$casino_plyid_2 = $row->casino_plyid_2;
		}
			
		// //CALL API - get balance asiagaming1688
		// $response = $this->api_get_balance(1, $username);
		// $result_array = json_decode($response, TRUE);
		// if(isset($result_array['status']) && $result_array['status'] == 0) {
			// $v_unit6 = $result_array['balance'];
		// }
		
		//CALL API - get balance luckyb3t
		$response_2 = $this->api_get_balance(2, $username);
		$result_array_2 = json_decode($response_2, TRUE);
		if(isset($result_array_2['status']) && $result_array_2['status'] == 0) {
			$v_unit7 = $result_array_2['balance'];
		}
		
		//get turnover luckyb3t
		$otherdb = $this->load->database('otherdb2', TRUE);
		
		$query = $otherdb->query("SELECT updated_date FROM bctp_withdrawals WHERE player_id = ? AND status = ? ORDER BY withdrawal_id DESC LIMIT 1", array($casino_plyid_2, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$last_withdrawal_date = $row->updated_date;
		}
		
		//Calculate rolling
		$query = $otherdb->query("SELECT SUM(bet_amount) AS total FROM bctp_transaction_report WHERE player_id = ? AND payout_time > ? AND status = ? AND win_loss != ? AND game_code = ?", array($casino_plyid_2, $last_withdrawal_date, 1, 0, 'Baccarat'));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$v_unit8 = (isset($row->total) ? $row->total : 0);
		}
		
		$this->db->trans_start();
	
		$this->db->query("UPDATE sw_member_wallets SET v_unit6 = ?, v_unit7 = ?, v_unit8 = ? WHERE member_id = ? LIMIT 1", array($v_unit6, $v_unit7, $v_unit8, $member_id));
		
		$this->db->trans_complete();
		
		$json = array('v_unit6' => number_format($v_unit6, 2, '.', ','), 'v_unit7' => number_format($v_unit7, 2, '.', ','), 'v_unit8' => number_format($v_unit8, 2, '.', ','));
			
		return $json;
    }
	
	function api_create_account($platform = NULL, $username = NULL, $password = NULL, $package_type = NULL)
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		switch($package_type) {
			case 1: $player_type = 3; break;
			case 2: $player_type = 4; break;
			default: $player_type = 2; break;
		}
		
		$arr = array(
			"username" => $username,
			"password" => $password,
			"player_type" => $player_type,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'MemberRegisterDV',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"player" => array(
				"username" => $arr['username'],
				"password" => $arr['password'],
				"player_type" => $arr['player_type'],
			)
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_topup_credit($platform = NULL, $username = NULL, $amount = NULL, $remark = NULL)
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		$arr = array(
			"username" => $username,
			"amount" => $amount,
			"remark" => $remark,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'CreditBalance',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"amount" => $arr['amount'],
			"remark" => $arr['remark'],
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_topup_debit($platform = NULL, $username = NULL, $amount = NULL, $remark = NULL)
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		$arr = array(
			"username" => $username,
			"amount" => $amount,
			"remark" => $remark,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'DebitBalance',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"amount" => $arr['amount'],
			"remark" => $arr['remark'],
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_get_balance($platform = NULL, $username = NULL) 
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		$arr = array(
			"username" => $username,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'GetBalanceDV',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_update_player_type($platform = NULL, $username = NULL, $package_type = NULL) 
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		switch($package_type) {
			case 1: $player_type = 3; break;
			case 2: $player_type = 4; break;
			default: $player_type = 2; break;
		}
		
		$arr = array(
			"username" => $username,
			"player_type" => $player_type,
			"turnover_limit" => 5,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'UpdatePlayerType',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"player_type" => $arr['player_type'],
			"turnover_limit" => $arr['turnover_limit'],
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_game_withdrawal($platform = NULL, $username = NULL) 
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		$arr = array(
			"username" => $username,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'GameWithdrawal',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
		);
		
		$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;
	}
}