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

class Home extends CI_Controller {

	public function __construct(){
		parent::__construct();
	}


    public function index(){
        $user = $this->admin_m->get_empty_admin();
        if($user == 1){
            $this->login();
        }else{
            $this->create();
        }
    }

	public function login()
	{
		$data = array();
		$data['page_title'] = "Login";
        $data['page'] = "Login";
		$data['main_content'] = $this->load->view('admin/login', $data, TRUE);
		$this->load->view('admin/index',$data);
	}

	public function create(){
        $data = array();
        $data['page_title'] = "Registration";
        $data['page'] = "Login";
        $data['main_content'] = $this->load->view('create', $data, TRUE);
        $this->load->view('admin/index', $data);
    }
	
	
/**
  *** login action
**/ 
public function user_login()
{
	$sorry = !empty(lang("sorry"))?lang("sorry"):"sorry";
	$welcome = !empty(lang("welcome"))?lang("welcome"):"Welcome";
	$login_success = !empty(lang("login_success"))?lang("login_success"):"Login successfull";
	$not_approve = !empty(lang("account_not_approve"))?lang("account_not_approve"):"Your account is not approved";
	$invalid = !empty(lang("invalid_login"))?lang("invalid_login"):"Login invalid";

	$this->form_validation->set_rules('email', 'Email / Username', 'trim|required|xss_clean');		
	$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|min_length[3]');
	if ($this->form_validation->run() == FALSE) {
		$msg = '<div class="alert alert-danger alert-dismissible">
		<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
		<strong>Sorry ! </strong> '.validation_errors().'
		</div>';
		echo json_encode(array('st' => 0, 'msg'=> $msg,));
	}else{	
		$setting = get_setting();

		if(isset($setting['is_recaptcha']) && $setting['is_recaptcha']==1 && !empty($setting['g_site_key'])):
			if($this->recaptcha()==FALSE){
				$msg = '<div class="alert alert-danger alert-dismissible">
				<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
				<strong>Sorry  ! </strong> Robot verification Failed
				</div>';
				echo json_encode(array('st' => 0, 'msg'=> $msg));
				exit();
			}
		endif;
		// get settings 
		

		$email = $this->input->post('email',TRUE);
		$password = $this->input->post('password',TRUE);
		if(is_numeric($email)){
			$is_customer = 1;
			$query = $this->admin_m->check_customer_login($email,$password); //check email / user name and password
		}else{
			$is_customer = 0;
			$query = $this->admin_m->login_info_check($email,$password);
		}
		
		if($query){
			$s_array= array();
			foreach($query as $row):
				if($is_customer==0):
					$s_array = array(
						'id' => $row->id,
						'username' => $row->username,
						'email' => $row->email,
						'user_type' => $row->user_type,
						'is_active' => $row->is_active,
						'is_verify' => $row->is_verify,
						'account_type' => $row->account_type,
						'user_login' => TRUE,
					);

					if($row->is_active == 1):
						$url = base_url('admin/dashboard');
						
						$this->session->set_userdata($s_array);
						$data =array(
							'login_time' => d_time()
						);
						
						$this->admin_m->update($data,$row->id,'users');
						
						if($row->user_type==0):
							// check features availability
							$this->insert_features($row->id);
						endif;

						//Qr code
						$this->qr_code($row->username);


						$msg = '<div class="alert alert-success alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>'.$welcome.' ! </strong> '.$login_success.'  <i class="fa fa-smile-o"></i>

						</div>';
						echo json_encode(array('st' => 1, 'msg'=> $msg, 'url'=> $url));
						exit();
					else:
						$msg = '<div class="alert alert-danger alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>'.$sorry.' </strong> '.$not_approve.'  <i class="fa fa-frown-o"></i>
						</div>';
						echo json_encode(array('st' => 2, 'msg'=> $msg));
						exit();
					endif;
				else: //is_customer else
					$s_array = array(
						'customer_id' => $row->id,
						'customer_name' => $row->name,
						'phone' => $row->phone,
						'is_customer' => TRUE,
					);

						$this->session->set_userdata($s_array);
						$msg = '<div class="alert alert-success alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>'.$welcome.' ! </strong> '.$login_success.'  <i class="fa fa-smile-o"></i>

						</div>';
						$url = base_url('service/order_list');
						echo json_encode(array('st' => 1, 'msg'=> $msg,'url'=>$url));
						exit();
				endif;//is_customer else
				
			endforeach;

		}else{
			
			
			$msg = '<div class="alert alert-danger alert-dismissible">
			<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
			<strong>'.$sorry.'</strong> '.$invalid.' <i class="fa fa-frown-o" ></i>
			</div>';
			echo json_encode(array('st' => 3, 'msg'=> $msg));
		} 
			//end login_info_check 

	} 
		//end validation 
}




