<?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));
		
        #Populate submitted data
	    $DBdata = array(
			'username' => 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)),
			'package_type' => trim($this->input->post('package_type', TRUE)),
			'origin_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' => 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)),
			'platform_type' => 1,
			'is_claim_only' => 0,
			'registered_by' => $this->session->userdata('username'),
			'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-zA-Z0-9_]{3,32}$/', $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("/^(?=.*\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;
		} 
		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 member_id, introducer_parent_ref FROM sw_members WHERE 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 . ',';
			}
			
			// #Get platform type
			// $s_arr = explode(',', $DBdata['introducer_parent_ref']);
			// if(in_array(13, $s_arr)) {
				// $DBdata['platform_type'] = 2;
			// }
			// else if(in_array(14, $s_arr)) {
				// $DBdata['is_claim_only'] = 1;
			// }
		}
		else {
			$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();
		
		$this->db->insert('sw_members', $DBdata);
		$db_data['member_id'] = $this->db->insert_id();
		
		$this->db->insert('sw_member_wallets', $db_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) {
			if($DBdata['member_type'] == 2) {
				//Get all package details
				$packages = array();
				$package_query = $this->db->query("SELECT * FROM sw_packages");
				if($package_query->num_rows() > 0) {
					foreach($package_query->result() as $package_row) {
						$packages[$package_row->package_id] = array(
																	'package_price' => $package_row->package_price,
																	'intro_commission' => $package_row->intro_commission
																);									
					}
				}
				
				//Prepare member list
				$member_lists = array();	
				$member_query = $this->db->query("SELECT a.member_id, a.username, a.member_type, a.package_type, a.active, b.v_unit2 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id)");
				if($member_query->num_rows() > 0) {
					foreach($member_query->result() as $member_row) {
						$member_lists[$member_row->member_id] = array(
																	'member_id' => $member_row->member_id,
																	'member_type' => $member_row->member_type,
																	'username' => $member_row->username,
																	'v_unit2' => $member_row->v_unit2,
																	'rate' => 0
																);	
						
						if($member_row->package_type > 0 && $member_row->active == 1) {
							$member_lists[$member_row->member_id]['rate'] = $packages[$member_row->package_type]['intro_commission'];
						}
					}
				}
				
				//Intro Bonus
				$server_time = time();
				$income_date = date('Y-m-d', $server_time);
				$current_rate = 0;
				$arr = explode(',', $DBdata['introducer_parent_ref']);
				for($i=(sizeof($arr) - 1);$i>0;$i--) {
					if( ! empty($arr[$i])) {
						if($current_rate == 10) {
							break;
						}
						else {
							$rate = $member_lists[$arr[$i]]['rate'];
							
							if($rate > 0) {
								if($current_rate < $rate) {
									$upgrade_rate = $rate;
									
									if($current_rate > 0) {
										$rate = ($rate - $current_rate);
									}
									
									$current_rate = $upgrade_rate;
								}
								else if($current_rate >= $rate) {
									$rate = 0;
								}
							}
						
							$bonus = (($package_price * $rate) / 100);
						
							if($bonus > 0) {
								$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($bonus, $member_lists[$arr[$i]]['member_id']));
						
								//Transaction log
								//transaction_type 1 = Intro Bonus, 2 = Algebra Bonus, 3 = Differential Bonus, 4 = Same Bonus, 5 = Pool Bonus
								$trans_data = array(
									'transaction_type' => 1,
									'from_member_id' => $db_data['member_id'],
									'from_member_username' => $DBdata['username'],
									'to_member_id' => $member_lists[$arr[$i]]['member_id'],
									'to_member_username' => $member_lists[$arr[$i]]['username'],
									'from_v_unit2' => $member_lists[$arr[$i]]['v_unit2'],
									'v_unit2_amount' => $bonus,
									'to_v_unit2' => ($member_lists[$arr[$i]]['v_unit2'] + $bonus),
									'status' => 1,
									'transaction_date' => $server_time
								);	
								$this->db->insert('sw_member_transactions', $trans_data);
								
								//Income summary
								$income_query = $this->db->query("SELECT member_id FROM sw_member_income_summary WHERE member_id = ? AND income_date = ? LIMIT 1", array($member_lists[$arr[$i]]['member_id'], $income_date));
								if($income_query->num_rows() == 0) {
									$income_data = array(
										'income_date' => $income_date,
										'intro_bonus' => $bonus,
										'v_unit2' => $bonus,
										'member_id' => $member_lists[$arr[$i]]['member_id']
									);	
									$this->db->insert('sw_member_income_summary', $income_data);
								}
								else {
									$this->db->query("UPDATE sw_member_income_summary SET intro_bonus = (intro_bonus + ?), v_unit2 = (v_unit2 + ?) WHERE income_date = ? AND member_id = ? LIMIT 1", array($bonus, $bonus, $income_date, $member_lists[$arr[$i]]['member_id']));
								}
							}
						}	
					}
				}
			}
			
			$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 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)),
			'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_star($member_id = NULL)
    {
		$this->lang->load('account_general', get_language());
		
		$stars = trim($this->input->post('stars', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'stars' => (($stars > 0 && $stars < 11) ? $stars : 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_STAR_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_star_upgrade_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(),
			// 'reinvest_expiry_date' => strtotime('+' . TENURE_CONTRACT . ' days', time()),
			'reinvest_active' => 1,
			'member_id' => $member_id,
    	);
		
		$casino_username = '';
		$query = $this->db->query("SELECT casino_username FROM sw_members WHERE member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$casino_username = $row->casino_username;
		}	
		
		if($casino_username == '') {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_binding_casino_account_message')));
    		return false;
		}
			
		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;
		$query = $this->db->query("SELECT package_price FROM sw_packages WHERE package_id = ? LIMIT 1", array($DBdata['reinvest_package_type']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$package_price = $row->package_price;
		}
		else {
			$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 member details
		$member_username = '';
		$introducer_parent_ref = '';
		$origin_package_type = 0;
		$origin_package_price = 0;
		$query = $this->db->query("SELECT a.package_type, a.username, a.introducer_parent_ref, b.package_price FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.member_id = ? LIMIT 1", array($member_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$member_username = $row->username;
			$introducer_parent_ref = $row->introducer_parent_ref;
			$origin_package_type = $row->package_type;
			$origin_package_price = $row->package_price;
		}
		
		$current_package_price = ($package_price - $origin_package_price);
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_reinvest', $DBdata);
		
		if($origin_package_type == 0) {
			$this->db->query("UPDATE sw_members SET package_type = ?, origin_package_type = ? WHERE member_id = ? LIMIT 1", array($DBdata['reinvest_package_type'], $DBdata['reinvest_package_type'], $member_id));
		}
		else {
			$this->db->query("UPDATE sw_members SET package_type = ? WHERE member_id = ? LIMIT 1", array($DBdata['reinvest_package_type'], $member_id));
		}
		
		$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 - topup credit
			if($casino_username != '') {
				$response = $this->api_topup_credit($casino_username, $current_package_price);
				$result_array = json_decode($response, TRUE);
				if(isset($result_array['status']) && $result_array['status'] == 0) {
					$SDBdata = array(
						'amount' => $current_package_price,
						'member_id' => $member_id,
						'transaction_date' => time(),
					);
					$this->db->insert('sw_member_sales', $SDBdata);
					
					$this->db->query("UPDATE sw_members SET allowed_withdraw = ?, active = ?, total_invest = (total_invest + ?) WHERE member_id = ? LIMIT 1", array(1, 1, $current_package_price, $member_id));
				}
			}
			
			//Get all package details
			$packages = array();
			$package_query = $this->db->query("SELECT * FROM sw_packages");
			if($package_query->num_rows() > 0) {
				foreach($package_query->result() as $package_row) {
					$packages[$package_row->package_id] = array(
																'package_price' => $package_row->package_price,
																'intro_commission' => $package_row->intro_commission
															);									
				}
			}
			
			$member_lists = array();	
			$member_query = $this->db->query("SELECT a.member_id, a.username, a.member_type, a.package_type, a.active, b.v_unit2 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id)");
			if($member_query->num_rows() > 0) {
				foreach($member_query->result() as $member_row) {
					$member_lists[$member_row->member_id] = array(
																'member_id' => $member_row->member_id,
																'member_type' => $member_row->member_type,
																'username' => $member_row->username,
																'v_unit2' => $member_row->v_unit2,
																'rate' => 0
															);	
					
					if($member_row->package_type > 0 && $member_row->active == 1) {
						$member_lists[$member_row->member_id]['rate'] = $packages[$member_row->package_type]['intro_commission'];
					}
				}
			}
			
			//Intro Bonus
			$server_time = time();
			$income_date = date('Y-m-d', $server_time);
			$current_rate = 0;
			$arr = explode(',', $introducer_parent_ref);
			for($i=(sizeof($arr) - 1);$i>0;$i--) {
				if( ! empty($arr[$i])) {
					if($current_rate == 10) {
						break;
					}
					else {
						$rate = $member_lists[$arr[$i]]['rate'];
						
						if($rate > 0) {
							if($current_rate < $rate) {
								$upgrade_rate = $rate;
								
								if($current_rate > 0) {
									$rate = ($rate - $current_rate);
								}
								
								$current_rate = $upgrade_rate;
							}
							else if($current_rate >= $rate) {
								$rate = 0;
							}
						}
					
						$bonus = (($current_package_price * $rate) / 100);
					
						if($bonus > 0) {
							$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($bonus, $member_lists[$arr[$i]]['member_id']));
					
							//Transaction log
							//transaction_type 1 = Intro Bonus, 2 = Algebra Bonus, 3 = Differential Bonus, 4 = Same Bonus, 5 = Pool Bonus
							$trans_data = array(
								'transaction_type' => 1,
								'from_member_id' => $member_id,
								'from_member_username' => $member_username,
								'to_member_id' => $member_lists[$arr[$i]]['member_id'],
								'to_member_username' => $member_lists[$arr[$i]]['username'],
								'from_v_unit2' => $member_lists[$arr[$i]]['v_unit2'],
								'v_unit2_amount' => $bonus,
								'to_v_unit2' => ($member_lists[$arr[$i]]['v_unit2'] + $bonus),
								'status' => 1,
								'transaction_date' => $server_time
							);	
							$this->db->insert('sw_member_transactions', $trans_data);
							
							//Income summary
							$income_query = $this->db->query("SELECT member_id FROM sw_member_income_summary WHERE member_id = ? AND income_date = ? LIMIT 1", array($member_lists[$arr[$i]]['member_id'], $income_date));
							if($income_query->num_rows() == 0) {
								$income_data = array(
									'income_date' => $income_date,
									'intro_bonus' => $bonus,
									'v_unit2' => $bonus,
									'member_id' => $member_lists[$arr[$i]]['member_id']
								);	
								$this->db->insert('sw_member_income_summary', $income_data);
							}
							else {
								$this->db->query("UPDATE sw_member_income_summary SET intro_bonus = (intro_bonus + ?), v_unit2 = (v_unit2 + ?) WHERE income_date = ? AND member_id = ? LIMIT 1", array($bonus, $bonus, $income_date, $member_lists[$arr[$i]]['member_id']));
							}
						}
					}	
				}
			}
			
			$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_]{3,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);
		
		$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, a.active, LOWER(a.introducer) AS introducer, ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) AS max_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->max_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, 'active' => $row->active, '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, a.active, ROUND((LENGTH(a.introducer_parent_ref) - LENGTH(REPLACE(a.introducer_parent_ref, ',', '')) ) / LENGTH(',')) AS max_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, 'active' => $sub_row->active, '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++;
		}
		
		//Get all package details
		$packages = array();
		$package_query = $this->db->query("SELECT * FROM sw_packages");
		if($package_query->num_rows() > 0) {
			foreach($package_query->result() as $package_row) {
				$packages[$package_row->package_id] = array('package_price' => $package_row->package_price);									
			}
		}
		
		//Prepare reinvest
		$reinvest_sales_lists = array();	
		$reinvest_query = $this->db->query("SELECT reinvest_package_type, member_id FROM sw_member_reinvest");
		if($reinvest_query->num_rows() > 0) {
			foreach($reinvest_query->result() as $reinvest_row) {
				if(isset($reinvest_sales_lists[$reinvest_row->member_id]['package_type'])) {
					if($reinvest_row->reinvest_package_type > $reinvest_sales_lists[$reinvest_row->member_id]['package_type']) {
						$reinvest_sales_lists[$reinvest_row->member_id]['package_type'] = $reinvest_row->reinvest_package_type;
					}
				}
				else {
					$reinvest_sales_lists[$reinvest_row->member_id]['package_type'] = $reinvest_row->reinvest_package_type;
				}					
			}
		}
				
		//Prepare member list
		$member_lists = array();	
		$member_query = $this->db->query("SELECT member_id, package_type FROM sw_members");
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				$member_lists[$member_row->member_id] = array(
																'package_type' => $member_row->package_type,
																'total_sales' => 0
															);
				
				if(isset($reinvest_sales_lists[$member_row->member_id]['package_type'])) {	
					if($reinvest_sales_lists[$member_row->member_id]['package_type'] > $member_lists[$member_row->member_id]['package_type']) {
						$member_lists[$member_row->member_id]['package_type'] = $reinvest_sales_lists[$member_row->member_id]['package_type'];
					}
				}
			}
		}
		
		//Prepare direct sales
		$member_query = $this->db->query("SELECT member_id, introducer_parent_ref FROM sw_members WHERE member_type = ? AND active = ? AND package_type > ?", array(2, 1, 0));
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				if($member_row->introducer_parent_ref != '') {
					$arr = explode(',', $member_row->introducer_parent_ref);
					
					for($i=0; $i<sizeof($arr); $i++) {
						if($arr[$i] != '' AND $arr[$i] > 0) {
							$member_lists[$arr[$i]]['total_sales'] = ($member_lists[$arr[$i]]['total_sales'] + $packages[$member_lists[$member_row->member_id]['package_type']]['package_price']);
						}
					}
				}
			}
		}
		
		$i = 0;
		$json = '';
		foreach($data2 as $k => $v) {
			if($i == 0) {
				$new_parent_id = 0;
				
				if($v['introducer'] != '') {
					$up_arrow = "<p><a style=\"color: #fff;\" 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 = (($v['active'] == 0) ? 'securities_offline' : 'securities_online'); 
			$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']));
			$total_sales = 'S: ' . $member_lists[$v['member_id']]['total_sales'];
			
			if($v['member_id'] > 0) {
				$json .= "{id: " . $v['new_id'] . ", name: '" . $up_arrow . "<div class=\"node-inner " . $s_bg . "\"><a style=\"color: #fff;\" href=\"" . base_url() . "member/structure/" . $v['username'] . "/\">" . $v['username'] . "<br />" . $ranking . "<br />" . $package_type . "<br />" . $total_sales . "</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 availability
		$platform_type = 1;
		$query = $this->db->query("SELECT member_id, platform_type FROM sw_members WHERE username = ? LIMIT 1", array($from_member_username));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['from_member_id'] = $row->member_id;
			$platform_type = $row->platform_type;
		}
		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 availability
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? LIMIT 1", array($to_member_username));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			if($platform_type == 2) {
				$sub_query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND introducer_parent_ref LIKE '%," . $row->member_id . ",%' LIMIT 1", array($DBdata['from_member_id']));
				if($sub_query->num_rows() > 0) {
					$DBdata['to_member_id'] = $row->member_id;
				}
				else {
					$sub_query2 = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND introducer_parent_ref LIKE '%," . $DBdata['from_member_id'] . ",%' LIMIT 1", array($row->member_id));
					if($sub_query2->num_rows() > 0) {
						$DBdata['to_member_id'] = $row->member_id;
					} 
					else {
						$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('transfer_invalid_to_member_username_message')));
						return false;
					}
				}
			}
			else {
				$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 == 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 == 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));
		$currency_rate = trim($this->input->post('currency_rate', TRUE));
		$remark = trim($this->input->post('remark', TRUE));
		$remark_2 = trim($this->input->post('remark_2', 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 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],
						'currency_rate' => $currency_rate,
						'remark' => (($remark == 'Others') ? trim($this->input->post('remark_others', TRUE)) : $remark),
						'remark_2' => $remark_2,
						'status' => 1,
						'transaction_date' => time()
					);
					
					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 == 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));
		$remark_2 = trim($this->input->post('remark_2', 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,
			'remark_2' => $remark_2,
			'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 = ? LIMIT 1", array($to_member_username));
		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 == 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 == 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 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 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,
						'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 = ?, 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['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,
						'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 = ?, 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['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));
				}
			}
			
			$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_unit = (v_unit + ?) 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 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 member_add_pool_bonus()
    {
		$this->lang->load('account_general', get_language());
	
		$to_member_username = trim($this->input->post('to_member_username', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_key = trim($this->input->post('security_key', TRUE));
		
		#Data validation
		if($to_member_username == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('report_to_member_username_must_fill_in_message')));
    		return false;
		}
		else if($transaction_amount == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('report_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('report_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('report_invalid_security_key_message')));
			return false;
		}
		
		$server_time = time();
		$income_date = date('Y-m-d', $server_time);
		
		$member_id = 0;
		$query = $this->db->query("SELECT a.member_id, a.username, b.v_unit2 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.username = ? LIMIT 1", array($to_member_username));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$member_id = $row->member_id;	
			
			//Transaction log
			//transaction_type 1 = Intro Bonus, 2 = Algebra Bonus, 3 = Differential Bonus, 4 = Same Bonus, 5 = Pool Bonus
			$trans_data = array(
				'transaction_type' => 5,
				'from_member_id' => $row->member_id,
				'from_member_username' => $row->username,
				'to_member_id' => $row->member_id,
				'to_member_username' => $row->username,
				'from_v_unit2' => $row->v_unit2,
				'v_unit2_amount' => $transaction_amount,
				'to_v_unit2' => ($row->v_unit2 + $transaction_amount),
				'status' => 1,
				'transaction_date' => $server_time
			);	
					
		}
		else {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('report_invalid_to_member_username_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		if($member_id > 0) {
			$this->db->insert('sw_member_transactions', $trans_data);
			
			$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($transaction_amount, $member_id));
				
			$income_query = $this->db->query("SELECT income_summary_id FROM sw_member_income_summary WHERE member_id = ? AND income_date = ? LIMIT 1", array($member_id, $income_date));
			if($income_query->num_rows() > 0) {
				$this->db->query("UPDATE sw_member_income_summary SET pool_bonus = (pool_bonus + ?), v_unit2 = (v_unit2 + ?) WHERE income_date = ? AND member_id = ? LIMIT 1", array($transaction_amount, $transaction_amount, $income_date, $member_id));
			}
			else {
				$income_data = array(
					'income_date' => $income_date,
					'pool_bonus' => $transaction_amount,
					'v_unit2' => $transaction_amount,
					'member_id' => $member_id
				);	
				$this->db->insert('sw_member_income_summary', $income_data);
			}	
			
			$this->insert_user_log($this->session->userdata('user_id'), LOG_ADD_POOL_BONUS, json_encode($trans_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('report_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());
		
		$is_reply = trim($this->input->post('is_reply', TRUE));
		$message_id = trim($this->input->post('message_id', TRUE));
	
		if($is_reply == 2) {
			#Populate submitted data
			$DBdata = array(
				'subject' => trim($this->input->post('message_subject', TRUE)),
				'message' => trim($this->input->post('message_message', TRUE)),
				'updated_by' => $this->session->userdata('username'),
				'updated_date' => time()
			);
		}
		else {
			#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();
		
		if($is_reply == 2) {
			$this->db->where('message_id', $message_id);
			$this->db->limit(1);
			$this->db->update('sw_member_messages', $DBdata);
			
			$this->insert_user_log($this->session->userdata('user_id'), LOG_EDIT_MESSAGE, json_encode($DBdata));
		}
		else {
			$this->db->query('UPDATE sw_member_messages SET admin_reply = ? WHERE message_id = ? LIMIT 1', array($is_reply, $message_id));
			
			$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 get_member_message_details_by_edit($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['subject']) AND isset($query['message'])) {
			$query['message_subject'] = $query['subject'];
			$query['message_message'] = $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)),
			'min_withdraw_2' => trim($this->input->post('min_withdraw_2', TRUE)),
			'max_withdraw_per_day' => trim($this->input->post('max_withdraw_per_day', TRUE)),
			'usdt_withdrawal_fee' => trim($this->input->post('usdt_withdrawal_fee', TRUE)),
			'topup_rate' => trim($this->input->post('topup_rate', TRUE)),
			'withdrawal_rate' => trim($this->input->post('withdrawal_rate', TRUE)),
			'currency_in_rate' => trim($this->input->post('currency_in_rate', TRUE)),
			'currency_out_rate' => trim($this->input->post('currency_out_rate', TRUE)),
			'omni_usdt_address' => trim($this->input->post('omni_usdt_address', TRUE)),
			'erc20_usdt_address' => trim($this->input->post('erc20_usdt_address', TRUE)),
			'bank_name_1' => trim($this->input->post('bank_name_1', TRUE)),
			'bank_account_holder_1' => trim($this->input->post('bank_account_holder_1', TRUE)),
			'bank_account_no_1' => trim($this->input->post('bank_account_no_1', TRUE)),
			'bank_name_2' => trim($this->input->post('bank_name_2', TRUE)),
			'bank_account_holder_2' => trim($this->input->post('bank_account_holder_2', TRUE)),
			'bank_account_no_2' => trim($this->input->post('bank_account_no_2', TRUE)),
			'group_sales' => trim($this->input->post('group_sales', TRUE)),
			'group_downlines' => trim($this->input->post('group_downlines', 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 set_currency_rate()
	{
		$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;
		}
		
		$this->db->trans_start();
		
		for($i=0;$i<sizeof($_POST['cid']);$i++) {
			$DBdata = array(
				't_currency_rate' => trim($_POST['drate'][$i]),
				'w_currency_rate' => trim($_POST['wrate'][$i]),
				'modified_by' => $this->session->userdata('username'),
				'modified_date' => time()
			);
			
			$this->db->where('currency_id', trim($_POST['cid'][$i]));
			$this->db->limit(1);
			$this->db->update('sw_currencies', $DBdata);
		}
        
		$this->user_model->insert_user_log($this->session->userdata('user_id'), LOG_UPDATE_CURRENCY_RATE, 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_currency_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_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) {
				//CALL API - topup credit
				$query_2 = $this->db->query("SELECT casino_username FROM sw_members WHERE member_id = ? LIMIT 1", array($row->from_member_id));
				if($query_2->num_rows() > 0) {
					$row_2 = $query_2->row();
					
					if( ! empty($row_2->casino_username)) {
						$this->api_topup_credit($row_2->casino_username, $row->claim_amount);
					}
				}
			}
			
			$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 get_curency_rates()
	{
		$query = $this->db->query("SELECT * FROM sw_currencies");
		
		return $query;
	}
	
	function reset_member_rolling_gaming($member_id = NULL){
		$query = $this->db->query("SELECT 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();
			if($row->casino_plyid_1 != ""){
				$response = $this->api_reset_player_turnover($row->casino_plyid_1);
				$result_array = json_decode($response['data'], TRUE);
				if(isset($result_array['success']) && $result_array['success'] == TRUE) {
					$this->db->query("UPDATE sw_members SET rolling_gaming = ? WHERE member_id = ? LIMIT 1", array(0, $member_id));
					return true;	
				}else{
					return false;	
				}
			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	function api_create_account($username = NULL, $password = NULL)
	{
		$arr = array(
			"username" => $username,
			"password" => $password,
			"nickname" => $username,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'MemberRegisterDV',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"player" => array(
				"username" => $arr['username'],
				"password" => $arr['password'],
				"nickname" => $arr['nickname'],
			)
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_topup_credit($username = NULL, $amount = NULL)
	{
		$arr = array(
			"username" => $username,
			"amount" => $amount,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'CreditBalance',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"amount" => $arr['amount'],
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_get_balance($username = NULL) 
	{
		$arr = array(
			"username" => $username,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'GetBalanceDV',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_update_player_type($username = NULL) 
	{
		$arr = array(
			"username" => $username,
		);
		
		$signature = md5(WHITELABEL_AGENT_ID . implode('', $arr) . WHITELABEL_SECRET_KEY);
		
		$array_param = array(
			"method" => 'UpdatePlayerType',
			"agentId" => WHITELABEL_AGENT_ID,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
		);
		
		$url = WHITELABEL_URL;
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function curl_json($url = NULL, $arr = NULL) 
	{
		$data_string = json_encode($arr);  
		
		$ch = curl_init($url);  	
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                      
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                       	
		curl_setopt($ch, CURLOPT_HTTPHEADER, 
			array(
				'charset=UTF-8',
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string)
			)
		);   	
		$response = curl_exec($ch);
		curl_close($ch);
		
		return $response;
	}

	function api_reset_player_turnover($player_id = NULL)
	{
		$url = 'https://www.wikibet88.net/xi8bet/external_api/reset_player_turnover';
		$arr = array('player_id' => $player_id);
		$data_string = http_build_query($arr);  
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                      
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
		curl_setopt($ch, CURLOPT_HTTPHEADER, 
				array(
					'charset=UTF-8',
					'Content-Type: application/x-www-form-urlencoded',
					'Content-Length: ' . strlen($data_string)
				)
			);
		
		$response = curl_exec($ch);
		
		if (curl_errno($ch)) 
		{
			$result['code'] = '888';
			$result['msg'] = 'Failed';
			$result['data'] = '';
		}
		else
		{
			$result['code'] = '0';
			$result['msg'] = 'Success';
			$result['data'] = $response;
		}
		
		return $result;
	}
	
	function member_payout()
    {
		$this->lang->load('account_general', get_language());
	
		$security_key = trim($this->input->post('security_key', TRUE));
		
		#Populate submitted data
		$DBdata = array(
			'department_id' => trim($this->input->post('department_id', TRUE)),
			'payment_gateway_id' => trim($this->input->post('payment_gateway_id', TRUE)),
			'currency_id' => trim($this->input->post('currency_id', TRUE)),
			'bank_id' => trim($this->input->post('bank_id', TRUE)),
			'holder_name' => trim($this->input->post('holder_name', TRUE)),
			'account_no' => trim($this->input->post('account_no', TRUE)),
			'amount' => trim($this->input->post('amount', TRUE)),
			'order_no' => date("Ymdhms").sprintf("%05d", rand(1, 99999)),
			'remark' => trim($this->input->post('remark', TRUE)),
			'gateway_response' => '',
			'status' => 0,
			'created_by' => $this->session->userdata('username'),
			'created_date' => time()
		);
		
		#Data validation
		if($DBdata['holder_name'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('payout_holder_name_must_fill_in_message')));
    		return false;
    	} 
		else if($DBdata['account_no'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('payout_account_no_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9]+)$/",$DBdata['account_no'])) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('payout_invalid_to_account_no_message')));
			return false;
    	}
		else if($DBdata['amount'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('payout_amount_must_fill_in_message')));
    		return false;
    	} 
		else if ( ! preg_match("/^([0-9.]+)$/",$DBdata['amount']) || $DBdata['amount'] <= 0) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('payout_invalid_amount_message')));
			return false;
    	}
		else if($security_key != SECURITY_KEY_HIGH) {
			$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('payout_invalid_security_key_message')));
			return false;
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_payout', $DBdata);
		$DBdata['member_transaction_id'] = $this->db->insert_id();
		
		$this->insert_user_log($this->session->userdata('user_id'), LOG_PAYOUT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			//Call API - submit payout
			$result_msg = $this->call_payout($DBdata);
			
			if($result_msg == 'Success') {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $this->lang->line('payout_successful_message')));
			}
			else {
				$this->session->set_userdata(array('form_msg_type' => 100, 'form_msg' => $result_msg));
			}
			
			return true;
		}
		else {
			return false;
		}
    }
	
	public function call_payout($arr = NULL)
	{
		$username = PG_FPAY_PAYOUT_USERNAME;
		$api_key = PG_FPAY_PAYOUT_API_KEY;
		$send = array('username' => $username , 'api_key' => $api_key);
		$url = PG_FPAY_URL . '/merchant/auth';

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

		$response = curl_exec($curl);
		curl_close($curl);
		
		$json_arr = json_decode($response, true);
		
		if($json_arr['status'] == true) {
			$auth = $json_arr['auth']; //Get from auth api
			$amount = $arr['amount']; //Price amount
			$currency = "MYR"; //Currency code
			$orderid = $arr['order_no']; //Merchant withdraw order ID 
			$bank_id = $arr['bank_id']; //Get from withdraw bank list api 
			$bank_branch = ""; //Optional
			$holder_name = $arr['holder_name']; //Insert the receiver holder name must same as receiver bank account. 
			$account_no = $arr['account_no']; //Receiver Bank Account no 

			$send = array(
				  'auth' => $auth,
				  'amount' => $amount,
				  'currency' => $currency,
				  'orderid' => $orderid,
				  'bank_id' => $bank_id,
				  'bank_branch' => $bank_branch,
				  'holder_name' => $holder_name,
				  'account_no' => $account_no,
				);
				
			$url = PG_FPAY_URL . '/merchant/withdraw_orders';

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

			$response = curl_exec($curl);
			curl_close($curl);
			
			$json_arr = json_decode($response, true);
			
			if($json_arr['status'] == true) {
				$this->db->query("UPDATE sw_member_payout SET gateway_response = ?, status = ? WHERE member_transaction_id = ? LIMIT 1", array($json_arr['message'], 1, $arr['member_transaction_id']));
			}
			else {
				$this->db->query("UPDATE sw_member_payout SET gateway_response = ?, status = ? WHERE member_transaction_id = ? LIMIT 1", array($json_arr['message'], 2, $arr['member_transaction_id']));
			}
			
			return $json_arr['message'];
		}
	}
}