<?php

class Member_Model extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function insert_member_log($member_id = NULL, $log_type = NULL, $user_data = NULL)
    {
        #Populate submitted data
		$DBdata = array(
		   'member_id' => $member_id,
		   'log_type' => $log_type,
		   'ip_address' => $this->input->ip_address(),
		   'user_agent' => substr($this->input->user_agent(), 0, 120),
		   'log_date' => time(),
		   'user_data' => $user_data
		);
		
		$this->db->insert('sw_member_logs', $DBdata);
    }
	
	function get_member_account_details()
    {
        $query = $this->db->query("SELECT a.*, b.v_unit, b.v_unit2, b.v_unit3, b.v_unit4, b.v_unit5, b.v_unit6, b.v_unit7, b.v_unit8 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.member_id = ? LIMIT 1", array($this->session->userdata('member_id')))->row_array();
	    
	    return $query;
    }
	
	function member_compose_message()
	{
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'subject' => trim($this->input->post('message_subject', TRUE)),
			'message' => str_replace(array('javascript','script','iframe','style','document'), array(''), trim($this->input->post('message_message', TRUE))),
			'message_type' => MESSAGE_SENT,
			'member_read' => 0,
			'admin_read' => 1,
			'member_id' => $this->session->userdata('member_id'),
			'created_date' => time()
    	);
		
		#Data validation
		if($DBdata['subject'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('message_subject_must_fill_in_message')));
    		return false;
		} 
		else if($DBdata['message'] == '') {
    		$this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('message_message_must_fill_in_message')));
    		return false;
		} 
		
		$this->db->trans_start();
		
		$this->db->query('UPDATE sw_member_messages SET member_reply = ? WHERE message_id = ? LIMIT 1', array(trim($this->input->post('is_reply', TRUE)), trim($this->input->post('message_id', TRUE))));
		
		$this->db->insert('sw_member_messages', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_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 message_id, subject, message, member_read FROM sw_member_messages WHERE message_id = ? AND member_id = ? LIMIT 1", array($message_id, $this->session->userdata('member_id')))->row_array();
	    
		if(isset($query['member_read']) AND $query['member_read'] == 1) {
			$this->db->query("UPDATE sw_member_messages SET member_read = ? WHERE message_id = ? AND member_id = ? LIMIT 1", array(0, $query['message_id'], $this->session->userdata('member_id')));
		}
		
	    return $query;
    }
	
	function get_member_message_details_by_reply($message_id = NULL)
    {
        $query = $this->db->query("SELECT message_id, subject, message, member_read FROM sw_member_messages WHERE message_id = ? AND member_id = ? LIMIT 1", array($message_id, $this->session->userdata('member_id')))->row_array();
	    
		if(isset($query['member_read']) AND $query['member_read'] == 1) {
			$this->db->query("UPDATE sw_member_messages SET member_read = ? WHERE message_id = ? AND member_id = ? LIMIT 1", array(0, $query['message_id'], $this->session->userdata('member_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 register_member()
	{
		$this->lang->load('account_general', get_language());
	
		$payment_type = trim($this->input->post('payment_type', TRUE));
		$amount_1 = trim($this->input->post('amount_1', TRUE));
		$amount_2 = trim($this->input->post('amount_2', TRUE));
		$password = trim($this->input->post('password', TRUE));
		$confirm_password = trim($this->input->post('confirm_password', TRUE));
		$security_password = $password;
		$confirm_security_password = $confirm_password;
		
        #Populate submitted data
	    $DBdata = array(
			'username' => strtolower(trim($this->input->post('username', TRUE))),
			'password_origin' => $password,
			'password' => sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key'))))),
			'security_password_origin' => $security_password,
			'security_password' => sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'full_name' => trim($this->input->post('full_name', TRUE)),
			'dob' => date('Y-m-d', time()),
			'gender' => 1,
			'id_type' => 1,
			'id_no' => '',
			'email' => trim($this->input->post('email', TRUE)),
			'mobile_no' => trim($this->input->post('mobile_no', TRUE)),
			'nationality' => 'VN',
			'country' => 'VN',
			'bank_country' => 'VN',
			'origin_package_type' => trim($this->input->post('package_type', TRUE)),
			'package_type' => trim($this->input->post('package_type', TRUE)),
			'contract_start_date' => time(),
			'contract_expiry_date' => strtotime('+' . TENURE_CONTRACT . ' days', time()),
			'active' => 1,
			'member_type' => 2,
			'introducer' => $this->session->userdata('member_username'),
			'allowed_withdraw' => 1,
			'unlimited_withdraw' => 0,
			'allowed_transfer' => 1,
			'allowed_convert' => 1,
			'allowed_topup' => 1,
			'allowed_game' => 1,
			'total_invest' => 1,
			'allowed_invest' => 1,
			'insurance_date' => strtotime('+1 month', time()),
			'registered_by' => $this->session->userdata('member_username'),
			'registered_date' => time()
    	);
		
		#Data validation
		if($DBdata['package_type'] == '') {
    		return $this->lang->line('registration_package_type_must_fill_in_message');
		}
		else if($DBdata['username'] == '') {
    		return $this->lang->line('registration_username_must_fill_in_message');
		}
		else if( ! preg_match('/^[a-z0-9]{6,16}$/', $DBdata['username'])) {
			return $this->lang->line('registration_invalid_username_format_message');
		}
		
		#Check for username availbility
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? LIMIT 1", array($DBdata['username']));
		if($query->num_rows() > 0) {
			return $this->lang->line('registration_username_unavailable_message');
		}
		
		if($password == '') {
    		return $this->lang->line('registration_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^[A-Za-z0-9!#$^*]{6,15}$/", $password)) {
			return $this->lang->line('registration_invalid_password_format_message');
		} 
		else if ($password != $confirm_password) {
			return $this->lang->line('registration_confirm_password_not_match_message');
		} 
		else if($security_password == '') {
    		return $this->lang->line('registration_security_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^[A-Za-z0-9!#$^*]{6,15}$/", $security_password)) {
			return $this->lang->line('registration_invalid_security_password_format_message');
		} 
		else if ($security_password != $confirm_security_password) {
			return $this->lang->line('registration_confirm_security_password_not_match_message');	
		}
		// else if($DBdata['full_name'] == '') {
    		// return $this->lang->line('registration_full_name_must_fill_in_message');
		// }
		// else if($DBdata['mobile_no'] == '') {
    		// return $this->lang->line('registration_mobile_no_must_fill_in_message');
		// }
		else if($DBdata['email'] == '') {
    		return $this->lang->line('registration_email_must_fill_in_message');
		} 
		else if (!isEmail($DBdata['email'])) {
    		return $this->lang->line('registration_invalid_email_message');
		}
		
		#Check for email availbility
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE email = ? LIMIT 1", array($DBdata['email']));
		if($query->num_rows() > 0) {
			return $this->lang->line('registration_email_unavailable_message');
		}
		
		if($DBdata['introducer'] == '') {
			return $this->lang->line('registration_introducer_must_fill_in_message');
		}
		
		#Check for introducer availbility
		$introducer_id = 0;
		$introducer_v_unit5 = 0;
		$query = $this->db->query("SELECT a.member_id, a.introducer_parent_ref, b.v_unit5 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.username = ? LIMIT 1", array($DBdata['introducer']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$introducer_id = $row->member_id;
			$introducer_v_unit5 = $row->v_unit5;
			
			if(empty($row->introducer_parent_ref)) {
				$DBdata['introducer_parent_ref'] = ',' . $row->member_id . ',';
			}
			else {
				$DBdata['introducer_parent_ref'] = $row->introducer_parent_ref . $row->member_id . ',';
			}
		}
		else {
			return $this->lang->line('registration_introducer_unavailable_message');
		}
		
		#Check for package type availability
		$package_price = 0;
		$package_price_1 = 0;
		$package_price_2 = 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;
			$package_price_1 = ($row->package_price / 2);
			$package_price_2 = ($row->package_price / 2);
		}
		else {
			return $this->lang->line('registration_package_type_no_found_message');
		}
		
		#Check for wallet balance
		$available_balance_1 = 0;
		$available_balance_2 = 0;
		$query = $this->db->query("SELECT v_unit3, v_unit5 FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$available_balance_1 = $row->v_unit3;
			$available_balance_2 = $row->v_unit5;
		}
		
		if($payment_type == 1) {
			if($available_balance_1 < $package_price) {
				return $this->lang->line('registration_insufficient_1');
			}
		}
		else {
			$total_amount = ($amount_1 + $amount_2);
			
			if($available_balance_1 < $amount_1) {
				return $this->lang->line('registration_insufficient_1');
			}
			else if($package_price_1 > $amount_1) {
				return $this->lang->line('registration_insufficient_5');
			}
			else if($available_balance_2 < $amount_2) {
				return $this->lang->line('registration_insufficient_2');
			}
			else if($total_amount != $package_price) {
				return $this->lang->line('registration_insufficient_4');
			}
		}
		
		$this->db->trans_start();
		
		$leverage = 3.5;
		$effect_time = time();
		if($effect_time >= 1668700800) {
			$leverage = 4;
		}
		
		$DBdata['current_package_amt'] = $package_price;
		$DBdata['current_extra_amt'] = ($package_price * 0.1);
		$DBdata['total_capital'] = ($package_price * 2);
		$DBdata['total_rolling'] = ($package_price * $leverage);
		
		$this->db->insert('sw_members', $DBdata);
		
		$db_data['v_unit'] = ($package_price * 0.1);
		$db_data['member_id'] = $this->db->insert_id();
		
		$this->db->insert('sw_member_wallets', $db_data);
		
		if($payment_type == 1) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 - ?) WHERE member_id = ? LIMIT 1", array($package_price, $this->session->userdata('member_id')));
			
			$trans_data = array(
				'transaction_type' => 1,
				'from_member_id' => $this->session->userdata('member_id'),
				'from_member_username' => $this->session->userdata('member_username'),
				'to_member_id' => $db_data['member_id'],
				'to_member_username' => $DBdata['username'],
				'from_credit_balance' => $available_balance_1,
				'credit_amount' => $package_price,
				'to_credit_balance' => ($available_balance_1 - $package_price),
				'status' => 1,
				'transaction_date' => time()
			);	
			$this->db->insert('sw_member_placement', $trans_data);
		}
		else {
			$this->db->query("UPDATE sw_member_wallets SET v_unit3 = (v_unit3 - ?), v_unit5 = (v_unit5 - ?) WHERE member_id = ? LIMIT 1", array($amount_1, $amount_2, $this->session->userdata('member_id')));
			
			$trans_data = array(
				'transaction_type' => 1,
				'from_member_id' => $this->session->userdata('member_id'),
				'from_member_username' => $this->session->userdata('member_username'),
				'to_member_id' => $db_data['member_id'],
				'to_member_username' => $DBdata['username'],
				'from_credit_balance' => $available_balance_1,
				'credit_amount' => $amount_1,
				'to_credit_balance' => ($available_balance_1 - $amount_1),
				'status' => 1,
				'transaction_date' => time()
			);	
			$this->db->insert('sw_member_placement', $trans_data);
			
			$trans_data = array(
				'transaction_type' => 2,
				'from_member_id' => $this->session->userdata('member_id'),
				'from_member_username' => $this->session->userdata('member_username'),
				'to_member_id' => $db_data['member_id'],
				'to_member_username' => $DBdata['username'],
				'from_credit_balance' => $available_balance_2,
				'credit_amount' => $amount_2,
				'to_credit_balance' => ($available_balance_2 - $amount_2),
				'status' => 1,
				'transaction_date' => time()
			);	
			$this->db->insert('sw_member_placement', $trans_data);
		}
		
		//Insert game withdrawal
		$mgw_data = array(
			'from_member_id' => $db_data['member_id'],
			'from_member_username' => $DBdata['username'],
			'deposit_date' => time(),
			'deposit_amount' => $package_price,
			'deposit_bonus' => ($package_price * 0.1),
		);	
		$this->db->insert('sw_member_game_withdrawals', $mgw_data);
		
		//For promotion
		// $current_time = time();
		// if($current_time >= 1662307200) {
			// $special_rebate = 0;
			
			// switch($DBdata['package_type']) {
				// case 2: $special_rebate = 200; break;
				// case 1: $special_rebate = 50; break;
				// default: $special_rebate = 0; break;
			// }
			
			// $this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 + ?) WHERE member_id = ? LIMIT 1", array($special_rebate, $introducer_id));
			
			// $promo_data = array(
				// 'transaction_type' => 5,
				// 'to_member_id' => $introducer_id,
				// 'to_member_username' => $DBdata['introducer'],
				// 'from_debit_balance' => $introducer_v_unit5,
				// 'debit_amount' => $special_rebate,
				// 'to_debit_balance' => ($introducer_v_unit5 + $special_rebate),
				// 'status' => 1,
				// 'transaction_date' => time()
			// );	
			// $this->db->insert('sw_member_topup', $promo_data);
		// }
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_ADD_MEMBER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			//CALL API - create account asiagaming1688
			$response = $this->api_create_account(1, $DBdata['username'], $DBdata['password_origin'], $DBdata['package_type']);
			$result_array = json_decode($response, TRUE);
			if(isset($result_array['status']) && $result_array['status'] == 0) {
				$this->db->query("UPDATE sw_members SET casino_plyid_1 = ? WHERE member_id = ? LIMIT 1", array($result_array['player_id'], $db_data['member_id']));
			}
			
			//CALL API - create account luckyb3t
			$response_2 = $this->api_create_account(2, $DBdata['username'], $DBdata['password_origin'], $DBdata['package_type']);
			$result_array_2 = json_decode($response_2, TRUE);
			if(isset($result_array_2['status']) && $result_array_2['status'] == 0) {
				$this->db->query("UPDATE sw_members SET casino_plyid_2 = ? WHERE member_id = ? LIMIT 1", array($result_array_2['player_id'], $db_data['member_id']));
			}
			
			//CALL API - topup credit asiagaming1688
			if(isset($result_array['player_id']) && $result_array['player_id'] > 0) {
				$this->api_topup_credit(1, $DBdata['username'], $package_price);
			}
			
			//CALL API - topup credit luckyb3t
			if(isset($result_array_2['player_id']) && $result_array_2['player_id'] > 0) {
				$this->api_topup_credit(2, $DBdata['username'], $package_price);
			}
			
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
	}
	
	function get_package_list()
    {
        $query = $this->db->query("SELECT * FROM sw_packages ORDER BY package_price ASC");
	    
	    return $query;
    }
	
	function get_package_details($package_id = NULL)
    {
        $query = $this->db->query("SELECT * FROM sw_packages WHERE package_id = ? LIMIT 1", array($package_id))->row_array();
	    
	    return $query;
    }
	
	function member_reinvest()
	{
	    $this->lang->load('account_general', get_language());
	
		$security_password = trim($this->input->post('security_password', TRUE));
		
		#get package type
		$current_package_type = 0;
		$selected_package_type = 0;
		$query = $this->db->query("SELECT package_type FROM sw_members WHERE member_id = ? AND package_type > ? LIMIT 1", array($this->session->userdata('member_id'), 0));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$current_package_type = $row->package_type;
			$selected_package_type = $row->package_type;
		}
		else {
			$selected_package_type = trim($this->input->post('package_type', TRUE));
		}
		
        #Populate submitted data
		$DBdata = array(
			'reinvest_type' => 1,
			'reinvest_package_type' => $selected_package_type,
			'reinvest_package_date' => time(),
			'member_id' => $this->session->userdata('member_id')
    	);
		
		#Check for package type availability
		$package_price = 0;
		$query = $this->db->query("SELECT package_price FROM sw_packages WHERE package_id = ? LIMIT 1", array($DBdata['reinvest_package_type']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$package_price = $row->package_price;
		}
		else {
			return $this->lang->line('registration_package_type_no_found_message');
		}

		if($security_password == '') {
    		return $this->lang->line('registration_security_password_must_fill_in_message');
		}
		
		#Check for security password availbility
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? AND active = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password, 1));
		if($query->num_rows() == 0) {
			return $this->lang->line('registration_invalid_security_password_message');
		}
		
		#Check for wallet balance
		$available_balance = 0;
		$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$available_balance = $row->v_unit;
		}
		
		if($available_balance < $package_price) {
			return $this->lang->line('registration_insufficient_3');
		}
		
		#Check for allow invest
		$query = $this->db->query("SELECT member_transaction_id FROM sw_member_game_withdrawals WHERE from_member_id = ? AND withdrawal_status = ? LIMIT 1", array($this->session->userdata('member_id'), 0));
		if($query->num_rows() > 0) {
			return $this->lang->line('registration_still_have_rolling_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_reinvest', $DBdata);
		
		$leverage = 3.5;
		$effect_time = time();
		if($effect_time >= 1668700800) {
			$leverage = 4;
		}
		
		$current_package_amt = $package_price;
		$current_extra_amt = ($package_price * 0.1);
		$total_capital = ($package_price * 2);
		$total_rolling = ($package_price * $leverage);
		
		if($current_package_type == 0) {
			$this->db->query("UPDATE sw_members SET package_type = ?, total_invest = (total_invest + ?), total_reinvest = (total_reinvest + ?), allowed_invest = ?, current_package_amt = ?, current_extra_amt = ?, total_capital = ?, total_rolling = ? WHERE member_id = ? LIMIT 1", array($DBdata['reinvest_package_type'], 1, $current_package_amt, 1, $current_package_amt, $current_extra_amt, $total_capital, $total_rolling, $this->session->userdata('member_id')));
		}
		else {
			$this->db->query("UPDATE sw_members SET total_invest = (total_invest + ?), total_reinvest = (total_reinvest + ?), allowed_invest = ?, current_package_amt = ?, current_extra_amt = ?, total_capital = ?, total_rolling = ? WHERE member_id = ? LIMIT 1", array(1, $current_package_amt, 1, $current_package_amt, $current_extra_amt, $total_capital, $total_rolling, $this->session->userdata('member_id')));
		}
		
		$extra_amount = ($package_price * 0.1);
		$deduct_amount = ($package_price - $extra_amount);
		
		$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($deduct_amount, $this->session->userdata('member_id')));
		
		//Insert game withdrawal
		$mgw_data = array(
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'deposit_date' => time(),
			'deposit_amount' => $package_price,
			'deposit_bonus' => ($package_price * 0.1),
		);	
		$this->db->insert('sw_member_game_withdrawals', $mgw_data);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_MEMBER_REINVEST, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			//CALL API - topup credit
			$query = $this->db->query("SELECT username FROM sw_members WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				//CALL API - update player type asiagaming1688
				$this->api_update_player_type(1, $row->username, $DBdata['reinvest_package_type']);
				
				//CALL API - update player type luckyb3t
				$this->api_update_player_type(2, $row->username, $DBdata['reinvest_package_type']);
				
				//CALL API - topup credit asiagaming1688
				$this->api_topup_credit(1, $row->username, $package_price);
				
				//CALL API - topup credit luckyb3t
				$this->api_topup_credit(2, $row->username, $package_price);
			}
			
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
	}
	
	function get_member_applied_miss_bet()
    {
		$timespan = time();
		$t_day = date('w', $timespan);
		$today_start = strtotime(date('Y-m-d 00:00:00'));
		$today_end = strtotime(date('Y-m-d 23:59:59'));
		$fd_of_week = $today_start;
		$ld_of_week = $today_end;

		switch($t_day) {
			case 1: $ld_of_week = ($ld_of_week + (86400 * 6)); break;
			case 2: $fd_of_week = ($fd_of_week - (86400 * 1)); $ld_of_week = ($ld_of_week + (86400 * 5)); break;
			case 3: $fd_of_week = ($fd_of_week - (86400 * 2)); $ld_of_week = ($ld_of_week + (86400 * 4)); break;
			case 4: $fd_of_week = ($fd_of_week - (86400 * 3)); $ld_of_week = ($ld_of_week + (86400 * 3)); break;
			case 5: $fd_of_week = ($fd_of_week - (86400 * 4)); $ld_of_week = ($ld_of_week + (86400 * 2)); break;
			case 6: $fd_of_week = ($fd_of_week - (86400 * 5)); $ld_of_week = ($ld_of_week + (86400 * 1)); break;
			default: $fd_of_week = ($fd_of_week - (86400 * 6)); break;
		}

		$query_today = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_miss_bets WHERE from_member_id = ? AND transaction_type = ? AND transaction_date > ? AND transaction_date < ?", array($this->session->userdata('member_id'), 1, $today_start, $today_end))->row();
		$today_total = ((isset($query_today->total) && $query_today->total > 0) ? $query_today->total : 0);

		$query_week = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_miss_bets WHERE from_member_id = ? AND transaction_type = ? AND transaction_date > ? AND transaction_date < ?", array($this->session->userdata('member_id'), 1, $fd_of_week, $ld_of_week))->row();
		$week_total = ((isset($query_week->total) && $query_week->total > 0) ? $query_week->total : 0);
		
		$arr = array('p_today' => $today_total, 'p_week' => $week_total);
		
	    return $arr;
    }
	
	function member_apply_miss_bet()
	{
	    $this->lang->load('account_general', get_language());
	
		$security_password = trim($this->input->post('security_password', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => 1,
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'status' => 0,
			'transaction_date' => time()
    	);
		
		if($security_password == '') {
    		return $this->lang->line('miss_bet_security_password_must_fill_in_message');
		}
		
		#Check for security password availbility
		$insurance_date = 0;
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT insurance_date FROM sw_members WHERE member_id = ? AND security_password = ? AND active = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$insurance_date = $row->insurance_date;
		}
		else {
			return $this->lang->line('miss_bet_invalid_security_password_message');
		}
		
		$timespan = time();
		
		if($insurance_date < $timespan) {
			return $this->lang->line('miss_bet_invalid_insurance_date_message');
		}
		
		$t_day = date('w', $timespan);
		$today_start = strtotime(date('Y-m-d 00:00:00'));
		$today_end = strtotime(date('Y-m-d 23:59:59'));
		$fd_of_week = $today_start;
		$ld_of_week = $today_end;

		switch($t_day) {
			case 1: $ld_of_week = ($ld_of_week + (86400 * 6)); break;
			case 2: $fd_of_week = ($fd_of_week - (86400 * 1)); $ld_of_week = ($ld_of_week + (86400 * 5)); break;
			case 3: $fd_of_week = ($fd_of_week - (86400 * 2)); $ld_of_week = ($ld_of_week + (86400 * 4)); break;
			case 4: $fd_of_week = ($fd_of_week - (86400 * 3)); $ld_of_week = ($ld_of_week + (86400 * 3)); break;
			case 5: $fd_of_week = ($fd_of_week - (86400 * 4)); $ld_of_week = ($ld_of_week + (86400 * 2)); break;
			case 6: $fd_of_week = ($fd_of_week - (86400 * 5)); $ld_of_week = ($ld_of_week + (86400 * 1)); break;
			default: $fd_of_week = ($fd_of_week - (86400 * 6)); break;
		}
		
		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_miss_bets WHERE from_member_id = ? AND transaction_type = ? AND transaction_date > ? AND transaction_date < ?", array($this->session->userdata('member_id'), 1, $today_start, $today_end))->row();
		$today_total = ((isset($query->total) && $query->total > 0) ? $query->total : 0);

		$query = $this->db->query("SELECT COUNT(member_transaction_id) AS total FROM sw_member_miss_bets WHERE from_member_id = ? AND transaction_type = ? AND transaction_date > ? AND transaction_date < ?", array($this->session->userdata('member_id'), 1, $fd_of_week, $ld_of_week))->row();
		$week_total = ((isset($query->total) && $query->total > 0) ? $query->total : 0);
		
		if($week_total >= 5)
		{
			return $this->lang->line('miss_bet_five_times_per_week_message');
		}
		else if($today_total >= 3)
		{
			return $this->lang->line('miss_bet_three_times_per_day_message');
		}
		
		$query = $this->db->query("SELECT insurance_date FROM sw_members WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$DBdata['insurance_expiry_date'] = $row->insurance_date;
		}
		
		$arr = $this->update_wallet();
		
		if(isset($arr['v_unit6'])) {
			$DBdata['v_unit6'] = str_replace(',', '', $arr['v_unit6']);
			$DBdata['v_unit7'] = str_replace(',', '', $arr['v_unit7']);
			$DBdata['v_unit8'] = str_replace(',', '', $arr['v_unit8']);
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_miss_bets', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_APPLY_MISS_BET, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
	}
	
	function member_buy_insurance()
	{
	    $this->lang->load('account_general', get_language());
	
		$security_password = trim($this->input->post('security_password', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'insurance_date' => date('Y-m-d', time()),
			'status' => 1,
			'transaction_date' => time()
    	);
		
		if($security_password == '') {
    		return $this->lang->line('insurance_security_password_must_fill_in_message');
		}
		
		#Check for security password availbility
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? AND active = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password, 1));
		if($query->num_rows() == 0) {
			return $this->lang->line('insurance_invalid_security_password_message');
		}
		
		#Check for package type & wallet balance
		$package_type = 0;
		$insurance_date = 0;
		$available_balance = 0;
		$query = $this->db->query("SELECT a.package_type, a.insurance_date, b.v_unit FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND a.member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$package_type = $row->package_type;
			$insurance_date = $row->insurance_date;
			$available_balance = $row->v_unit;
		}
		
		if($package_type == 0) {
			return $this->lang->line('insurance_buy_package_before_continue_message');
		}
		
		$remaining_day = 0;
		if(isset($insurance_date)) {
			$current_date = time();
			
			if($insurance_date > $current_date) {
				$tmp = ($insurance_date - $current_date);
				$tmp2 = ($tmp / 86400);
				$arr = explode('.', $tmp2);
				$remaining_day = $arr[0];
			}
			else {
				$remaining_day = 0;
			}
		}
		
		if($remaining_day > 0) {
			return $this->lang->line('insurance_still_running_message');
		}
		
		switch($package_type) {
			case 2: $DBdata['credit_amount'] = 300; break;
			case 1: $DBdata['credit_amount'] = 100; break;
		}
		
		if($available_balance < $DBdata['credit_amount']) {
			return $this->lang->line('insurance_insufficient_amount_message');
		}
		
		$DBdata['from_credit_balance'] = $available_balance;
		$DBdata['to_credit_balance'] = ($available_balance - $DBdata['credit_amount']);
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_buy_insurances', $DBdata);
		
		$new_insurance_date = strtotime('+1 month', time());
		$this->db->query("UPDATE sw_members SET insurance_date = ? WHERE member_id = ? LIMIT 1", array($new_insurance_date, $this->session->userdata('member_id')));
		$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $this->session->userdata('member_id')));
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_BUY_INSURANCE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
	}
	
	function update_profile()
    {
		$this->lang->load('account_general', get_language());
	
        #Populate submitted data
	    $DBdata = array(
			'full_name' => trim($this->input->post('full_name', TRUE)),
			'email' => trim($this->input->post('email', TRUE)),
			// 'dob' => trim($this->input->post('dob_year', TRUE)) . '-' . trim($this->input->post('dob_month', TRUE)) . '-' . trim($this->input->post('dob_day', TRUE)),
			// 'gender' => trim($this->input->post('gender', TRUE)),
			// 'id_type' => 1,
			// 'id_no' => trim($this->input->post('id_no', TRUE)),
			// 'nationality' => trim($this->input->post('nationality', 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)),
			'wallet_address' => trim($this->input->post('wallet_address', TRUE)),
			// 'bank_country' => trim($this->input->post('bank_country', TRUE)),
			// 'bank_swift_code' => trim($this->input->post('bank_swift_code', TRUE)),
			'is_profile_locked' => 1,
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
    	);
		
		#Data validation
		// if($DBdata['dob'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_dob_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['gender'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_gender_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['id_type'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_id_type_must_fill_in_message')));
    		// return false;
		// }
		if($DBdata['full_name'] == '') {
    		return $this->lang->line('registration_full_name_must_fill_in_message');
		}
		else if($DBdata['mobile_no'] == '') {
    		return $this->lang->line('registration_mobile_no_must_fill_in_message');
		}
		else if($DBdata['email'] == '') {
    		return $this->lang->line('registration_email_must_fill_in_message');
		}
		// else if($DBdata['id_no'] == '') {
    		// return $this->lang->line('registration_id_no_must_fill_in_message');
		// }
		// else if($DBdata['nationality'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_nationality_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['address'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_address_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['city'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_city_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['postal_code'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_postal_code_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['state'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_state_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['country'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_country_must_fill_in_message')));
    		// return false;
		// }
		// else if($DBdata['bank_name'] == '') {
    		// return $this->lang->line('registration_bank_name_must_fill_in_message');
		// }
		// else if($DBdata['bank_account_no'] == '') {
    		// return $this->lang->line('registration_bank_account_no_must_fill_in_message');
		// }
		// else if($DBdata['account_holder_name'] == '') {
    		// return $this->lang->line('registration_account_holder_name_must_fill_in_message');
		// }
		// else if($DBdata['bank_address'] == '') {
    		// return $this->lang->line('registration_bank_address_must_fill_in_message');
		// }
		// else if($DBdata['bank_country'] == '') {
    		// $this->session->set_userdata(array('form_msg_type' => 200, 'form_msg' => $this->lang->line('registration_bank_country_must_fill_in_message')));
    		// return false;
		// }
		else if($DBdata['wallet_address'] == '') {
    		return $this->lang->line('registration_wallet_address_must_fill_in_message');
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_EDIT_PROFILE, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function change_login_password()
    {
		$this->lang->load('account_general', get_language());
	
		$old_password = trim($this->input->post('old_login_password', TRUE));
		$new_password = trim($this->input->post('login_password', TRUE));
		$confirm_password = trim($this->input->post('confirm_login_password', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'password_origin' => $new_password,
			'password' => sha1(md5(sha1(md5($new_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
    	);
		
		#Data validation
		if($old_password == '') {
    		return $this->lang->line('profile_old_password_must_fill_in_message');
    	}
		else if($new_password == '') {
    		return $this->lang->line('profile_new_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$new_password)) {
			return $this->lang->line('profile_new_password_format_message');
    	}
		else if($new_password != $confirm_password) {
    		return $this->lang->line('profile_new_password_not_match_message');
    	}
		
		#Check for existing password
		$encrypted_password = sha1(md5(sha1(md5($old_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND password = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('profile_invalid_old_password_message');
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CHANGE_LOGIN_PASSWORD, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function change_security_password()
    {
		$this->lang->load('account_general', get_language());
	
		$old_password = trim($this->input->post('old_security_password', TRUE));
		$new_password = trim($this->input->post('security_password', TRUE));
		$confirm_password = trim($this->input->post('confirm_security_password', TRUE));
	
        #Populate submitted data
	    $DBdata = array(
			'security_password_origin' => $new_password,
			'security_password' => sha1(md5(sha1(md5($new_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'modified_by' => $this->session->userdata('member_username'),
			'modified_date' => time()
    	);
		
		#Data validation
		if($old_password == '') {
    		return $this->lang->line('profile_old_password_must_fill_in_message');
    	}
		else if($new_password == '') {
    		return $this->lang->line('profile_new_password_must_fill_in_message');
		} 
		else if ( ! preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/",$new_password)) {
			return $this->lang->line('profile_new_password_format_message');
    	}
		else if($new_password != $confirm_password) {
    		return $this->lang->line('profile_new_password_not_match_message');
    	}
		
		#Check for existing security password
		$encrypted_password = sha1(md5(sha1(md5($old_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('profile_invalid_old_password_message');
		}
		
		$this->db->trans_start();
		
		$this->db->where('member_id', $this->session->userdata('member_id'));
		$this->db->limit(1);
		$this->db->update('sw_members', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CHANGE_SECURITY_PASSWORD, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function get_member_total_topup()
    {
		$query = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE to_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
		
	    return $query->total;
    }
	
	function get_member_total_invest()
    {
		$origin_query = $this->db->query("SELECT package_price AS total_amount FROM sw_members a, sw_packages b WHERE (a.origin_package_type = b.package_id) AND a.member_id = ? LIMIT 1", array($this->session->userdata('member_id')))->row();
		$reinvest_query = $this->db->query("SELECT COUNT(member_reinvest_id) AS total_invest, SUM(b.package_price) AS total_amount FROM sw_member_reinvest a, sw_packages b WHERE (a.reinvest_package_type = b.package_id) AND a.member_id = ?", array($this->session->userdata('member_id')))->row();
		$o_total_amount = (isset($origin_query->total_amount) ? $origin_query->total_amount : 0);
		$r_total_invest = (isset($reinvest_query->total_invest) ? $reinvest_query->total_invest : 0);
		$r_total_amount = (isset($reinvest_query->total_amount) ? $reinvest_query->total_amount : 0);
	    $data['total_invest'] = ((($o_total_amount > 0) ? 1 : 0) + $r_total_invest);
		$data['total_amount'] = ($o_total_amount + $r_total_amount);
		
	    return $data;
    }
	
	function get_member_total_reinvest_expired()
    {
		$current_time = time();
		
		$origin_query = $this->db->query("SELECT COUNT(member_id) AS total FROM sw_members WHERE member_id = ? AND contract_expiry_date < ?", array($this->session->userdata('member_id'), $current_time))->row();
		$reinvest_query = $this->db->query("SELECT COUNT(member_reinvest_id) AS total FROM sw_member_reinvest WHERE member_id = ? AND reinvest_expiry_date < ?", array($this->session->userdata('member_id'), $current_time))->row();
	    $total = ($origin_query->total + $reinvest_query->total);
		 
	    return $total;
    }
	
	function get_member_total_withdrawal()
    {
		$query_pending = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 0))->row();
		$query_success = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 2))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }

	function get_member_total_withdrawal_bank_transfer()
    {
		$query_pending = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 0, 1))->row();
		$query_success = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 1, 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 2, 1))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }

    function get_member_total_withdrawal_usdt()
    {
		$query_pending = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 0, 2))->row();
		$query_success = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 1, 2))->row();
		$query_cancel = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 2, 2))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }    
	
	function get_member_total_earn()
    {
		$query_1 = $this->db->query("SELECT SUM(v_unit_amount) AS total FROM sw_member_transactions WHERE to_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
		$query_2 = $this->db->query("SELECT SUM(profit) AS total FROM sw_member_game_withdrawals WHERE from_member_id = ? AND withdrawal_status = ?", array($this->session->userdata('member_id'), 1))->row();
		$total_amount_1 = (isset($query_1->total) ? $query_1->total : 0);
		$total_amount_2 = (isset($query_2->total) ? $query_2->total : 0);
		$grand_total = ($total_amount_1 + $total_amount_2);
		
	    return $grand_total;
    }
	
	function get_setting_rates()
	{
		$query = $this->db->query("SELECT * FROM sw_setting LIMIT 1")->row_array();
	    
	    return $query;
	}
	
	function member_withdraw_to_coin()
    {
		$this->lang->load('account_general', get_language());
	
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
		$setting = $this->member_model->get_setting_rates();
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => 2,
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'credit_amount' => $transaction_amount,
			'status' => 0,
			'transaction_date' => time()
		);
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('withdraw_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('withdraw_invalid_amount_message');
    	}
		else {
			if($transaction_amount < $setting['min_withdraw']) {
				return str_replace('_MIN_', number_format($setting['min_withdraw'], 2, '.', ''), $this->lang->line('withdraw_minimum_maximum_amount'));
			}
		}
		
		if($this->session->userdata('member_unlimited_withdraw') AND $this->session->userdata('member_unlimited_withdraw') == 1) {
			//Do nothing...
		}
		else {
			$final_amount = $transaction_amount;
			$query = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_withdraw WHERE from_member_id = ? AND transaction_type = ? AND status < ?", array($DBdata['from_member_id'], 1, 2));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$final_amount = ($final_amount + $row->total);
			}
			
			if($final_amount > $setting['max_withdraw_per_day']) {
				return $this->lang->line('withdraw_withdrawal_limit_exceeded_message');
			}
		}
		
		if($security_password == '') {
    		return $this->lang->line('withdraw_security_password_must_fill_in_message');
    	}
		
		$DBdata['charges'] = (($DBdata['credit_amount'] * $setting['withdrawal_rate']) / 100);
		$DBdata['withdrawal_amount'] = ($DBdata['credit_amount'] - $DBdata['charges']);
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() > 0) {
			$row = $query->row();
		}
		else {
			return $this->lang->line('withdraw_invalid_security_password_message');
		}
		
		#Check for available balance
		$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 {
			return $this->lang->line('withdraw_insufficient_amount_message');
		}
		
		#Check for wallet address
		$query = $this->db->query("SELECT wallet_address FROM sw_members WHERE member_id = ? LIMIT 1", array($DBdata['from_member_id']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['to_bank_address'] = $row->wallet_address;
			
			if($row->wallet_address == '') {
				return $this->lang->line('withdraw_invalid_wallet_address_message');
			}
		}
		else {
			return $this->lang->line('withdraw_invalid_account_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_withdraw', $DBdata);
		
		#Credit
		$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_WITHDRAWAL, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function get_member_total_transfer($type = NULL)
    {
		$query_pending = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_transfers WHERE transaction_type = ? AND from_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 0))->row();
		$query_success = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_transfers WHERE transaction_type = ? AND from_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_transfers WHERE transaction_type = ? AND from_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 2))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }

    function get_to_member_total_transfer($type = NULL)
    {
		$query_pending = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_transfers WHERE transaction_type = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 0))->row();
		$query_success = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_transfers WHERE transaction_type = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_transfers WHERE transaction_type = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 2))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }
	
	function member_transfer()
    {
		$this->lang->load('account_general', get_language());
	
		$wallet_type = trim($this->input->post('wallet_type', TRUE));
		$member_username = trim($this->input->post('member_username', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => (($wallet_type == 1 || $wallet_type == 3 || $wallet_type == 5) ? $wallet_type : 1),
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'credit_amount' => $transaction_amount,
			'debit_amount' => $transaction_amount,
			'status' => 1,
			'transaction_date' => time()
		);
		
		$setting = $this->member_model->get_setting_rates();
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('transfer_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/", $transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('transfer_invalid_amount_message');
    	}
		else if($transaction_amount < $setting['min_transfer']) {
			return str_replace('_MIN_', number_format($setting['min_transfer'], 2, '.', ''), $this->lang->line('transfer_min_request_message'));
		}
		else if($member_username == '') {
    		return $this->lang->line('transfer_member_username_must_fill_in_message');
		}
		else if($security_password == '') {
    		return $this->lang->line('transfer_security_password_must_fill_in_message');
    	}
		
		$today_start = strtotime(date('Y-m-d 00:00:00'));
		$today_end = strtotime(date('Y-m-d 23:59:59'));
		$final_amount = $transaction_amount;
		$query = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_transfers WHERE from_member_id = ? AND transaction_type = ? AND status < ? AND transaction_date >= ? AND transaction_date <= ?", array($DBdata['from_member_id'], $DBdata['transaction_type'], 2, $today_start, $today_end));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$final_amount = ($final_amount + $row->total);
		}
		
		if($DBdata['transaction_type'] == 1 && $final_amount > $setting['max_transfer_per_day']) {
			return str_replace('_MAX_', $setting['max_transfer_per_day'], $this->lang->line('transfer_max_request_message'));
		}
		else if($DBdata['transaction_type'] == 3 && $final_amount > $setting['max_transfer_per_day_2']) {
			return str_replace('_MAX_', $setting['max_transfer_per_day_2'], $this->lang->line('transfer_max_request_message'));
		}
		else if($DBdata['transaction_type'] == 5 && $final_amount > $setting['max_transfer_per_day_3']) {
			return str_replace('_MAX_', $setting['max_transfer_per_day_3'], $this->lang->line('transfer_max_request_message'));
		}
		
		#Check for member username availability
		$query = $this->db->query("SELECT member_id, username FROM sw_members WHERE member_id != ? AND username = ? AND active = ? LIMIT 1", array($DBdata['from_member_id'], $member_username, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$sub_query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND introducer_parent_ref LIKE '%," . $row->member_id . ",%' LIMIT 1", array($DBdata['from_member_id']));
			if($sub_query->num_rows() > 0) {
				$DBdata['to_member_id'] = $row->member_id;
				$DBdata['to_member_username'] = $row->username;
			}
			else {
				$sub_query2 = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND introducer_parent_ref LIKE '%," . $DBdata['from_member_id'] . ",%' LIMIT 1", array($row->member_id));
				if($sub_query2->num_rows() > 0) {
					$DBdata['to_member_id'] = $row->member_id;
					$DBdata['to_member_username'] = $row->username;
				} 
				else {
					return $this->lang->line('transfer_invalid_member_username_message');
				}
			}
		}
		else {
			return $this->lang->line('transfer_invalid_member_username_message');
		}
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('transfer_invalid_security_password_message');
		}
		
		#Check for available balance
		if($DBdata['transaction_type'] == 5) {
			$query = $this->db->query("SELECT v_unit5 FROM sw_member_wallets WHERE v_unit5 >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit5;
				$DBdata['to_credit_balance'] = ($row->v_unit5 - $transaction_amount);
			}
			else {
				return $this->lang->line('transfer_insufficient_amount_message');
			}
			
			$query = $this->db->query("SELECT v_unit5 FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_debit_balance'] = $row->v_unit5;
				$DBdata['to_debit_balance'] = ($row->v_unit5 + $transaction_amount);
			}
		}
		else if($DBdata['transaction_type'] == 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 {
				return $this->lang->line('transfer_insufficient_amount_message');
			}
			
			$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 {
			$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE v_unit >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
			}
			else {
				return $this->lang->line('transfer_insufficient_amount_message');
			}
			
			$query = $this->db->query("SELECT v_unit FROM sw_member_wallets WHERE member_id = ? LIMIT 1", array($DBdata['to_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_debit_balance'] = $row->v_unit;
				$DBdata['to_debit_balance'] = ($row->v_unit + $transaction_amount);
			}
		}	
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_transfers', $DBdata);
		
		#Credit
		if($DBdata['transaction_type'] == 5) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
		
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit5 = (v_unit5 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
		}
		else if($DBdata['transaction_type'] == 3) {
			$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 {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			
			#Debit
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit + ?) WHERE member_id = ? LIMIT 1", array($DBdata['debit_amount'], $DBdata['to_member_id']));
		}
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_TRANSFER, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function get_member_downline($username = NULL)
    {
		$root_member_id = $this->session->userdata('member_id');
		$member_lists = array();	
		$member_query = $this->db->query("SELECT member_id, username FROM sw_members WHERE introducer_parent_ref LIKE '%,$root_member_id,%'");
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				$member_lists[$member_row->member_id] = array('username' => $member_row->username, 'total_intro' => 0);	
			}
		}
		
		$member_query = $this->db->query("SELECT member_id, username, introducer_parent_ref FROM sw_members WHERE introducer_parent_ref LIKE '%,$root_member_id,%'");
		if($member_query->num_rows() > 0) {
			foreach($member_query->result() as $member_row) {
				if($member_row->introducer_parent_ref != '') {
					$arr = explode(',', $member_row->introducer_parent_ref);
					
					for($i=0; $i<sizeof($arr); $i++) {
						if($arr[$i] != '' AND $arr[$i] > 0) {
							if(isset($member_lists[$arr[$i]])) {
								$member_lists[$arr[$i]]['total_intro'] = ($member_lists[$arr[$i]]['total_intro'] + 1);
							}
						}
					}
				}
			}
		}
		
		$html = '';
		$query = $this->db->query("SELECT member_id, username, level, special_level FROM sw_members WHERE introducer = ?", array($username));
		if($query->num_rows() > 0) {
			$html .= '<ul class="nested active" data-switch="1">';
			foreach($query->result() as $row) {
				$highest_level = (($row->special_level > $row->level) ? $row->special_level : $row->level);
				
				switch($highest_level){
					case 1 : $ranking = $this->lang->line('level_1'); break;
					case 2 : $ranking = $this->lang->line('level_2'); break;
					case 3 : $ranking = $this->lang->line('level_3'); break;
					case 4 : $ranking = $this->lang->line('level_4'); break;
					case 5 : $ranking = $this->lang->line('level_5'); break;
					case 6 : $ranking = $this->lang->line('level_6'); break;
					case 7 : $ranking = $this->lang->line('level_7'); break;
					case 8 : $ranking = $this->lang->line('level_8'); break;
					case 9 : $ranking = $this->lang->line('level_9'); break;
					case 10 : $ranking = $this->lang->line('level_10'); break;
					case 11 : $ranking = $this->lang->line('level_11'); break;
					case 12 : $ranking = $this->lang->line('level_12'); break;
					case 13 : $ranking = $this->lang->line('level_13'); break;
					case 14 : $ranking = $this->lang->line('level_14'); break;
					default: $ranking = $this->lang->line('level_0'); break;
				}
				if($member_lists[$row->member_id]['total_intro'] > 0) {
					$html .= '<li><span class="caret" id="ht-' . $row->member_id . '" onclick="get_downline(' . $row->member_id . ', \'' . $row->username . '\')" data-value="0">' . $row->username . ' ('.$ranking.')</span></li>';
				}
				else {
					$html .= '<li>' . $row->username . ' ('.$ranking.')</li>';
				}
			}
			
			$html .= '</ul>';
		}	
		
		return $html;
    }
	
	function member_get_sales()
	{
		if($_POST) {
			$search_date = trim($this->input->post('search_date', TRUE));
			$start_date = strtotime($search_date . ' 00:00:00');
			$end_date = strtotime($search_date . ' 23:59:59');
			
			$query_origin = $this->db->query("SELECT SUM(b.package_price) AS total FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%' AND a.registered_date >= ? AND a.registered_date <= ?", array($start_date, $end_date))->row();
			$query_reinvest = $this->db->query("SELECT SUM(c.package_price) AS total FROM sw_members a, sw_member_reinvest b, sw_packages c WHERE ((a.member_id = b.member_id) AND (b.reinvest_package_type = c.package_id)) AND a.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%' AND b.reinvest_package_date >= ? AND b.reinvest_package_date <= ?", array($start_date, $end_date))->row();
			$rs['total'] = ($query_origin->total + $query_reinvest->total);
		}
		else {
			$start_date = strtotime(date('Y-m-d') . ' 00:00:00');
			$end_date = strtotime(date('Y-m-d') . ' 23:59:59');
			
			$query_origin = $this->db->query("SELECT SUM(b.package_price) AS total FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%' AND a.registered_date >= ? AND a.registered_date <= ?", array($start_date, $end_date))->row();
			$query_reinvest = $this->db->query("SELECT SUM(c.package_price) AS total FROM sw_members a, sw_member_reinvest b, sw_packages c WHERE ((a.member_id = b.member_id) AND (b.reinvest_package_type = c.package_id)) AND a.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%' AND b.reinvest_package_date >= ? AND b.reinvest_package_date <= ?", array($start_date, $end_date))->row();
			$rs['total'] = ($query_origin->total + $query_reinvest->total);
		}
		
	    return $rs;
	}
	
	function get_member_unread_message()
	{
		$query = $this->db->query("SELECT COUNT(message_id) AS total FROM sw_member_messages WHERE member_id = ? AND member_read = ?", array($this->session->userdata('member_id'), 1))->row();
		$total = $query->total;
		
		return $total;
	}
	
	function get_member_total_convert($type = NULL)
    {
		if($type == 3) {
			$query_pending = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 0))->row();
			$query_success = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
			$query_cancel = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 2))->row();
		}
		else {
			$query_pending = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 0))->row();
			$query_success = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
			$query_cancel = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 2))->row();
		}
		
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }
	
	function member_convert()
    {
		$this->lang->load('account_general', get_language());
	
		$wallet_type = trim($this->input->post('wallet_type', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => (($wallet_type > 0 && $wallet_type < 5) ? $wallet_type : 1),
			'from_member_id' => $this->session->userdata('member_id'),
			'from_member_username' => $this->session->userdata('member_username'),
			'credit_amount' => $transaction_amount,
			'status' => 1,
			'transaction_date' => time()
		);
		
		$setting = $this->member_model->get_setting_rates();
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('convert_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/", $transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('convert_invalid_amount_message');
    	}
		else if($transaction_amount < $setting['min_convert']) {
			return str_replace('_MIN_', number_format($setting['min_convert'], 2, '.', ''), $this->lang->line('convert_min_request_message'));
		}
		
		if($wallet_type > 0 && $wallet_type < 4) {
			$today_start = strtotime(date('Y-m-d 00:00:00'));
			$today_end = strtotime(date('Y-m-d 23:59:59'));
			$final_amount = $transaction_amount;
			$query = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_converts WHERE from_member_id = ? AND transaction_type >= ? AND transaction_type <= ? AND status < ? AND transaction_date >= ? AND transaction_date <= ?", array($DBdata['from_member_id'], 1, 3, 2, $today_start, $today_end));
			if($query->num_rows() > 0) {
				$row = $query->row();
				$final_amount = ($final_amount + $row->total);
			}
			
			if($final_amount > $setting['max_convert_per_day']) {
				return str_replace('_MAX_', $setting['max_convert_per_day'], $this->lang->line('convert_max_request_message'));
			}
		}
		
		if($security_password == '') {
    		return $this->lang->line('convert_security_password_must_fill_in_message');
    	}
		
		#Check for security password
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? LIMIT 1", array($DBdata['from_member_id'], $encrypted_password));
		if($query->num_rows() == 0) {
			return $this->lang->line('convert_invalid_security_password_message');
		}
		
		#Check for available balance
		if($wallet_type == 4) {
			$query = $this->db->query("SELECT v_unit2, v_unit4 FROM sw_member_wallets WHERE v_unit2 >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit2;
				$DBdata['to_credit_balance'] = ($row->v_unit2 - $transaction_amount);
				$DBdata['debit_amount'] = $transaction_amount;
				$DBdata['from_debit_balance'] = $row->v_unit4;
				$DBdata['to_debit_balance'] = ($row->v_unit4 + $DBdata['debit_amount']);
			}
			else {
				return $this->lang->line('convert_insufficient_amount_message');
			}
		}
		else if($wallet_type == 3) {
			$query = $this->db->query("SELECT a.level, a.special_level, b.v_unit, b.v_unit5 FROM sw_members a, sw_member_wallets b WHERE (a.member_id = b.member_id) AND b.v_unit >= ? AND b.member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$highest_level = (($row->special_level > $row->level) ? $row->special_level : $row->level);
				$tmp_amount = ($transaction_amount / 10);
				$multiplier = 5;
				
				switch($highest_level) {
					case 1:
					case 2: $multiplier = 6; break;
					case 3:
					case 4: $multiplier = 7; break;
					case 5:
					case 6: $multiplier = 8; break;
					case 7:
					case 8: $multiplier = 9; break;
				}
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
				$DBdata['debit_amount'] = ($tmp_amount * $multiplier);
				$DBdata['from_debit_balance'] = $row->v_unit5;
				$DBdata['to_debit_balance'] = ($row->v_unit5 + $DBdata['debit_amount']);
			}
			else {
				return $this->lang->line('convert_insufficient_amount_message');
			}
		}
		else if($wallet_type == 2) {
			$query = $this->db->query("SELECT v_unit, v_unit4 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();
				
				$tmp_amount = ($transaction_amount / 4);
				$multiplier = 3;
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
				$DBdata['debit_amount'] = ($tmp_amount * $multiplier);
				$DBdata['from_debit_balance'] = $row->v_unit4;
				$DBdata['to_debit_balance'] = ($row->v_unit4 + $DBdata['debit_amount']);
			}
			else {
				return $this->lang->line('convert_insufficient_amount_message');
			}
		}
		else {
			$query = $this->db->query("SELECT v_unit, v_unit2 FROM sw_member_wallets WHERE v_unit >= ? AND member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['from_member_id']));
			if($query->num_rows() > 0) {
				$row = $query->row();
				
				$DBdata['from_credit_balance'] = $row->v_unit;
				$DBdata['to_credit_balance'] = ($row->v_unit - $transaction_amount);
				$DBdata['debit_amount'] = ($transaction_amount / 2);
				$DBdata['from_debit_balance'] = $row->v_unit2;
				$DBdata['to_debit_balance'] = ($row->v_unit2 + $DBdata['debit_amount']);
			}
			else {
				return $this->lang->line('convert_insufficient_amount_message');
			}
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_converts', $DBdata);
		
		if($wallet_type == 4) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit2 = (v_unit2 - ?), v_unit4 = (v_unit4 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['debit_amount'], $DBdata['from_member_id']));
		}
		else if($wallet_type == 3) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?), v_unit5 = (v_unit5 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['debit_amount'], $DBdata['from_member_id']));
		}
		else if($wallet_type == 2) {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?), v_unit4 = (v_unit4 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['debit_amount'], $DBdata['from_member_id']));
		}
		else {
			$this->db->query("UPDATE sw_member_wallets SET v_unit = (v_unit - ?), v_unit2 = (v_unit2 + ?) WHERE member_id = ? LIMIT 1", array($DBdata['credit_amount'], $DBdata['debit_amount'], $DBdata['from_member_id']));
		}
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_CONVERT, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function get_member_group_sales() 
	{
		$parent_id = $this->session->userdata('member_id');
		
		$query_1 = $this->db->query("SELECT SUM(a.package_price) AS total FROM sw_packages a, sw_members b WHERE (a.package_id = b.package_type) AND b.member_type = 2 AND (b.introducer_parent_ref LIKE '%,$parent_id,%' OR b.member_id = $parent_id)")->row_array();
		$total_1 = (($query_1['total'] > 0 && $query_1['total'] != '') ? $query_1['total'] : 0);
		
		//$query_2 = $this->db->query("SELECT SUM(a.package_price) AS total FROM sw_packages a, sw_member_reinvest b, sw_members c WHERE ((a.package_id = b.reinvest_package_type) AND (b.member_id = c.member_id)) AND (c.introducer_parent_ref LIKE '%,$parent_id,%' OR c.member_id = $parent_id)")->row_array();
		//$total_2 = (($query_2['total'] > 0 && $query_2['total'] != '') ? $query_2['total'] : 0);
		$total_2 = 0;
		$total = ($total_1 + $total_2);
		
		return $total;
	}
	
	function get_currency_rate($nationality = NULL) 
	{
		$currency_id = 1;
		$currency_rate = 0;
		
		switch($nationality) {
			case 'US': $currency_id = 1; break;
			case 'CN': $currency_id = 2; break;
			case 'MY': $currency_id = 3; break;
			case 'ID': $currency_id = 4; break;
			case 'USDT': $currency_id = 5; break;
			case 'TH': $currency_id = 6; break;
			case 'VN': $currency_id = 7; break;
			case 'SG': $currency_id = 8; break;
			default: $currency_id = 1; break;
		}
		
		$query = $this->db->query("SELECT t_currency_rate FROM sw_currencies WHERE currency_id = ? LIMIT 1", array($currency_id));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$currency_rate = $row->t_currency_rate;
		}
		
		return $currency_rate;
	}

	function get_member_total_topup_by_all()
    {
		$query_pending = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE to_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 0))->row();
		$query_success = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE to_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE to_member_id = ? AND status = ?", array($this->session->userdata('member_id'), 2))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }
	
	function get_member_total_topup_by_method($type = NULL)
    {
		$query_pending = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE payment_method = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 0))->row();
		$query_success = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE payment_method = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(debit_amount) AS total FROM sw_member_topup WHERE payment_method = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 2))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }

    function get_member_total_topup_winloss_by_method($type = NULL)
    {
		// $query_pending = $this->db->query("SELECT SUM(winloss_amount) AS total FROM sw_member_topup WHERE payment_method = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 0))->row();
		// $query_success = $this->db->query("SELECT SUM(winloss_amount) AS total FROM sw_member_topup WHERE payment_method = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 1))->row();
		// $query_cancel = $this->db->query("SELECT SUM(winloss_amount) AS total FROM sw_member_topup WHERE payment_method = ? AND to_member_id = ? AND status = ?", array($type, $this->session->userdata('member_id'), 2))->row();
		$arr = array('pending' => 0, 'success' => 0, 'cancel' => 0);
		
	    return $arr;
    }

     function get_member_total_register_by_all()
    {
		$query_pending = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_placement WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 0,1))->row();
		$query_success = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_placement WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 1,1))->row();
		$query_cancel = $this->db->query("SELECT SUM(credit_amount) AS total FROM sw_member_placement WHERE from_member_id = ? AND status = ? AND transaction_type = ?", array($this->session->userdata('member_id'), 2,1))->row();
		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total);
		
	    return $arr;
    }
	
	function member_topup_offline()
    {
		$this->lang->load('account_general', get_language());
	
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
		$setting = $this->member_model->get_setting_rates();
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => 1,
			'payment_method' => 1,
			'to_member_id' => $this->session->userdata('member_id'),
			'to_member_username' => $this->session->userdata('member_username'),
			'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)),
			'debit_amount' => $transaction_amount,
			'status' => 0,
			'transaction_date' => time()
		);
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('topup_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('topup_invalid_amount_message');
    	}
		else if ($DBdata['debit_amount'] < $setting['min_topup']) {
			return str_replace('%f', $setting['min_topup'], $this->lang->line('topup_min_amount_message'));
    	}else if($DBdata['bank_name'] == '') {
    		return $this->lang->line('registration_bank_name_must_fill_in_message');
		}
		else if($DBdata['bank_account_no'] == '') {
    		return $this->lang->line('registration_bank_account_no_must_fill_in_message');
		}
		else if($DBdata['account_holder_name'] == '') {
    		return $this->lang->line('registration_account_holder_name_must_fill_in_message');
		}
		else if($DBdata['bank_address'] == '') {
    		return $this->lang->line('registration_bank_address_must_fill_in_message');
		}
		
		#Get currency
		$query = $this->db->query("SELECT nationality FROM sw_members WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			switch($row->nationality) {
				case 'US': $DBdata['transaction_type'] = 1; break;
				case 'CN': $DBdata['transaction_type'] = 2; break;
				case 'MY': $DBdata['transaction_type'] = 3; break;
				case 'ID': $DBdata['transaction_type'] = 4; break;
				case 'USDT': $DBdata['transaction_type'] = 5; break;
				case 'TH': $DBdata['transaction_type'] = 6; break;
				case 'VN': $DBdata['transaction_type'] = 7; break;
				case 'SG': $DBdata['transaction_type'] = 8; break;
				default: $DBdata['transaction_type'] = 1; break;
			}
		}
		else {
			return $this->lang->line('topup_invalid_currency_message');
		}
		
		#Get currency
		$query = $this->db->query("SELECT t_currency_rate FROM sw_currencies WHERE currency_id = ? LIMIT 1", array($DBdata['transaction_type']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['currency_rate'] = $row->t_currency_rate;
			$DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $DBdata['currency_rate']);
		}
		else {
			return $this->lang->line('topup_invalid_currency_message');
		}
		
		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
		if(isset($_FILES['bank_in_slip']['size']) AND $_FILES['bank_in_slip']['size'] > 0) 
		{
			if( ! in_array($_FILES['bank_in_slip']['type'], $allowed_types)) 
			{
				return $this->lang->line('topup_invalid_bank_in_slip_message');
			}
			else
			{
				$DBdata['bank_in_slip'] = md5($this->session->userdata('member_id') . 'offline' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		else {
			return $this->lang->line('topup_bank_in_slip_must_fill_in_message');
		}
		
		if($security_password == '') {
    		return $this->lang->line('topup_security_password_must_fill_in_message');
    	}
		
		#Check for security password availbility
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? AND active = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password, 1));
		if($query->num_rows() == 0) {
			return $this->lang->line('topup_invalid_security_password_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_topup', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_TOPUP, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			if(isset($_FILES['bank_in_slip']['size']) AND $_FILES['bank_in_slip']['size'] > 0)
			{
				$this->load->library('image_lib');
				$config['source_image'] = $_FILES['bank_in_slip']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'banks/' .$DBdata['bank_in_slip'];
				$config['maintain_ratio'] = TRUE;
				// $config['width'] = 600;
				// $config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function member_topup_usdt()
    {
		$this->lang->load('account_general', get_language());
	
		$transaction_amount = trim($this->input->post('transaction_amount', TRUE));
		$security_password = trim($this->input->post('security_password', TRUE));
		
		$setting = $this->member_model->get_setting_rates();
		
        #Populate submitted data
		$DBdata = array(
			'transaction_type' => 5,
			'payment_method' => 2,
			'to_member_id' => $this->session->userdata('member_id'),
			'to_member_username' => $this->session->userdata('member_username'),
			'debit_amount' => $transaction_amount,
			'status' => 0,
			'transaction_date' => time()
		);
		
		#Data validation
		if($transaction_amount == '') {
    		return $this->lang->line('topup_amount_must_fill_in_message');
    	} 
		else if ( ! preg_match("/^([0-9]+)$/",$transaction_amount) || $transaction_amount <= 0) {
			return $this->lang->line('topup_invalid_amount_message');
    	}
		else if ($DBdata['debit_amount'] < $setting['min_topup']) {
			return str_replace('%f', $setting['min_topup'], $this->lang->line('topup_min_amount_message'));
    	}
		
		#Get currency
		$query = $this->db->query("SELECT t_currency_rate FROM sw_currencies WHERE currency_id = ? LIMIT 1", array($DBdata['transaction_type']));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$DBdata['currency_rate'] = $row->t_currency_rate;
			$DBdata['transaction_amount'] = ($DBdata['debit_amount'] * $DBdata['currency_rate']);
		}
		else {
			return $this->lang->line('topup_invalid_currency_message');
		}
		
		$allowed_types = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png');
		if(isset($_FILES['bank_in_slip']['size']) AND $_FILES['bank_in_slip']['size'] > 0) 
		{
			if( ! in_array($_FILES['bank_in_slip']['type'], $allowed_types)) 
			{
				return $this->lang->line('topup_invalid_bank_in_slip_message');
			}
			else
			{
				$DBdata['bank_in_slip'] = md5($this->session->userdata('member_id') . 'offline' . $this->config->item('encryption_key') . time()) . '.jpg';
			}
		}
		else {
			return $this->lang->line('topup_bank_in_slip_must_fill_in_message');
		}
		
		if($security_password == '') {
    		return $this->lang->line('topup_security_password_must_fill_in_message');
    	}
		
		#Check for security password availbility
		$encrypted_password = sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key')))));
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE member_id = ? AND security_password = ? AND active = ? LIMIT 1", array($this->session->userdata('member_id'), $encrypted_password, 1));
		if($query->num_rows() == 0) {
			return $this->lang->line('topup_invalid_security_password_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_member_topup', $DBdata);
		
		$this->insert_member_log($this->session->userdata('member_id'), LOG_TOPUP, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			if(isset($_FILES['bank_in_slip']['size']) AND $_FILES['bank_in_slip']['size'] > 0)
			{
				$this->load->library('image_lib');
				$config['source_image'] = $_FILES['bank_in_slip']['tmp_name'];
				$config['new_image'] = UPLOAD_MEDIA_PHYSICAL_PATH . 'banks/' .$DBdata['bank_in_slip'];
				$config['maintain_ratio'] = TRUE;
				// $config['width'] = 600;
				// $config['height'] = 600;
				$this->image_lib->initialize($config); 
				$this->image_lib->resize();
				$this->image_lib->clear();
			}
			
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
    }
	
	function member_reset_password()
	{
		$username = trim($this->input->post('username', TRUE));
		$email = trim($this->input->post('email', TRUE));
		
		if ($username == '') {
			echo $this->lang->line('login_enter_username_message');
			exit();
		} else if ($email == '') {
			echo $this->lang->line('login_enter_email_message');
			exit();
		}
		
		#Check for username availbility
		$query = $this->db->query("SELECT member_id, email FROM sw_members WHERE username = ? AND email = ? LIMIT 1", array($username, $email));
		if($query->num_rows() > 0) {
			$row = $query->row();
			
			$rand_pass = rand(100000, 999999);
			$DBdata = array(
				'password_origin' => $rand_pass,
				'password' => sha1(md5(sha1(md5($rand_pass)) . sha1(md5($this->config->item('encryption_key'))))),
			);	
			
			$this->db->trans_start();
		
			$this->db->where('member_id', $row->member_id);
			$this->db->limit(1);
			$this->db->update('sw_members', $DBdata);
			
			$this->insert_member_log($row->member_id, LOG_RESET_PASSWORD, json_encode($DBdata));
			
			$this->db->trans_complete();
			
			if ($this->db->trans_status() === TRUE) {
				#Send an activation email to member 
				$this->load->config('email');
				$this->load->library('email');

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

				$e_body = str_replace(array('%f', '%s'), array($row->username, $rand_pass), $this->lang->line('forgot_password_email_body'));

				// if(substr($row->email, -6, 6) == 'qq.com') {
					// $headers = "From: $form \r\n";
					// $headers .= "MIME-Version: 1.0\r\n";
					// $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
					// $result = mail($row->email, $e_subject, $e_body, $headers);
				// }
				// else {
					$result = $this->email
							->from($form)
							->to($row->email)
							->subject($e_subject)
							->message($e_body)
							->send();
				// }
				
				echo STATUS_200;
			}
			else {
				echo $this->lang->line('login_reset_failed');
			}
		}
		else {
			echo $this->lang->line('login_invalid_username_or_email');
		}
	}
	
	function get_member_details_by_username($username = NULL)
    {
		$query = $this->db->query("SELECT * FROM sw_members WHERE username = ? LIMIT 1", array($username))->row_array();
	    
	    return $query;
    }
	
	function register_member_without_package()
	{
		$this->lang->load('account_general', get_language());
	    
		$password = trim($this->input->post('password', TRUE));
		$confirm_password = trim($this->input->post('confirm_password', TRUE));
		$security_password = $password;
		$confirm_security_password = $confirm_password;
		
        #Populate submitted data
	    $DBdata = array(
			'username' => strtolower(trim($this->input->post('username', TRUE))),
			'password_origin' => $password,
			'password' => sha1(md5(sha1(md5($password)) . sha1(md5($this->config->item('encryption_key'))))),
			'security_password_origin' => $security_password,
			'security_password' => sha1(md5(sha1(md5($security_password)) . sha1(md5($this->config->item('encryption_key'))))),
			'full_name' => '',//trim($this->input->post('full_name', TRUE)),
			'dob' => date('Y-m-d', time()),
			'gender' => 1,
			'id_type' => 1,
			'id_no' => '',
			'email' => trim($this->input->post('email', TRUE)),
			'mobile_no' => '',//trim($this->input->post('mobile_no', TRUE)),
			'nationality' => 'VN',
			'country' => 'VN',
			'bank_country' => 'VN',
			'origin_package_type' => 0,
			'package_type' => 0,
			'contract_start_date' => time(),
			'contract_expiry_date' => strtotime('+' . TENURE_CONTRACT . ' days', time()),
			'active' => 1,
			'member_type' => 2,
			'introducer' => trim($this->input->post('introducer', TRUE)),
			'allowed_withdraw' => 1,
			'unlimited_withdraw' => 0,
			'allowed_transfer' => 1,
			'allowed_convert' => 1,
			'allowed_topup' => 1,
			'allowed_game' => 1,
			'insurance_date' => strtotime('+1 month', time()),
			'registered_by' => 'Self',
			'registered_date' => time()
    	);
		
		#Data validation
		if($DBdata['username'] == '') {
    		return $this->lang->line('registration_username_must_fill_in_message');
		}
		else if( ! preg_match('/^[a-zA-Z0-9_]{6,16}$/', $DBdata['username'])) {
			return $this->lang->line('registration_invalid_username_format_message');
		}
		
		#Check for username availbility
		$query = $this->db->query("SELECT member_id FROM sw_members WHERE username = ? LIMIT 1", array($DBdata['username']));
		if($query->num_rows() > 0) {
			return $this->lang->line('registration_username_unavailable_message');
		}
		
		if($password == '') {
    		return $this->lang->line('registration_password_must_fill_in_message');
		} 
		else if( ! preg_match("/^[A-Za-z0-9!#$^*]{6,15}$/", $password)) {
			return $this->lang->line('registration_invalid_password_format_message');
		} 
		else if ($password != $confirm_password) {
			return $this->lang->line('registration_confirm_password_not_match_message');
		} 
		else if($security_password == '') {
    		return $this->lang->line('registration_security_password_must_fill_in_message');
		} 
		else if( ! preg_match("/^[A-Za-z0-9!#$^*]{6,15}$/", $security_password)) {
			return $this->lang->line('registration_invalid_security_password_format_message');
		} 
		else if ($security_password != $confirm_security_password) {
			return $this->lang->line('registration_confirm_security_password_not_match_message');	
		}
		// else if($DBdata['full_name'] == '') {
    		// return $this->lang->line('registration_full_name_must_fill_in_message');
		// }
		// else if($DBdata['id_no'] == '') {
    		// return $this->lang->line('registration_id_no_must_fill_in_message');
		// }
		// else if($DBdata['mobile_no'] == '') {
    		// return $this->lang->line('registration_mobile_no_must_fill_in_message');
		// }
		/*
		else if($DBdata['email'] == '') {
    		return $this->lang->line('registration_email_must_fill_in_message');
		} 
		*/
		else if($DBdata['email'] != '') {
			if (!isEmail($DBdata['email'])) {
	    		return $this->lang->line('registration_invalid_email_message');
			}
			
			#Check for email availbility
			$query = $this->db->query("SELECT member_id FROM sw_members WHERE email = ? LIMIT 1", array($DBdata['email']));
			if($query->num_rows() > 0) {
				return $this->lang->line('registration_email_unavailable_message');
			}
		}
		else if($DBdata['introducer'] == '') {
			return $this->lang->line('registration_introducer_must_fill_in_message');
		}
		
		#Check for introducer availbility
		$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();
			
			if(empty($row->introducer_parent_ref)) {
				$DBdata['introducer_parent_ref'] = ',' . $row->member_id . ',';
			}
			else {
				$DBdata['introducer_parent_ref'] = $row->introducer_parent_ref . $row->member_id . ',';
			}
		}
		else {
			return $this->lang->line('registration_introducer_unavailable_message');
		}
		
		$this->db->trans_start();
		
		$this->db->insert('sw_members', $DBdata);
		$db_data['member_id'] = $this->db->insert_id();
		
		$this->db->insert('sw_member_wallets', $db_data);
		
		$this->insert_member_log(0, LOG_REGISTRATION, json_encode($DBdata));
		
		$this->db->trans_complete();
		
		$rs = $this->db->trans_status();
		
		if($rs) {
			//CALL API - create account asiagaming1688
			$response = $this->api_create_account(1, $DBdata['username'], $DBdata['password_origin'], 0);
			$result_array = json_decode($response, TRUE);
			if(isset($result_array['status']) && $result_array['status'] == 0) {
				$this->db->query("UPDATE sw_members SET casino_plyid_1 = ? WHERE member_id = ? LIMIT 1", array($result_array['player_id'], $db_data['member_id']));
			}
			
			//CALL API - create account luckyb3t
			$response_2 = $this->api_create_account(2, $DBdata['username'], $DBdata['password_origin'], 0);
			$result_array_2 = json_decode($response_2, TRUE);
			if(isset($result_array_2['status']) && $result_array_2['status'] == 0) {
				$this->db->query("UPDATE sw_members SET casino_plyid_2 = ? WHERE member_id = ? LIMIT 1", array($result_array_2['player_id'], $db_data['member_id']));
			}
			
			return STATUS_200;
		}
		else {
			return $this->lang->line('unknown_error');
		}
	}
	
	public function get_member_total_bet(){
		$query_pending = $this->db->query("SELECT SUM(bet_amount) AS total FROM sw_transaction_report WHERE player_id = ? AND status = ?", array($this->session->userdata('member_id'), 0))->row();
		$query_success = $this->db->query("SELECT SUM(bet_amount) AS total FROM sw_transaction_report WHERE player_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();
		$query_cancel = $this->db->query("SELECT SUM(bet_amount) AS total FROM sw_transaction_report WHERE player_id = ? AND status = ?", array($this->session->userdata('member_id'), 2))->row();
		$query_winloss = $this->db->query("SELECT SUM(win_loss) AS total FROM sw_transaction_report WHERE player_id = ? AND status = ?", array($this->session->userdata('member_id'), 1))->row();

		$arr = array('pending' => $query_pending->total, 'success' => $query_success->total, 'cancel' => $query_cancel->total, 'winloss' => $query_winloss->total);
	    return $arr;
	}
	
	public function get_player_turnover($type = NULL,$player_id = NULL){
		$json = array(
			'status' => 1,
		);
		if($type == "xi8bet"){
			$db_secondary = $this->load->database('xi8bet', TRUE);
			$query = $db_secondary->query("SELECT player_id, is_turnover FROM player WHERE player_id = ? limit 1", array($player_id));
			if($query->num_rows() > 0) {
				$playerData = $query->row_array();
				if($playerData['is_turnover']){
					$query = $db_secondary->query("SELECT modified_date FROM credit_adjustment WHERE player_id = ? AND modified_by = ? ORDER BY modified_date DESC limit 1", array($player_id,888));
					if($query->num_rows() > 0) {
						$creditData = $query->row_array();
						$query = $db_secondary->query("SELECT SUM(br_amount) AS total FROM bet_record WHERE br_userid = ? AND br_result IN (1,2) AND br_bet_time_bdt > ?", array($player_id,$creditData['modified_date']));
						$query2 = $db_secondary->query("SELECT br_id FROM bet_record WHERE br_userid = ? AND br_result IN (1,2) AND br_bet_time_bdt > ?", array($player_id,$creditData['modified_date']));
						if($query->num_rows() > 0) {
							$turnoverData = $query->row_array();
							if(!empty($turnoverData['total'])){
								$json = array(
									'status' => 0,
									'turnover' => $turnoverData['total'],
									'counter' => $query2->num_rows()
								);
							}else{
								$json = array(
									'status' => 0,
									'turnover' => 0,
									'counter' => 0,
								);
							}
						}
					}
				}else{
					$json = array(
						'status' => 0,
						'turnover' => 0,
						'counter' => 0,
					);
				}
			}						
		}else{
			$db_secondary = $this->load->database('novas365', TRUE);
			$query = $db_secondary->query("SELECT player_id, is_turnover FROM player WHERE player_id = ? limit 1", array($player_id));
			if($query->num_rows() > 0) {
				$playerData = $query->row_array();
				if($playerData['is_turnover']){
					$query = $db_secondary->query("SELECT modified_date FROM credit_adjustment WHERE player_id = ? AND modified_by = ? ORDER BY modified_date DESC limit 1", array($player_id,888));
					if($query->num_rows() > 0) {
						$creditData = $query->row_array();
						$query = $db_secondary->query("SELECT SUM(br_amount) AS total FROM bet_record WHERE br_userid = ? AND br_result IN (1,2) AND br_bet_time_bdt > ?", array($player_id,$creditData['modified_date']));
						$query2 = $db_secondary->query("SELECT br_id FROM bet_record WHERE br_userid = ? AND br_result IN (1,2) AND br_bet_time_bdt > ?", array($player_id,$creditData['modified_date']));
						if($query->num_rows() > 0) {
							$turnoverData = $query->row_array();
							if(!empty($turnoverData['total'])){
								$json = array(
									'status' => 0,
									'turnover' => $turnoverData['total'],
									'counter' => $query2->num_rows()
								);
							}else{
								$json = array(
									'status' => 0,
									'turnover' => 0,
									'counter' => 0,
								);
							}
						}
					}
				}else{
					$json = array(
						'status' => 0,
						'turnover' => 0,
						'counter' => 0,
					);
				}
			}
		}

		return $json;
	}

	public function get_xi8bet_rolling_setting(){
		$query_dg = $this->db->query("SELECT SUM(bet_amount) AS total FROM sw_transaction_report WHERE player_id = ? AND status = ? AND game_provider_code = ?  AND win_loss != ?", array($this->session->userdata('member_id'), 1,"XBDG",0.00))->row();
		$query_sa = $this->db->query("SELECT SUM(bet_amount) AS total FROM sw_transaction_report WHERE player_id = ? AND status = ? AND game_provider_code = ?  AND win_loss != ?", array($this->session->userdata('member_id'), 1,"XBSA",0.00))->row();
		$arr = array('DG' => $query_dg->total, 'SA' => $query_sa->total);
	    return $arr;
	}
	
	public function get_pending_withdrawal($type = NULL)
    {
        $query = $this->db->query("SELECT * FROM sw_member_withdraw WHERE from_member_id = ? AND status = ? AND transaction_type = ? ORDER BY member_transaction_id ASC",array($this->session->userdata('member_id'),0,$type));
	    return $query;
    }

    public function member_withdraw_cancel(){
        exit;
    	$this->lang->load('account_general', get_language());
    	$transaction_id = trim($this->input->post('transaction_id', TRUE));
    	$status = 2;

    	$DBdata = array(
			'status' => $status
    	);
    	
    	if($transaction_id == '') {
    		return $this->lang->line('withdrawal_cancel_fail_message');
    	}

    	$query = $this->db->query("SELECT member_transaction_id, from_member_id, credit_amount, charges FROM sw_member_withdraw WHERE member_transaction_id = ? AND status = ? AND from_member_id = ? LIMIT 1", array($transaction_id, 0, $this->session->userdata('member_id')));
    	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_id' => $this->session->userdata('member_id'),
				'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_member_log($this->session->userdata('member_id'), LOG_WITHDRAWAL_CANCEL, json_encode($db_data));
			$this->db->trans_complete();
			$rs = $this->db->trans_status();
			if($rs) {
				return STATUS_200;
			}else{
				return $this->lang->line('unknown_error');
			}
    	}else{
    		return $this->lang->line('withdrawal_cancel_fail_message');
    	}
    }

    public function get_count_total_all_downline_member(){
    	$total_query = $this->db->query("SELECT COUNT(member_id) AS total FROM sw_members WHERE introducer = ?", array($this->session->userdata('member_username')))->row();
	    $total = $total_query->total;	 
		return $total;
    }
	
	public function get_all_downline_company_token_sales(){
    	$total_query = $this->db->query("SELECT SUM(a.credit_amount) AS total FROM sw_member_placement a, sw_members b WHERE (a.from_member_id = b.member_id) AND a.transaction_type = ? AND (a.from_member_id = ? OR b.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%')", array(1, $this->session->userdata('member_id')))->row();
	    $total = $total_query->total;	 
		return $total;
    }
	
	public function get_all_downline_total_sales(){
    	$total_query = $this->db->query("SELECT SUM(b.package_price) AS total FROM sw_members a, sw_packages b WHERE (a.package_type = b.package_id) AND a.member_type = ? AND a.active = ? AND a.introducer_parent_ref LIKE '%," . $this->session->userdata('member_id') . ",%'", array(2, 1, $this->session->userdata('member_id')))->row();
	    $total = $total_query->total;	 
		return $total;
    }
	
	public function update_wallet()
	{
		$casino_plyid_2 = 0;
		$last_withdrawal_date = 0;
    	$v_unit6 = 0;
		$v_unit7 = 0;
		$v_unit8 = 0;
		
		$query = $this->db->query("SELECT casino_plyid_2 FROM sw_members WHERE member_id = ? LIMIT 1", array($this->session->userdata('member_id')));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$casino_plyid_2 = $row->casino_plyid_2;
		}
			
		//CALL API - get balance asiagaming1688
		$response = $this->api_get_balance(1, $this->session->userdata('member_username'));
		$result_array = json_decode($response, TRUE);
		if(isset($result_array['status']) && $result_array['status'] == 0) {
			$v_unit6 = $result_array['balance'];
		}
		
		//CALL API - get balance luckyb3t
		$response_2 = $this->api_get_balance(2, $this->session->userdata('member_username'));
		$result_array_2 = json_decode($response_2, TRUE);
		if(isset($result_array_2['status']) && $result_array_2['status'] == 0) {
			$v_unit7 = $result_array_2['balance'];
		}
		
		//get turnover luckyb3t
		$otherdb = $this->load->database('otherdb2', TRUE);
		
		$query = $otherdb->query("SELECT updated_date FROM bctp_withdrawals WHERE player_id = ? AND status = ? ORDER BY withdrawal_id DESC LIMIT 1", array($casino_plyid_2, 1));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$last_withdrawal_date = $row->updated_date;
		}
		
		//Calculate rolling
		$query = $otherdb->query("SELECT SUM(bet_amount) AS total FROM bctp_transaction_report WHERE player_id = ? AND payout_time > ? AND status = ? AND win_loss != ? AND game_code = ?", array($casino_plyid_2, $last_withdrawal_date, 1, 0, 'Baccarat'));
		if($query->num_rows() > 0) {
			$row = $query->row();
			$v_unit8 = (isset($row->total) ? $row->total : 0);
		}
		
		$this->db->trans_start();
	
		$this->db->query("UPDATE sw_member_wallets SET v_unit6 = ?, v_unit7 = ?, v_unit8 = ? WHERE member_id = ? LIMIT 1", array($v_unit6, $v_unit7, $v_unit8, $this->session->userdata('member_id')));
		
		$this->db->trans_complete();
		
		$json = array('v_unit6' => number_format($v_unit6, 2, '.', ','), 'v_unit7' => number_format($v_unit7, 2, '.', ','), 'v_unit8' => number_format($v_unit8, 2, '.', ','));
			
		return $json;
    }
	
	function api_create_account($platform = NULL, $username = NULL, $password = NULL, $package_type = NULL)
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		switch($package_type) {
			case 1: $player_type = 3; break;
			case 2: $player_type = 4; break;
			default: $player_type = 2; break;
		}
		
		$arr = array(
			"username" => $username,
			"password" => $password,
			"player_type" => $player_type,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'MemberRegisterDV',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"player" => array(
				"username" => $arr['username'],
				"password" => $arr['password'],
				"player_type" => $arr['player_type'],
			)
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_topup_credit($platform = NULL, $username = NULL, $amount = NULL, $remark = NULL)
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		$arr = array(
			"username" => $username,
			"amount" => $amount,
			"remark" => $remark,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'CreditBalance',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"amount" => $arr['amount'],
			"remark" => $arr['remark'],
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_get_balance($platform = NULL, $username = NULL) 
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		$arr = array(
			"username" => $username,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'GetBalanceDV',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
		);
		
		$response = $this->curl_json($url, $array_param);
				
		return $response;
	}
	
	function api_update_player_type($platform = NULL, $username = NULL, $package_type = NULL) 
	{
		$url = WHITELABEL_URL_1;
		$agent_id = WHITELABEL_AGENT_ID_1;
		$secret_key = WHITELABEL_SECRET_KEY_1;
		
		if($platform == 2) {
			$url = WHITELABEL_URL_2;
			$agent_id = WHITELABEL_AGENT_ID_2;
			$secret_key = WHITELABEL_SECRET_KEY_2;
		}
		
		switch($package_type) {
			case 1: $player_type = 3; break;
			case 2: $player_type = 4; break;
			default: $player_type = 2; break;
		}
		
		$arr = array(
			"username" => $username,
			"player_type" => $player_type,
		);
		
		$signature = md5($agent_id . implode('', $arr) . $secret_key);
		
		$array_param = array(
			"method" => 'UpdatePlayerType',
			"agentId" => $agent_id,
			"signature" => $signature,
			"syslang" => 1,
			"device" => 1,
			"username" => $arr['username'],
			"player_type" => $arr['player_type'],
		);
		
		$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;
	}
}