	function check_all($dir){
	   $check = $this->admin_m->check_files($dir);
	   if($check==true):
	   	echo 'done';
	   else:
	   	echo 'not found';
	   endif;

	}

public function recaptcha(){
	$setting =  get_setting();
	$recaptchaResponse = trim($this->input->post('g-recaptcha-response'));
    $userIp=$this->input->ip_address();
    $secret = $setting['g_secret_key'];

    $url="https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$recaptchaResponse."&remoteip=".$userIp;

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    $output = curl_exec($ch); 
    curl_close($ch);      
     
    $status= json_decode($output, true);
    if($status['success']){
    	return TRUE;
    }else{
    	return FALSE;
    }
}

/**
  *** user registration option 
**/ 
public function user_insert(){
	$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
	$this->form_validation->set_rules('phone', 'Phone', 'trim|required|xss_clean');
	$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_english_check');
	$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|is_unique[users.email]',array('is_unique'=>'The email is already Exists'));	
	$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|min_length[3]');
	$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|xss_clean|matches[password]');
	$this->form_validation->set_rules('terms', 'Terms & Condition required', 'trim|required|xss_clean');
	if ($this->form_validation->run() == FALSE) {
		$msg = '<div class="alert alert-danger alert-dismissible">
		<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
		<strong>Sorry ! </strong> '.validation_errors().'
		</div>';
		echo json_encode(array('st' => 0, 'msg'=> $msg,));
	}else{
		//package slug
		$package = get_id_by_package_slug($this->input->post('slug',TRUE));

		if(!empty($package)):
		// check unique username 
			$check = $this->admin_m->check_username(str_slug($this->input->post('username',TRUE)));

			if($check==1){
				$msg = '<div class="alert alert-danger alert-dismissible">
				<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
				<strong>Sorry ! </strong> This name <b>'.str_slug($this->input->post('username',TRUE)).'</b> already exists !!
				</div>';
				echo json_encode(array('st' => 0, 'msg'=> $msg,));
				exit();
			}else{
				$settings = get_setting();

				if(isset($settings['is_recaptcha']) && $settings['is_recaptcha']==1):
					if($this->recaptcha()==FALSE){
						$msg = '<div class="alert alert-danger alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>Sorry  ! </strong> Robot verification Failed
						</div>';
						echo json_encode(array('st' => 0, 'msg'=> $msg));
						exit();
					}
				endif;

				if(is_demo()==1){
					$data = array(
						'account_type' => $package['id'],
						'username' =>str_slug($this->input->post('username',TRUE)),
						'name' =>$this->input->post('name',TRUE),
						'email' => $this->input->post('email',TRUE),
						'phone' => $this->input->post('phone',TRUE),
						'country' => !empty($country_info)?$country_info->id:0,
						'dial_code' => !empty($country_info)?$country_info->dial_code:0,
						'password' => md5($this->input->post('password',TRUE)),
						'is_active' => 1,
						'is_verify' => 1,
						'is_payment' => 1,
						'post_time' => d_time(),
					);
					$insert = $this->admin_m->insert($data,'users');
					$u_info = get_all_user_info_slug($data['username']);
					$this->insert_features($insert);//insert all features into user_features
					// Add qr_code
					$this->qr_code($data['username']);
					$this->active_free_account($data['username'],$package['type']);
					$msg = '<div class="alert alert-success alert-dismissible">
							<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
							<p><strong>Congratulations ! </strong>Account Create Successfully</p>
							<p>Please login to continue</p>
							</div>';
					echo json_encode(array('st' => 1, 'msg'=> $msg));
					exit();
				}


				isset($settings['approve_option']) && $settings['approve_option']==1?$approve = 1:$approve=0;
				isset($settings['email_verification']) && $settings['email_verification']==1?$verify=0:$verify=1;
				isset($package['type']) && $package['type'] =='free'?$verify_type=1:$verify_type=0;


				$country_code = $this->input->post('country_code',true);
				$country_info = $this->admin_m->get_country_info($country_code);

				$data = array(
					'account_type' => $package['id'],
					'username' =>str_slug($this->input->post('username',TRUE)),
					'name' =>$this->input->post('name',TRUE),
					'email' => $this->input->post('email',TRUE),
					'phone' => $this->input->post('phone',TRUE),
					'country' => !empty($country_info)?$country_info->id:0,
					'dial_code' => !empty($country_info)?$country_info->dial_code:0,
					'password' => md5($this->input->post('password',TRUE)),
					'is_active' => $approve,
					'is_verify' => $verify,
					'is_payment' => $verify_type,
					'post_time' => d_time(),
				);
				$insert = $this->admin_m->insert($data,'users');
				if($insert){

						$u_info = get_all_user_info_slug($data['username']);

						$this->insert_features($insert);//insert all features into user_features
						// Add qr_code
						$this->qr_code($data['username']);

						//send invoice mail to user
						if(isset($settings['user_invoice']) && $settings['user_invoice'] ==1):
							$this->email_m->send_purchase_invoice($data['username']); 
						endif;	


						// when email verify on
						if(isset($settings['email_verification']) && $settings['email_verification']==1):
							$this->email_m->send_registration_mail($data,$this->input->post('password',TRUE),$package); //send registred user with account information
							$msg = '<div class="alert alert-success alert-dismissible">
							<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
							<p><strong>Congratulations ! </strong>Account Create Successfully</p>
							<p>Account confirmation link has been emailed to you, follow the link in the email to continue.</p>
							</div>';
						else:
							$msg = '<div class="alert alert-success alert-dismissible">
							<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
							<p><strong>Congratulations ! </strong>Account Create Successfully</p>
							<p>Please login to continue</p>
							</div>';
						endif;

						//send new user  email to admin 
						if(isset($settings['new_user_mail']) && $settings['new_user_mail'] ==1):
							$this->email_m->new_user_mail($data,$package); 
						endif;

					if($package['type'] !='free' && $package['type'] !='trial'){
						echo json_encode(array('st' => 1, 'msg'=> $msg));

					}else{  //free account

						
						// active free account
						$this->active_free_account($data['username'],$package['type']);
						// when verify on
						echo json_encode(array('st' => 1, 'msg'=> $msg));

					}

				}else{
					$msg = '<div class="alert alert-danger alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<strong>Sorry ! </strong> Somethings Were Wrong
					</div>';
					echo json_encode(array('st' => 0, 'msg'=> $msg,));
					
				}	
			}
		else:
			$msg = '<div class="alert alert-danger alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<strong>Sorry ! </strong> You are selected invalid package
					</div>';
					echo json_encode(array('st' => 0, 'msg'=> $msg,));	
		endif;

	}
		//end validation check
}


public function english_check($string){
	if (preg_match('/[^A-Za-z0-9 ]/', $string))  {
		    //string contains only letters from the English alphabet
		$this->form_validation->set_message('english_check', 'The {field} field contains only letters from the English alphabet.');
		return FALSE;
	}else{
		return true;
	}
}



public function payment_method($slug,$account_slug)
{
	$data = array();
	$data['page_title'] = "Payment Gateway";
	$data['slug'] = $slug;
	$data['account_type'] = $account_slug;
    $data['u_info'] = get_all_user_info_slug($slug);
    $data['settings'] = get_setting();
    $data['package'] = $this->admin_m->get_id_by_package_slug($account_slug);
	$data['main_content'] = $this->load->view('payment/payment_gateway', $data, TRUE);
	$this->load->view('payment_index',$data);
}

	


// email verify 
public function verifiy($username){
	$u_info = get_all_user_info_slug($username);
	if($u_info['is_verify']==1):
		$this->session->set_flashdata('verify', 'Your account already verified');
		redirect(base_url('login'));
	else:

		if($u_info['type']=='free' || $u_info['type'] == 'trial'):

			$this->session->set_flashdata('verify', 'Your account verified successfully');
			$data = array('is_verify'=>1,'is_payment'=>1,'is_active'=>1,'verify_time'=>d_time(),'start_date'=>d_time(),'end_date'=>add_year($u_info['type']));
			$this->admin_m->verify_mail($data, $username,'users');
			redirect(base_url('login'));
			
		else:
			$data = array('is_verify'=>1, 'is_payment'=>0, 'verify_time'=>d_time(),'start_date'=>d_time());
			$this->admin_m->verify_mail($data, $username,'users');
			$this->session->set_flashdata('verify', 'Your account verified successfully');

			// after verify by mail redirect to payment method
			redirect(base_url('payment-method/'.$username.'/'.$u_info['slug']));
			
		endif;
		
	endif;		
	
}


// email verify 
public function active_free_account($username,$package_type){
	$data = array(
		'is_verify'=>1,
		'is_payment'=>1,
		'verify_time'=>d_time(),
		'start_date'=>d_time(),
		'end_date'=>add_year($package_type),
	);
	$change = $this->admin_m->verify_mail($data, $username,'users');
	return true;		
	
}



// check username 
public function check_username($username){
	header ('Content-type: text/html; charset=utf-8');
    $username = str_slug($username);
	$check = $this->admin_m->check_username(urldecode($username));
	if($check==1){
		$msg = 'Username already exists';
		$st =0;
	}else{
		$msg = 'Username is available';
		$st =1;
	}

	$response = ['st'=>$st,'msg'=>$msg];
	echo json_encode($response);
}

public function create_admin(){
	$this->form_validation->set_rules('code', 'Purchases Code', 'trim|required|xss_clean');
	$this->form_validation->set_rules('site_id', 'Site Id Code', 'trim|required|xss_clean');
	$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|is_unique[users.username]');
	$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email|is_unique[users.email]',array('is_unique'=>'The email is already Exists'));	
	$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean|min_length[3]');

	$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|xss_clean|matches[password]');

	if ($this->form_validation->run() == FALSE) {
		$this->session->set_flashdata('error', validation_errors());
		redirect(base_url('login'));
		}else{	
			$email = $this->input->post('email',true);
			$password = md5($this->input->post('password',true));
			$code = $this->input->post('code',true);
			$site_id = $this->input->post('site_id',true);


			$check_valid = $this->check_vaild($code,$site_id);
			if($check_valid->st ==1):
				$data = array(
					'supported_until' => $check_valid->supported_until,
					'active_code' => $check_valid->active_code,
					'purchase_code' =>$code,
					'site_info' =>$check_valid->li,
					'license' =>$check_valid->license,
					'site_url' => SITE_LINK,
					'active_key' => $check_valid->active_key,
					'license_code' => $check_valid->li_code,
					'purchase_date' => $check_valid->sold_at,
					'created_at' =>d_time(),
				);
				$insert = $this->admin_m->update_setting($data,$site_id,'setting');
			else:
				$this->session->set_flashdata('error', 'Invalid Purchases Code / PUrchase code already used');
				redirect(base_url('login'));
			endif;

			if($insert):

				$data = array(
					'username' => str_slug($this->input->post('username',true)),
					'email' => strtolower($email),
					'password' => $password,
					'user_type' =>1,
					'is_verify' =>1,
					'is_active' =>1,
					'is_payment' =>1,
					'post_time' => d_time(),
				);
				$create_admin = $this->admin_m->insert($data,'users');

			endif;

			if($create_admin){
				$query = $this->admin_m->login_info_check($email,$password);
				foreach ($query['result'] as $key => $row) {
				    $s_array = array(
						'id' => $row->id,
						'username' => $row->username,
						'email' => $row->email,
						'user_type' => $row->user_type,
						'is_active' => 1,
						'is_verify' =>1,
						'is_login' => TRUE,
						'active_code' => 'NM98-MOK95-8567M',
					);
					$this->session->set_userdata($s_array);
					redirect(base_url('dashboard'),'refresh');
				};
				
				$this->session->set_flashdata('success', !empty(lang('success_text'))?lang('success_text'):'Please login');
				redirect(base_url('dashboard'));
			}else{
				$this->session->set_flashdata('error', !empty(lang('error_text'))?lang('error_text'):'Somethings Were Wrong!!');
				redirect(base_url('login'));
			}	
	}
}





	public function check_vaild($code,$site_id){
		// check_valid_purchases
			$form_data = array(
				'code'  => $code,
				'site_id'  => $site_id,
				'site_link'  => SITE_LINK,
			);
			$form_data = json_encode($form_data);
			$ch = curl_init(URL."check-valid");  
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                     
			curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data);                   
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
			curl_setopt($ch, CURLOPT_POST, 1);                                    
			$result = curl_exec($ch);
			curl_close($ch);
			return $result = json_decode($result);
	}


/**
  ** recover password
**/
public function recovery_password(){
	$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
	$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
	if ($this->form_validation->run() == FALSE) {
		$msg = '<div class="alert alert-danger alert-dismissible">
		<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
		<strong>Sorry ! </strong> '.validation_errors().'
		</div>';
		echo json_encode(array('st' => 0, 'msg'=> $msg,));
		exit();
	}else{
		$check = $this->admin_m->check_username(str_slug($this->input->post('username',TRUE)));
		$check_email = $this->admin_m->check_valid_email(strtolower(trim($this->input->post('email',true))));

		if($check!=1){
			$msg = '<div class="alert alert-danger alert-dismissible">
				<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
				<strong>Sorry ! </strong> Username not valid
			</div>';
			echo json_encode(array('st' => 0, 'msg'=> $msg,));	
			exit();
		}

		if(!$check_email){
			$msg = '<div class="alert alert-danger alert-dismissible">
				<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
				<strong>Sorry ! </strong> Email not Correct
			</div>';
			echo json_encode(array('st' => 0, 'msg'=> $msg,));	
			exit();
		}

		if($check==1 && $check_email){
			
			$data = array();
			$random_number = random_string('numeric',4);
				$data['username'] = $check_email['username'];	
				$data['email'] = $check_email['email'];	
				$data['password'] = $random_number;	

				$send = $this->email_m->send_recovery_mail($data); // call mail function

				if($send==TRUE):
					$users = array('password' => md5($random_number));
	                $this->admin_m->update($users, $check_email['id'], 'users');

	                $msg = '<div class="alert alert-success alert-dismissible">
					<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
					<strong>Success ! </strong> Recovery mail send successfully 
				</div>';
	                echo json_encode(array('st' => 1, 'msg'=> $msg,));
            else:
            	$msg = '<div class="alert alert-danger alert-dismissible">
						<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
						<strong>Error ! </strong> Somethings were wrong! Please try again 
					</div>';
                echo json_encode(array('st' => 0, 'msg'=> $msg,));
            endif;
				
		}
	}
}





/**
  ***  Logout
**/ 
	public function logout()
	{
        $this->session->unset_userdata('user_login');
        $this->session->sess_destroy();
        $sdata = array();
        $sdata['msg'] = 'You are Successfully logout';
        $this->session->set_userdata($sdata);
        redirect('login','refresh');
    }


 
    function get_data($url) {
		$ch = curl_init();
		$timeout = 5;
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;

	}

	
/**
   ** user image uploader
 **/ 
	public function upload_profile_image()
	{
		is_test();
	    $data = array();
	    if (!empty($_FILES['file']['name'])) {
	        $filesCount = count($_FILES['file']['name']);
	        for ($i = 0; $i < $filesCount; $i++) {
	              $_FILES['uploadFile']['name'] = str_replace(",","_",$_FILES['file']['name'][$i]);
	              $_FILES['uploadFile']['type'] = $_FILES['file']['type'][$i];
	              $_FILES['uploadFile']['tmp_name'] = $_FILES['file']['tmp_name'][$i];
	              $_FILES['uploadFile']['error'] = $_FILES['file']['error'][$i];
	              $_FILES['uploadFile']['size'] = $_FILES['file']['size'][$i];

	              //Directory where files will be uploaded
	              $uploadPath = 'uploads/profile/';


	              $config['upload_path'] = $uploadPath;
	              // Specifying the file formats that are supported.
	              $config['allowed_types'] = 'jpg|jpeg|png';
	              $config['overwrite'] = TRUE;
				  $config['encrypt_name'] = TRUE;
	              $this->load->library('upload', $config);
	              $this->upload->initialize($config);
	              // resize library
	              $this->load->library('image_lib');

	              if ($this->upload->do_upload('uploadFile')) {
	                  $fileData = $this->upload->data();
	                  $uploadData[$i]['file_name'] = $fileData['file_name'];
	                  // resize
			            $config = array(
						    'source_image'      => $fileData['full_path'], 
						    'new_image'         => $uploadPath.'/thumb', //path to
						    'maintain_ratio'    => true,
						    'width'             => 250,
						    'height'            => 250
						);
						    $this->image_lib->initialize($config);
						    $this->image_lib->resize();
						// resize
						    
	              }else{
	              	$error = array('error' => $this->upload->display_errors());
                    foreach ($error as $value) {
                    	$msg = $value;
                    }
                    echo json_encode(array('st'=>0,'msg'=>$msg,));
                    exit();
	              }

	        }
	          
	        if (!empty($uploadData)) {
	          $list=array();
	          	foreach ($uploadData as $value) {
		          	$data = array(
		          		'image' => $uploadPath.$value['file_name'],
		          		'thumb' => $uploadPath.'thumb/'.$value['file_name'],
		          	);
		          	//insert image into database query
		          	// $this->admin_m->update_user($data,auth('id'),'home');
		          	$this->admin_m->update(array('thumb' => $uploadPath.'thumb/'.$value['file_name']),auth('id'),'users');
	          	}
	    		echo json_encode(array('st'=>1,'img'=>$uploadPath.'thumb/'.$value['file_name']));
		  	}else{
		    	$msg = 'Please insert an image';
		    	echo json_encode(array('st'=>0,'msg'=>$msg,));
		    }

	    }
	}

	public function insert_features($user_id){
	$fetaures = $this->admin_m->select('features');
	$check_feature = $this->admin_m->select_all_by_user_id($user_id,'users_features');

	if(count($check_feature) == 0){
		foreach ($fetaures as $key => $row) {
			$data =  array(
				'feature_id' => $row['id'],
				'user_id' => $user_id,
				'status' => 1
			);
			$this->admin_m->insert($data,'users_features');
		}

	}elseif(count($check_feature) == count($fetaures)){
		return true;
	}elseif(count($check_feature) < count($fetaures)){
		
		foreach ($fetaures as $key => $row) {
			$feature_id = $this->admin_m->get_users_active_features($row['id'],$user_id);
			
			if($feature_id['feature_id']!=$row['id']){
				$data =  array(
					'feature_id' => $row['id'],
					'user_id' => $user_id,
					'status' => 1
				);
				$this->admin_m->insert($data,'users_features');
			}
			
		}
	}
	
	return true;
}




	public function qr_code($username){

		$check = get_user_info_by_slug($username);
		if(empty($check['qr_code']) || !file_exists($check['qr_code'])):
			$this->load->library('ciqrcode');
			$qr_image=$username.'_'.rand().'.png';
			$params['data'] = base_url($username);
			$params['level'] = 'H';
			$params['size'] = 8;
			$params['savename'] =FCPATH."uploads/qrcode/".$qr_image;
			if($this->ciqrcode->generate($params))
			{
				$data = array(
					'qr_code' =>'uploads/qrcode/'.$qr_image,
				);
				$update = $this->admin_m->update_by_username($data,$username,'users');
				return true;
			}
		endif;
		return true;
	}

	public function qrcode($username){
		$check = get_user_info_by_slug($username);
		$this->load->helper('download');

		$name = basename($check['qr_code']);
		$data = file_get_contents($check['qr_code']); 
		force_download($name, $data); 
		redirect('index','refresh');

		echo "File downloaded!";

		echo  "<script type='text/javascript'>";
	    echo "window.close();";
	    echo "</script>";
	}




}
