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

class Users extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->model('common_model');
		$this->load->model('users_model');
		if(get_cookie('admin_id'))
		{
			$this->session->set_userdata('admin_id',get_cookie('admin_id'));
		}
		if(!$this->session->userdata('admin_id'))
		{
			redirect('admin/login');
		}
	}
	public function alllist($page=''){
		$content_data = array();
		if($page=='')
		{
			$page=0;
		}
		$limit = 10;

		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['users'] = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','',$page,$limit) ;
		//echo $this->db->last_query(); die;
		$userlist = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC') ;
		
		//$userlist = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','','',5000) ;
		if($this->input->post())
		{
			if($this->input->post('search') && $this->input->post('search_name'))
			{
				$content_data['users'] = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','',$page,$limit,array('email'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
				$userlist = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','','','',array('email'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
			}
			if($this->input->post('search'))
			{
				$content_data['users'] = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','',$page,$limit,array('email'=>$this->input->post('search'))) ;
				$userlist = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','','','',array('email'=>$this->input->post('search'))) ;
			}
			if($this->input->post('search_name'))
			{
				$content_data['users'] = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','',$page,$limit,array('username'=>$this->input->post('search_name'))) ;
				$userlist = $this->common_model->getAll('feu_userdetails','',array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','','','',array('username'=>$this->input->post('search_name'))) ;
			}
			if($this->input->post('search_id'))
			{
				$content_data['users'] = $this->common_model->getAll('feu_userdetails',array('user_id'=>$this->input->post('search_id')),array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC','','',$page,$limit) ;
				$userlist = $this->common_model->getAll('feu_userdetails',array('user_id'=>$this->input->post('search_id')),array('usr_users','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC') ;
			}
			
		}
		$arr=array();
		require_once $_SERVER['DOCUMENT_ROOT'].'/Mandrill.php';
		$mandrill = new Mandrill('TveFwCTbtHjorrsBDKwJ8Q');
		//print_r($mandrill); die;
		if(!empty($content_data['users']))
		{
			foreach ($content_data['users'] as $key => $users) {
				//echo $users['mandrill_id']; die;
			    //$id = '938dd6f19f924062ac040777f27f4e0e';
			    /*if($users['mandrill_id'])
			    {
			    	$result = $mandrill->messages->info($users['mandrill_id']);
				    if(!empty($result))
				    {
				    	$reason = '';
				    	if($result['bounce_description'])
				    	{
				    		$reason = $result['bounce_description'];
				    	}
				    	$update=$this->common_model->UpdateData('feu_userdetails',array('email_status'=>$result['state'],'reject_reason'=>$reason),array('user_id'=>$users['id']));
				   		//echo $this->db->last_query(); die;
				    }
			    }*/
			    $qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) and user_id = '.$users['user_id'].' order by b.created DESC');
			 	$membership = $qry->row_array();
			 	$qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created <('.time().' - (365 * 86400)) when time = 182 then b.created <('.time().' - (182 * 86400)) end AND article_id in (5,4) and user_id = '.$users['user_id'].' order by b.created DESC');
			 	$membership_expired = $qry->row_array();
			    //echo $this->db->last_query(); die;
			    $arr[] = $users;
			    if(!empty($membership))
			    {
			    	$content_data['users'][$key]['membership'] = ucfirst($membership['userstatus']);
			    }
			    else
			    {
			    	if(!empty($membership_expired))
			    	{
			    		$content_data['users'][$key]['membership'] = 'Expired';
			    	}
			    	else
			    	{
			    		$content_data['users'][$key]['membership'] = 'No membership';
			    	}
			    }
			    //array_merge($users,$arr);
			}
		}	

		//$content_data['users']= $users;
		//print_r($content_data['users']); die;
		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/users/alllist/';
		$config['total_rows'] = count($userlist);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$content_data['link'] = $this->pagination->create_links();

		$data['content'] = $this->load->view('admin/users/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function expiredusers()
	{
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['users'] = $this->users_model->getExpiredMembers() ;
		//print_r($content_data['users']); die;
		$data['content'] = $this->load->view('admin/users/expiredlist', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function delete($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			$userdetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$userId));
			$useremaildata = $this->common_model->getAllRow('usr_users',array('id'=>$userId));
			$userImagesData = $this->common_model->getAll('sys_files',array('user_id'=>$userId));
			
			if(!empty($userdetails))
			{
				//$to = 'sayan@digitalaptech.com';
				$to = $useremaildata['email'];
				$sub = getAdminLang('Your_account_has_been_deleted',$userdetails['userlanguage']);
				$body= '<p>'.getAdminLang('profile_castleevents_has_been_deleted',$userdetails['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('All_content_information_as_well',$userdetails['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('We_hope_you_had_a_good_time',$userdetails['userlanguage']).'</p>';
				
				
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>Dear <span style="text-transform:capitalize">'.$userdetails['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                             <tr>
	                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
	                             		'.getAdminLang('Best_regards',$userdetails['userlanguage']).' <br>
	                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$userdetails['userlanguage']).'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';
				$this->utility->sendCIMail($to,$sub,$bodys);
			}

			$arr = array(
						'username'=>$userdetails['username'],
						'email'=>$useremaildata['email'],
						'created_date'=>$userdetails['created'],
						'delete_date'=>time()
					);
			$inst = $this->common_model->insertData('deleted_users',$arr);
			$comments = $this->common_model->getAll('cmt_comments',array('alias_path'=>'community/profil/'.$userdetails['alias']));
			$this->common_model->deleteData('usr_users',array('id'=>$userId));
			$this->common_model->deleteData('event_guest',array('username'=>$userdetails['username']));
			$this->common_model->deleteData('feu_userdetails',array('user_id'=>$userId));
			if(count($comments)>0)
			{
				foreach ($comments as $value) {
					$this->common_model->deleteData('cmt_comments',array('id'=>$value['id']));
				}
			}
			$this->common_model->deleteData('feu_addresses',array('user_id'=>$userId));
			$this->common_model->deleteData('feu_auth_requests',array('user_id'=>$userId));
			$this->common_model->deleteData('feu_profilevisits',array('from_user_id'=>$userId));
			$this->common_model->deleteData('feu_profilevisits',array('to_user_id'=>$userId));
			$this->common_model->deleteData('feu_relationships',array('user_id_1'=>$userId));
			$this->common_model->deleteData('feu_relationships',array('user_id_2'=>$userId));
			$this->common_model->deleteData('feu_sexual_preference',array('user_id'=>$userId));
			$this->common_model->deleteData('feu_user_discounts',array('user_id'=>$userId));
			$this->common_model->deleteData('feu_user_steps',array('user_id'=>$userId));
			$this->common_model->deleteData('like_likes',array('user_id'=>$userId));
			$this->common_model->deleteData('like_likes',array('identifier'=>'profile:'.$userId));
			$this->common_model->deleteData('msg_conversations_users',array('user_id'=>$userId));
			$this->common_model->deleteData('msg_messages',array('from_user_id'=>$userId));
			$this->common_model->deleteData('newsletter_couple_lady',array('couple'=>$userId));
			$this->common_model->deleteData('newsletter_couple_lady',array('lady'=>$userId));
			$this->common_model->deleteData('newsletter_couple_lady',array('gentleman'=>$userId));
			$this->common_model->deleteData('notification',array('from_id'=>$userId));
			$this->common_model->deleteData('notification',array('to_id'=>$userId));
			//$this->common_model->deleteData('shop_carts',array('user_id'=>$userId));
			//$this->common_model->deleteData('shop_orders',array('invoiceAddress'=>$useremaildata['email']));
			$this->common_model->deleteData('sys_files',array('user_id'=>$userId));
			$this->common_model->deleteData('ugal_images',array('user_id'=>$userId));
			$this->common_model->deleteData('ugal_images_user_privacy',array('from_user_id'=>$userId));
			$this->common_model->deleteData('ugal_images_user_privacy',array('to_user_id'=>$userId));
			$this->common_model->deleteData('usr_log',array('user_id'=>$userId));
			$this->common_model->deleteData('usr_modules',array('user_id'=>$userId));
			$this->common_model->deleteData('usr_phones',array('user_id'=>$userId));
			$this->common_model->deleteData('usr_recurring_payment',array('user_id'=>$userId));
			$this->common_model->deleteData('usr_roles_users',array('user_id'=>$userId));
			if(count($userImagesData)>0)
			{
				foreach ($userImagesData as $value) {
					$filename = $value['filename'].'.'.$value['extension'];
					
					$filename_blur = $value['filename'].'_blur.'.$value['extension'];
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/'.$filename);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/80/'.$filename);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/160/'.$filename);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/320/'.$filename);
					
					if($value['temp_name']!='')
					{
						$temp_name = $value['temp_name'].'.'.$value['extension'];
						@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/'.$temp_name);
						@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/80/'.$temp_name);
						@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/160/'.$temp_name);
						@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/320/'.$temp_name);
					}

					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/'.$filename_blur);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/250/'.$filename);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/500/'.$filename);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/750/'.$filename);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/1000/'.$filename);

					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/250/'.$filename_blur);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/500/'.$filename_blur);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/750/'.$filename_blur);
					@unlink(FCPATH.'assets/userfiles/'.$value['path'].'/1000/'.$filename_blur);
				}
			}
			/********Delete from Castleevents German************/
			$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
			$listId = "4b705bab4e";
			$batch_operations = array();
			$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower($useremaildata['email']));
			$operation = array(
		            'email_address'=>$useremaildata['email'],
		            
		            );
			$request_encoded = json_encode($operation);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_USERPWD, 'user:' . $apiKey);    
		    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
		    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
		    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
			$result = curl_exec($curl);
			//var_dump($result); die;
			/********Delete from Castleevents German************/

			/********Delete from Castleevents English************/	
			$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
			$listIdEng = "a8efb2baef";
			$batch_operations = array();
			$urlEng = "https://us14.api.mailchimp.com/3.0/lists/".$listIdEng."/members/".md5(strtolower($useremaildata['email']));
			$operationEng = array(
		            'email_address'=>$useremaildata['email'],
		            
		            );
			$request_encodedEng = json_encode($operationEng);
		    $curl = curl_init($urlEng);
		    curl_setopt($curl, CURLOPT_USERPWD, 'user:' . $apiKey);    
		    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
		    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
		    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encodedEng); 
			$result = curl_exec($curl);
			/********Delete from Castleevents English************/	
	

			$this->utility->setMsg('Member deleted','SUCCESS');	
			redirect(base_url().'admin/users/alllist');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function deletelist($page=''){
		$content_data = array();
		if($page=='')
		{
			$page=0;
		}
		$limit = 10;

		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['users'] = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','',$page,$limit) ;
		//echo $this->db->last_query(); die;
		$userlist = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC') ;
		if($this->input->post())
		{
			if($this->input->post('search') && $this->input->post('search_name'))
			{
				$content_data['users'] = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','',$page,$limit,array('email'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
				$userlist = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','','','',array('email'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
				
			}
			if($this->input->post('search'))
			{
				$content_data['users'] = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','',$page,$limit,array('email'=>$this->input->post('search'))) ;
				$userlist = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','','','',array('email'=>$this->input->post('search'))) ;
			}
			if($this->input->post('search_name'))
			{
				$content_data['users'] = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','',$page,$limit,array('username'=>$this->input->post('search_name'))) ;
				$userlist = $this->common_model->getAll('deleted_users','','','deleted_users.delete_date DESC','','','','',array('username'=>$this->input->post('search_name'))) ;
			}
			
		}
		
		//print_r($content_data['users']); die;
		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/users/deletelist/';
		$config['total_rows'] = count($userlist);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$content_data['link'] = $this->pagination->create_links();

		$data['content'] = $this->load->view('admin/users/deletelist', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function email_confirm($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('usr_users',array('email_confirmed'=>1),array('id'=>$userId));
			$this->utility->setMsg('Member email confirmed','SUCCESS');	
			redirect(base_url().'admin/users/alllist');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function edit($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			if($this->input->post())
			{//print_r($this->input->post()); die;
				$email=$this->utility->info_cleanQuery($this->input->post('email'));
				$username=$this->utility->info_cleanQuery($this->input->post('public_username'));
				$password = '';
				if($this->input->post('public_password'))
				{
					$password=$this->common_model->generateHash($this->utility->info_cleanQuery($this->input->post('public_password')));
				}
				$discount=$this->utility->info_cleanQuery($this->input->post('discount'));
				$acount_type=$this->utility->info_cleanQuery($this->input->post('acount_type'));
				$lady_dob = strtotime($this->input->post('she_year').'-'.$this->input->post('she_month').'-'.$this->input->post('she_date'));
				$gen_dob = strtotime($this->input->post('he_year').'-'.$this->input->post('he_month').'-'.$this->input->post('he_date'));
				$lady_physis = $this->input->post('she_physis');
				$gen_physis = $this->input->post('he_physis');
				$about=$this->utility->info_cleanQuery($this->input->post('about'));
				$preferences=$this->utility->info_cleanQuery($this->input->post('preferences'));
				$interested_lady=$this->utility->info_cleanQuery($this->input->post('interested_lady'));
				$interested_gen=$this->utility->info_cleanQuery($this->input->post('interested_gen'));
				$interested_couple=$this->utility->info_cleanQuery($this->input->post('interested_couple'));
				$country=$this->utility->info_cleanQuery($this->input->post('country'));
				$language=$this->utility->info_cleanQuery($this->input->post('language'));
				
				//echo $this->db->last_query();die;
				$emailDetails = $this->common_model->getAllRow('usr_users',array('id'=>$userId));
				$usernameDetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$userId));
				if($email!='')
				{
					$emailExit = $this->common_model->getAllRow('usr_users',array('email'=>$email,'id !='=>$userId));
					if(count($emailExit)==0)
					{
						$usr_con=array(
								'email'=>$email
						);
						$this->common_model->UpdateData('usr_users',$usr_con,array('id'=>$userId));
						$this->common_model->UpdateData('shop_orders',array('invoiceAddress'=>$email),array('invoiceAddress'=>$emailDetails['email']));
					}
					else
					{
						$this->utility->setMsg('Email already exist','ERROR');	
						redirect(base_url().'admin/users/edit/'.$enc_userID);
					}
				}
				
				if($password !='')
				{
					$usr_con=array(
							'password'=>$password
					);
					$this->common_model->UpdateData('usr_users',$usr_con,array('id'=>$userId));
				}
				if($username !='')
				{
					$usr_con=array(
							'username'=>$username
					);
					$this->common_model->UpdateData('feu_userdetails',$usr_con,array('user_id'=>$userId));
					$this->common_model->UpdateData('event_guest',array('username'=>$username),array('username'=>$usernameDetails['username']));
					//echo $this->db->last_query(); die;
				}
				
				$usrDetails_con=array(
							'accounttype'=>$acount_type,
							'dob_lady'=>($lady_dob),
							'dob_gentleman'=>($gen_dob),
							'physis_lady'=>$lady_physis,
							'physis_gentleman'=>$gen_physis,
							'preferences'=>$preferences,
							'interested_in_ladies'=>$interested_lady,
							'interested_in_gentlemen'=>$interested_gen,
							'interested_in_couples'=>$interested_couple,
							'about'=>$about,
							'country'=>$country,
							'userlanguage'=>$language,
							'visitor_mail'=>$this->input->post('visitor_mail'),
							'interested_in_private_meeting'=>$this->input->post('interested_in_private_meeting'),
							'interested_financial_interests'=>$this->input->post('interested_financial_interests'),
							'escort_interest'=>$this->input->post('escort_interest'),
					);
				$this->common_model->UpdateData('feu_userdetails',$usrDetails_con,array('user_id'=>$userId));


				/***************unsubscribe newsletter***********************/
				if($this->input->post('unsub'))
				{
					$userdata = $this->common_model->getAllRow('usr_users',array('id'=>$userId),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
					$this->common_model->UpdateData('feu_userdetails',array('subscribe'=>0),array('user_id'=>$userId));
					$list_id = $userdata['mailchimp_list_id'];
					//$list_id = '118a4ef469';
					$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
					$url = "https://us14.api.mailchimp.com/3.0/lists/".$list_id."/members/".md5(strtolower($userdata['email']));
					$operation = array(
				            'email_address'=>$userdata['email'],
				            'status'=>'subscribed'
				            );
					$request_encoded = json_encode($operation);
				    $curl = curl_init($url);
				    curl_setopt($curl, CURLOPT_USERPWD, 'user:' . $apiKey);    
				    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
				    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
				    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
				    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
					$result = curl_exec($curl);
				}
				/***************unsubscribe newsletter***********************/


				$sexual_preference = $this->input->post('sexual_preference');
				if(!empty($sexual_preference))
				{
					$this->common_model->deleteData('feu_sexual_preference',array('user_id'=>$userId));
					foreach ($sexual_preference as $key => $value) {
						$arr = array(
								'user_id'=>$userId,
								'sex_preference'=>$value,
						);
						$this->common_model->insertData('feu_sexual_preference',$arr);
					}
				}
				$discountDetails = $this->common_model->getAllRow('feu_user_discounts',array('user_id'=>$userId));
				if(empty($discountDetails))
				{
					$dis_con=array(
						'user_id'=>$userId,
						'discount'=>$discount,
						'created'=>time()
					);
					$this->common_model->insertData('feu_user_discounts',$dis_con);
				}
				else
				{
					$dis_con=array(
							'discount'=>$discount
					);
					$this->common_model->UpdateData('feu_user_discounts',$dis_con,array('user_id'=>$userId));
				}
				if($_FILES['avatar']['name']!='')
				{
					$imagefolder = 'avatars/' ;
			        $uploadpath = 'assets/userfiles/'. $imagefolder;
					$filename = microtime().$_FILES['avatar']['name'];
			        $config = array(
			            'upload_path' 		=> FCPATH . $uploadpath . '/',
			            'allowed_types' 	=> 'jpg|JPG|png|PNG|jpeg|JPEG',
			            'encrypt_name' 		=> true,
			            'file_name'			=> $filename,
			            'file_ext_tolower' 	=> true,
			            //'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
			        );

			        $this->load->library('upload', $config);
			       
			        if(!$this->upload->do_upload('avatar')) {

			            $this->utility->setMsg($this->upload->display_errors(),'ERROR');	
						redirect(base_url().'admin/users/edit/'.$enc_userID);
			        }

			        $uploaddata = $this->upload->data();
			        if($uploaddata)
			        {
			        	$file = array(
			            'user_id' 	=> $userId,
			            'path' 		=> $imagefolder,
			            'filename' 	=> $uploaddata['raw_name'],
			            'extension' => substr($uploaddata['file_ext'], 1),
			            'mimetype' 	=> $uploaddata['file_type'],
			            'is_image' 	=> $uploaddata['is_image'],
			            'attr_alt' 	=> 'Bild von ' ,
			            'created'	=> time(),
			            'temp_name'	=> ''
				        );
				        
				        $imagesize = getimagesize($uploaddata['full_path']);
				        $file['width'] 	= $imagesize[0];
				        $file['height'] = $imagesize[1];


				        $fileId = $this->common_model->insertData('sys_files',$file);

						$resize = $this->avater($uploaddata['raw_name'] .'.'. substr($uploaddata['file_ext'], 1));

				        $this->common_model->UpdateData('feu_userdetails',array('avatar_file_id'=>$fileId),array('user_id'=>$userId));
						
			        }
			    }
			    if(count($_FILES['profileImages']['name'])>0)
				{
					for($i=0;$i<count($_FILES['profileImages']['name']);$i++)
					{
						if($_FILES['profileImages']['name'][$i]!='')
						{
							$_FILES['userFile']['name'] = $_FILES['profileImages']['name'][$i];
				            $_FILES['userFile']['type'] = $_FILES['profileImages']['type'][$i];
				            $_FILES['userFile']['tmp_name'] = $_FILES['profileImages']['tmp_name'][$i];
				            $_FILES['userFile']['error'] = $_FILES['profileImages']['error'][$i];
				            $_FILES['userFile']['size'] = $_FILES['profileImages']['size'][$i];
				            //pr($_FILES);
							$imagefolder = 'usergalleries/';
					        $uploadpath = 'assets/userfiles/'. $imagefolder;
							$config = array(
					            'upload_path' 		=> FCPATH . $uploadpath . '/',
					            'allowed_types' 	=> 'jpg|JPG|png|PNG|jpeg|JPEG',
					            'encrypt_name' 		=> true,
					            'file_ext_tolower' 	=> true,
					            //'min_width'			=> 400,
					            //'min_height'		=> 400
					            //'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
					        );

					        $this->load->library('upload', $config);
					        $this->upload->initialize($config);
					        if(!$this->upload->do_upload('userFile')) {

					            $this->utility->setMsg($this->upload->display_errors(),'ERROR');	
								redirect(base_url().'admin/users/edit/'.$enc_userID);
					        }

					        $uploaddata = $this->upload->data();
					        $this->load->library('Utility');

					        //$this->utility->pic_resize($uploadpath.$uploaddata['raw_name'].substr($uploaddata['file_ext'], 1),$uploadpath.$uploaddata['raw_name'].substr($uploaddata['file_ext'], 1),400,400);
					        if(!file_exists(FCPATH . 'assets/userfiles/usergalleries/' . $uploaddata['raw_name'] .'_blur.'. substr($uploaddata['file_ext'], 1))){
					            $im = new Imagick(FCPATH . 'assets/userfiles/usergalleries/' . $uploaddata['raw_name'] .'.'. substr($uploaddata['file_ext'], 1));
					            //print_r(FCPATH . 'assets/userfiles/' . $fileDetails['path'] . '/' . $fileDetails['filename'] .'.'. $fileDetails['extension']); die;
					            $im->blurImage(30,20);
					            $blurredImg = FCPATH . 'assets/userfiles/usergalleries/' . $uploaddata['raw_name'] .'_blur.'. substr($uploaddata['file_ext'], 1);
					            $fp = fopen($blurredImg, "x");
					            $im->writeImageFile($fp);
					            //fclose($fp);
				        	}

					        $file = array(
						            'user_id' 	=> $userId,
						            'path' 		=> $imagefolder,
						            'filename' 	=> $uploaddata['raw_name'],
						            'extension' => substr($uploaddata['file_ext'], 1),
						            'mimetype' 	=> $uploaddata['file_type'],
						            'is_image' 	=> $uploaddata['is_image'],
						            'created'	=> time(),
						            'temp_name'	=> $uploaddata['raw_name'],
						            //'attr_alt' 	=> 'Bild von ' . $username,
						        );
					        
					        $imagesize = getimagesize($uploaddata['full_path']);
						    $file['width'] 	= $imagesize[0];
						    $file['height'] = $imagesize[1];

						    $fileId = $this->common_model->insertData('sys_files',$file);
							$dataset = array(
						            'user_id' 	=> $userId,
						            'file_id' 	=> $fileId,
						            'is_private'=> 1,
						            'created'	=>time()
						        );
						    $galId = $this->common_model->insertData('ugal_images',$dataset);
						    $this->common_model->insertData('notification',array('from_id'=>$userId,'to_id'=>1,'type'=>12,'created'=>time(),'file_id'=>$fileId));        
						}
					}
				}
				
				$this->utility->setMsg('Member details update','SUCCESS');	
				redirect(base_url().'admin/users/edit/'.$enc_userID);
			}

			$content_data = array();
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$content_data['userDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$userId),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$content_data['avatarImage'] = $this->common_model->getAllRow('sys_files',array('id'=>$content_data['userDetails']['avatar_file_id'])) ;
			$content_data['membershipDetails'] = $this->users_model->getMembershipDetails($userId);
			//echo $this->db->last_query(); die;
			$content_data['memberDiscount'] = $this->common_model->getAllRow('feu_user_discounts',array('user_id'=>$userId),'','created DESC');
			$content_data['memberStep'] = $this->common_model->getAllRow('feu_user_steps',array('user_id'=>$userId),'','created DESC');
			$content_data['memberImages'] = $this->common_model->getAll('ugal_images',array('ugal_images.user_id'=>$userId,'sys_files.is_image'=>1),array('sys_files','sys_files.id = ugal_images.file_id'),'ugal_images.created DESC');
			$content_data['coutries'] = $this->common_model->getAll('feu_countries');
			$content_data['languages'] = $this->common_model->getAll('sys_languages');
			$sql111 = "SELECT `shop_orders`.*, `shop_articles_carts`.`event_id`, `shop_articles_carts`.`article_id` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_orders`.`cart_id` = `shop_carts`.`id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE `user_id` = ".$userId." And  is_booking = 0 and  payed = 0 ORDER BY `shop_orders`.`created` DESC";
			$orders111 = $this->db->query($sql111);
			$sql = "SELECT `shop_orders`.*, `shop_articles_carts`.`event_id`, `shop_articles_carts`.`article_id` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_orders`.`cart_id` = `shop_carts`.`id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE `user_id` = ".$userId." AND order_id > 0 AND event_id is NULL And case when is_booking = 0 and is_renewed = 0 then payed = 1 when is_renewed = 1 then payed in (0,1) end ORDER BY `shop_orders`.`order_id` DESC";
			$orders = $this->db->query($sql);
			$content_data['userPreferences'] = $this->common_model->getAllMultipleJoin('feu_sexual_preference',array('feu_sexual_preference.user_id'=>$userId)) ;
			$content_data['lifestyles'] = $this->common_model->getAll('lifestyles');
			//echo $this->db->last_query();die;
			$content_data['orders111'] = $orders111->result_array();
			$content_data['orders'] = $orders->result_array();

			$sql = "SELECT `shop_orders`.*, `shop_articles_carts`.`event_id`, `shop_articles_carts`.`article_id` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_orders`.`cart_id` = `shop_carts`.`id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE `user_id` = ".$userId." AND order_id > 0 And (is_booking = 1 OR event_id > 0) ORDER BY `shop_orders`.`order_id` DESC";
			$bookingorders = $this->db->query($sql);
			$content_data['bookingorders'] = $bookingorders->result_array();
			//pr($content_data['orders']);
			/*************************Log*************************/
			$ConnectRequestRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 1 AND from_id = ".$userId);
			$content_data['LoginRequest'] = $ConnectRequestRes->result_array();
			$LoginRes = $this->db->query("SELECT count(*) as total FROM `usr_log` WHERE type= 1 AND user_id = ".$userId);
			$content_data['Login'] = $LoginRes->result_array();
			$PrivacyRequestRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 5 AND from_id = ".$userId);
			$content_data['PrivacyRequest'] = $PrivacyRequestRes->result_array();
			$MessageRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 4 AND from_id = ".$userId);
			$content_data['Message'] = $MessageRes->result_array();
			$HotshotProfileRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 8 AND from_id = ".$userId);
			$content_data['HotshotProfile'] = $HotshotProfileRes->result_array();
			$HotshotPictureRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 9 AND from_id = ".$userId);
			$content_data['HotshotPicture'] = $HotshotPictureRes->result_array();
			$VisitRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 10 AND from_id = ".$userId);
			$content_data['Visit'] = $VisitRes->result_array();
			$VisitHisProfileRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 10 AND to_id = ".$userId);
			$content_data['VisitHisProfile'] = $VisitHisProfileRes->result_array();
			$UploadRes = $this->db->query("SELECT count(*) as total FROM `notification` WHERE type= 12 AND from_id = ".$userId);
			$content_data['Upload'] = $UploadRes->result_array();

			/*************************Log*************************/

			$to_number = '';
			$userPhones = $this->common_model->getAllRow('usr_phones',array('user_id'=>$userId));
			if($content_data['userDetails']['mobile_number']!='')
			{
				if(strpos($content_data['userDetails']['mobile_number'],'+') === false)
				{
					$to_number = '+'.$content_data['userDetails']['mobile_number'];
				}
				else
				{
					$to_number = $content_data['userDetails']['mobile_number'];
				}
			}
			elseif($userPhones)
			{
				if(strpos($userPhones['mobile_number'],'+') === false)
				{
					$to_number = '+'.$userPhones['mobile_number'];
				}
				else
				{
					$to_number = $userPhones['mobile_number'];
				}
			}
			$content_data['to_number'] = $to_number;

			$receivedWhere = "msg_conversations_users.user_id != '' AND (text !='' OR image_path != '') AND msg_conversations_users.user_id =".$userId;
			$content_data['received_msg'] = $this->common_model->getAllMultipleJoin('msg_messages',$receivedWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','*,msg_messages.created as msg_create');

			$givenWhere = "msg_conversations_users.user_id != '' AND (text !='' OR image_path != '') AND msg_messages.from_user_id =".$userId;
			$content_data['given_msg'] = $this->common_model->getAllMultipleJoin('msg_messages',$givenWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_conversations_users.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','*,msg_messages.created as msg_create');

			/***************************year wiese statistics****************************/
			$allordersstats = [];
			for($i=2015; $i<=date('Y');$i++){
				$ordersqlstat = "SELECT sum(total_sum) as order_total,YEAR(FROM_UNIXTIME(shop_orders.created)) as year,count(*) as count FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_orders`.`cart_id` = `shop_carts`.`id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE `user_id` = ".$userId." And is_booking = 0 AND  payed = 1 AND order_id > 0 AND event_id is NULL AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$i." GROUP BY year ORDER BY `shop_orders`.`order_id` DESC";
				$ordersstat = $this->db->query($ordersqlstat);
				$ordersstats = $ordersstat->row_array();

				$booksql = "SELECT sum(total_sum) as booking_total,YEAR(FROM_UNIXTIME(shop_orders.created)) as year FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_orders`.`cart_id` = `shop_carts`.`id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` WHERE `user_id` = ".$userId." And (is_booking = 1 OR event_id > 0) AND  payed = 1 AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$i."  AND order_id > 0 GROUP BY year ORDER BY `shop_orders`.`order_id` DESC";
				$bookstat = $this->db->query($booksql);
				$bookstats = $bookstat->row_array();//print_r($bookstats);
				$allordersstats[$i]['year'] = $i;
				$allordersstats[$i]['order_total'] = $ordersstats['order_total']/100;
				$allordersstats[$i]['booking_total'] = $bookstats['booking_total']/100;
			}
			$content_data['ordersstats'] = $allordersstats;
			$content_data['usr_downgrade'] = $this->common_model->getAllRow('usr_downgraded',array('users_id'=>$userId, 'downgrade_date >'=>date('Y-m-d'))) ;
			/***************************year wiese statistics****************************/
			$content_data['userAddress'] = $this->common_model->getAll('feu_addresses',array('user_id'=>$userId));
			//pr($allordersstats);
			$data['content'] = $this->load->view('admin/users/edit', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function add()
	{
		if($this->input->post())
		{
			$email=$this->utility->info_cleanQuery($this->input->post('useremail'));
			$username=$this->utility->info_cleanQuery($this->input->post('userusername'));
			$password=$this->common_model->generateHash($this->utility->info_cleanQuery($this->input->post('userpassword')));
			$discount=$this->utility->info_cleanQuery($this->input->post('discount'));
			$acount_type=$this->utility->info_cleanQuery($this->input->post('acount_type'));
			$lady_dob=$this->utility->info_cleanQuery($this->input->post('lady_dob'));
			$lady_physis=$this->utility->info_cleanQuery($this->input->post('lady_physis'));
			$gen_dob=$this->utility->info_cleanQuery($this->input->post('gen_dob'));
			$gen_physis=$this->utility->info_cleanQuery($this->input->post('gen_physis'));
			$about=$this->utility->info_cleanQuery($this->input->post('about'));
			$preferences=$this->utility->info_cleanQuery($this->input->post('preferences'));
			$interested_lady=$this->utility->info_cleanQuery($this->input->post('interested_lady'));
			$interested_gen=$this->utility->info_cleanQuery($this->input->post('interested_gen'));
			$interested_couple=$this->utility->info_cleanQuery($this->input->post('interested_couple'));
			$country=$this->utility->info_cleanQuery($this->input->post('country'));
			$language=$this->utility->info_cleanQuery($this->input->post('language'));
			
			
			$usr_con=array(
						'email'=>$email,
						'created'=>time(),
						'password'=>$password,
						'email_confirmed'=>1,
				);
			$userId = $this->common_model->insertData('usr_users',$usr_con);
			
			$usrDetails_con=array(
						'user_id'=>$userId,
						'created'=>time(),
						'username'=>$username,
						'alias'=>str_replace(' ','-',trim($username)),
						'accounttype'=>$acount_type,
						'dob_lady'=>strtotime($lady_dob),
						'dob_gentleman'=>strtotime($gen_dob),
						'physis_lady'=>$lady_physis,
						'physis_gentleman'=>$gen_physis,
						'preferences'=>$preferences,
						'interested_in_ladies'=>$interested_lady,
						'interested_in_gentlemen'=>$interested_gen,
						'interested_in_couples'=>$interested_couple,
						'about'=>$about,
						'country'=>$country,
						'userlanguage'=>$language
				);
			$this->common_model->insertData('feu_userdetails',$usrDetails_con);

			$dis_con=array(
						'user_id'=>$userId,
						'discount'=>$discount,
						'created'=>time()
				);
			$this->common_model->insertData('feu_user_discounts',$dis_con);
			
			if($_FILES['imagefile']['name']!='')
			{
				$imagefolder = 'avatars/';
		        $uploadpath = 'assets/userfiles/'. $imagefolder;
				if (!file_exists(FCPATH . $uploadpath)) {
				    mkdir(FCPATH . $uploadpath, 0777, true);
				}
		        $config = array(
		            'upload_path' 		=> FCPATH . $uploadpath . '/',
		            'allowed_types' 	=> '*',
		            'encrypt_name' 		=> true,
		            'file_ext_tolower' 	=> true,
		            //'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
		        );

		        $this->load->library('upload', $config);
		       
		        if(!$this->upload->do_upload('imagefile')) {

		            $this->utility->setMsg($this->upload->display_errors(),'ERROR');	
				}

		        $uploaddata = $this->upload->data();

		        $file = array(
		            'user_id' 	=> $userId,
		            'path' 		=> $imagefolder,
		            'filename' 	=> $uploaddata['raw_name'],
		            'extension' => substr($uploaddata['file_ext'], 1),
		            'mimetype' 	=> $uploaddata['file_type'],
		            'is_image' 	=> $uploaddata['is_image'],
		            'attr_alt' 	=> 'Bild von ' . $username,
		        );
		        if($this->input->post('is_private'))
		        {
					/*if(!file_exists(FCPATH . 'assets/userfiles/' .$imagefolder . '/' . $uploaddata['raw_name'] .'_blur.'. substr($uploaddata['file_ext'], 1))){
			            $im = new Imagick(FCPATH . 'assets/userfiles/' . $imagefolder . '/' . $uploaddata['raw_name'] .'.'. substr($uploaddata['file_ext'], 1));
			            $im->blurImage(30,20);
			            $blurredImg = FCPATH . 'assets/userfiles/' .$imagefolder . '/' . $uploaddata['raw_name'] .'_blur.'. substr($uploaddata['file_ext'], 1);
			            $fp = fopen($blurredImg, "x");
			            $im->writeImageFile($fp);
			            fclose($fp);
		        	}*/
		        }
		       
		        $imagesize = getimagesize($uploaddata['full_path']);

		        $file['width'] 	= $imagesize[0];
		        $file['height'] = $imagesize[1];


		        $fileId = $this->common_model->insertData('sys_files',$file);
		        if($this->input->post('is_avatar'))
		        {
		        	$set = array(
			            'avatar_file_id' 	=> $fileId,
		        	);
		        	$this->common_model->updateData('feu_userdetails',$set,array('user_id'=>$userId));
		        }
		        else
		        {
		        	$dataset = array(
			            'user_id' 	=> $userId,
			            'file_id' 	=> $fileId,
			            'is_private'=> ($this->input->post('is_private'))?1:0,
			        );
			        $this->common_model->insertData('ugal_images',$dataset);
		        }
		        
			}
			$this->utility->setMsg('Member details added','SUCCESS');	
			redirect(base_url().'admin/users/alllist');
		}

		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['coutries'] = $this->common_model->getAll('feu_countries');
		$content_data['languages'] = $this->common_model->getAll('sys_languages');
		
		$data['content'] = $this->load->view('admin/users/add', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
		
	}

	public function add_membership($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			if($this->input->post())
			{
				$membershipDetails = $this->common_model->getAllRow('shop_articles',array('id'=>$this->input->post('type')));
				if($this->input->post('price')==6)
				{
					$origPrice = 17000;
					$time = 182;
				}
				else
				{
					$origPrice = $membershipDetails['base_price'];
					$time = 365;
				}
				$feePrice = $origPrice*(2.5/100);
				$type = $this->input->post('type');
				$user_id = $userId;
				$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$userId));
				$userData = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$userId));
				$finaltotal = 0;
				$finaltotal = $feePrice+$origPrice;
				$cartArr = array(
							'created'=>time(),
							'user_id'=>$user_id,
							'session_id'=>$this->session->userdata('session_id'),
							'ordered'=>1
					);
				$cartId = $this->common_model->insertData('shop_carts',$cartArr);
				$artArr = array(
							'created'=>time(),
							'cart_id'=>$cartId,
							'article_id'=>$type,
							'quantity'=>1
					);
				$cartArtId = $this->common_model->insertData('shop_articles_carts',$artArr);
				$orderDetails = $this->common_model->getAllRow('shop_orders','','','','max(order_id) as order_id');
				
				$dataset = array(
					'order_id'				=> $orderDetails['order_id']+1,
					'cart_id' 				=> $cartId,
					'shipping_address_id' 	=> 13,
					'invoice_address_id' 	=> 13,
					'ip_address' 			=> $this->input->ip_address(),
					'total_base' 			=> $origPrice,
					'shipping_fee' 			=> 0,
					'payment_fee' 			=> $feePrice,
					'vat' 					=> 0,
					'total_sum' 			=> $finaltotal,
					'payment_method_id' 	=> 15,
					'invoiceAddress' 		=> $userDetails['email'],
		            'discount'              => 0,
		            'time'					=> $time,
		            'created'				=> time(),
		            'payed'					=> 1
				);
				$this->common_model->insertData('shop_orders',$dataset);
				$orderId = $orderDetails['order_id']+1;
				
				$this->common_model->UpdateData('shop_orders',array('order_id_masked'=>'CE-'.$orderId),array('order_id'=>$orderId));
				$stepdata = $this->common_model->getAllRow('feu_user_steps',array('user_id'=>$user_id,'step'=>6));
				if(!empty($stepdata))
				{
					$this->common_model->deleteData('feu_user_steps',array('user_id'=>$user_id));
				}
				

				$this->utility->setMsg('Member details added','SUCCESS');	
				redirect(base_url().'admin/users/alllist');
			}

			$content_data = array();
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id Desc') ;
			
			$data['content'] = $this->load->view('admin/users/add_membership', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function premiums(){
		$content_data = array();
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$res = $this->db->query('select * from (select * from (SELECT usr_users.last_login, feu_userdetails.accounttype,usr_users.email_confirmed, feu_userdetails.username,shop_articles_carts.article_id as id,shop_orders.payment_method_id,shop_orders.cart_id,shop_orders.time,usr_users.customer_id,shop_orders.created,shop_articles_carts.article_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN feu_userdetails ON feu_userdetails.user_id = usr_users.id WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where b.created > ('.time().' - (time * 365 * 86400)) AND article_id in (4)  order by b.created DESC');
        //$res = $this->db->query('select * from (select * from (SELECT shop_orders.created,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE  `shop_articles`.`reoccuring` IS NOT NULL AND `shop_articles`.`reoccuring` >0 AND ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where b.user_id = '.$userId.' order by b.user_id');
        $result = $res->result_array();
		$content_data['users'] = $result;
		//print_r($content_data['users']); die;
		
		$data['content'] = $this->load->view('admin/users/premiums', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function block($enc_userID='',$status='')
	{
		if($enc_userID!='')
		{
			if($status==2)
			{
				$new = 0;
			}
			else
			{
				$new = 1;
			}
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('usr_users',array('status'=>$new),array('id'=>$userId));
			$this->utility->setMsg('Member block status chnaged successfully','SUCCESS');	
			redirect(base_url().'admin/users/alllist');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function profile_text($page=''){
		$content_data = array();
		if($page=='')
		{
			$page=0;
		}
		$limit = 20;

		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['profile_text'] = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',$page,$limit);
		$profile_text_list = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',0,5000) ;
		if($this->input->post())
		{
			if($this->input->post('search') && $this->input->post('search_name'))
			{
				$content_data['profile_text'] = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',$page,$limit,array('about'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
				$profile_text_list = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',0,5000,array('about'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
			}
			if($this->input->post('search'))
			{
				$content_data['profile_text'] = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',$page,$limit,array('about'=>$this->input->post('search'))) ;
				$profile_text_list = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',0,5000,array('about'=>$this->input->post('search'))) ;
			}
			if($this->input->post('search_name'))
			{
				$content_data['profile_text'] = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',$page,$limit,array('username'=>$this->input->post('search_name'))) ;
				$profile_text_list = $this->common_model->getAll('feu_userdetails','','','feu_userdetails.created DESC','','',0,5000,array('username'=>$this->input->post('search_name'))) ;
			}
		}
		//echo '<pre>';print_r($content_data['profile_text']);die;
		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/users/profile_text/';
		$config['total_rows'] = count($profile_text_list);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$content_data['link'] = $this->pagination->create_links();

		$data['content'] = $this->load->view('admin/profile_text/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function remove($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('feu_userdetails',array('about'=>''),array('user_id'=>$userId));
			$userDetail = $this->common_model->getAllRowMultipleJoin('usr_users',array('user_id'=>$userId),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
			/****************Remove Mail******************/
			if(!empty($userDetail))
			{
				//$to = 'sayan@digitalaptech.com';
				$to = $userDetail['email'];
				$sub = getAdminLang('Your_profile_text_has_been_removed',$userDetail['userlanguage']);
				$body= '<p>'.getAdminLang('Unfortunately_your_profile_text_has_been_removed',$userDetail['userlanguage']).'!</p>';
				$body.= '<p>'.getAdminLang('Castleevents_is_known_as_probably_the_most_exclusive',$userDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('when_writing_profile_texts',$userDetail['userlanguage']).'</p>';
				$body.= '<ul>';
				$body.= '<li>'.getAdminLang('Protect_your_anonymity',$userDetail['userlanguage']).'</li>';
				$body.= '<li>'.getAdminLang('Texts_should_be_written_in_a_good_quality',$userDetail['userlanguage']).'</li>';
				$body.= '</ul>';
				$body.= '<p>'.getAdminLang('On_our_website_you_will_find',$userDetail['userlanguage']).'</p>';
				
				
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>Dear <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                             <tr>
	                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
	                             		'.getAdminLang('Best_regards',$userDetail['userlanguage']).' <br>
	                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$userDetail['userlanguage']).'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';


				$this->utility->sendCIMail($to,$sub,$bodys);
			}
			/****************Remove Mail******************/
			$this->utility->setMsg('Profile text deleted','SUCCESS');	
			redirect(base_url().'admin/users/profile_text');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/profile_text');
		}
	}
	public function profile_text_deleteall()
	{
		$ids = $this->input->post('ids');
		if($ids!='')
		{
			foreach ($ids as $key => $value) {
				$userId=$value;
				if($userId > 0){	
					$this->common_model->UpdateData('feu_userdetails',array('about'=>''),array('user_id'=>$userId));
					$userDetail = $this->common_model->getAllRowMultipleJoin('usr_users',array('user_id'=>$userId),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
					/****************Remove Mail******************/
					if(!empty($userDetail))
					{
						//$to = 'sayan@digitalaptech.com';
						$to = $userDetail['email'];
						$sub = getAdminLang('Your_profile_text_has_been_removed',$userDetail['userlanguage']);
						$body= '<p>'.getAdminLang('Unfortunately_your_profile_text_has_been_removed',$userDetail['userlanguage']).'!</p>';
						$body.= '<p>'.getAdminLang('Castleevents_is_known_as_probably_the_most_exclusive',$userDetail['userlanguage']).'</p>';
						$body.= '<p>'.getAdminLang('when_writing_profile_texts',$userDetail['userlanguage']).'</p>';
						$body.= '<ul>';
						$body.= '<li>'.getAdminLang('Protect_your_anonymity',$userDetail['userlanguage']).'</li>';
						$body.= '<li>'.getAdminLang('Texts_should_be_written_in_a_good_quality',$userDetail['userlanguage']).'</li>';
						$body.= '</ul>';
						$body.= '<p>'.getAdminLang('On_our_website_you_will_find',$userDetail['userlanguage']).'</p>';
						
						
						$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
			                    <tr>
			                       <td>
			                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
			                             <tr>
			                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
			                                   <h2>Dear <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
			                                </td>
			                             </tr>
			                             <tr>
			                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
			                                   '.$body.'
			                                </td>
			                             </tr>
			                             <tr>
			                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
			                             		'.getAdminLang('Best_regards',$userDetail['userlanguage']).' <br>
			                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$userDetail['userlanguage']).'</p> 
			                             	</td>
			                             </tr>
			                          </table>
			                       </td>
			                    </tr>
			                </table>';


						$this->utility->sendCIMail($to,$sub,$bodys);
					}
				}
				/****************Remove Mail******************/
			}
			$this->utility->setMsg('Profile text deleted','SUCCESS');	
			redirect(base_url().'admin/users/profile_text');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/profile_text');
		}
	}

	public function update($enc_userID='')
	{
		if($enc_userID!='')
		{
			$archieveId=base64_decode($enc_userID);
			if($this->input->post())
			{
				$this->load->library('Utility');
				$text=$this->utility->info_cleanQuery($this->input->post('text'));
				
				$archDetails_con=array(
							'about'=>$text
					);
				$this->common_model->UpdateData('feu_userdetails',$archDetails_con,array('user_id'=>$archieveId));

				$this->utility->setMsg('Profile text update','SUCCESS');	
				redirect(base_url().'admin/users/update/'.$enc_userID);
			}

			$content_data = array();
			$content_data['profile_text'] = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$archieveId)) ;
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			//print_r($content_data); die;
			$data['content'] = $this->load->view('admin/profile_text/edit', $content_data, TRUE);
			$this->load->view('admin/layout', $data);

		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/profile_text');
		}
	}
	public function pin_text($page=''){
		$content_data = array();
		if($page=='')
		{
			$page=0;
		}
		$limit = 20;

		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['profile_text'] = $this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',$page,$limit,array('alias_path'=>'community/profil'));
		//print_r($content_data); die;
		$profile_text_list = $this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',0,5000,array('alias_path'=>'community/profil')) ;
		if($this->input->post())
		{
			if($this->input->post('search') && $this->input->post('search_name'))
			{
				$content_data['profile_text'] = $this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',$page,$limit,array('alias_path'=>'community/profil','comment'=>$this->input->post('search'),'username'=>$this->input->post('search_name')));
				$profile_text_list = $this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',0,5000,array('alias_path'=>'community/profil','comment'=>$this->input->post('search'),'username'=>$this->input->post('search_name'))) ;
		
			}
			if($this->input->post('search'))
			{
				$content_data['profile_text'] = $this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',$page,$limit,array('alias_path'=>'community/profil','comment'=>$this->input->post('search')));
				$profile_text_list =$this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',0,5000,array('alias_path'=>'community/profil','comment'=>$this->input->post('search'))) ;
		
			}
			if($this->input->post('search_name'))
			{
				$content_data['profile_text'] = $this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',$page,$limit,array('alias_path'=>'community/profil','username'=>$this->input->post('search_name')));
				$profile_text_list =$this->common_model->getAll('cmt_comments','',array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','',0,5000,array('alias_path'=>'community/profil','username'=>$this->input->post('search_name'))) ;
		
			}
		}

		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/users/pin_text';
		$config['total_rows'] = count($profile_text_list);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$content_data['link'] = $this->pagination->create_links();

		$data['content'] = $this->load->view('admin/pin_text/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function pindelete($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			$userDetail = $this->common_model->getAllRowMultipleJoin('cmt_comments',array('cmt_comments.id'=>$userId),array(array('usr_users','cmt_comments.user_id = usr_users.id'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
			$this->common_model->deleteData('cmt_comments',array('id'=>$userId));
			/****************Remove Mail******************/
			if(!empty($userDetail))
			{
				//$to = 'sayan@digitalaptech.com';
				$to = $userDetail['email'];
				$sub = getAdminLang('Your_pin_text_has_been_removed',$userDetail['userlanguage']);
				$body= '<p>'.getAdminLang('Unfortunately_your_pin_text_has_been_removed',$userDetail['userlanguage']).'!</p>';
				$body.= '<p>'.getAdminLang('Castleevents_is_known_as_probably_the_most_exclusive',$userDetail['userlanguage']).'</p>';
				$body.= '<p>'.getAdminLang('when_writing_profile_texts',$userDetail['userlanguage']).'</p>';
				$body.= '<ul>';
				$body.= '<li>'.getAdminLang('Protect_your_anonymity',$userDetail['userlanguage']).'</li>';
				$body.= '<li>'.getAdminLang('Texts_should_be_written_in_a_good_quality',$userDetail['userlanguage']).'</li>';
				$body.= '</ul>';
				$body.= '<p>'.getAdminLang('On_our_website_you_will_find',$userDetail['userlanguage']).'</p>';
				
				
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>Dear <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                             <tr>
	                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
	                             		'.getAdminLang('Best_regards',$userDetail['userlanguage']).' <br>
	                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$userDetail['userlanguage']).'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';


				$this->utility->sendCIMail($to,$sub,$bodys);
			}
			/****************Remove Mail******************/
			$this->utility->setMsg('Pin text deleted','SUCCESS');	
			redirect(base_url().'admin/users/pin_text');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/pin_text');
		}
	}

	public function pin_text_deleteall()
	{
		$ids = $this->input->post('ids');
		if($ids!='')
		{
			foreach ($ids as $key => $value) {
				$userId=$value;
				if($userId > 0){	
					$userDetail = $this->common_model->getAllRowMultipleJoin('cmt_comments',array('cmt_comments.id'=>$userId),array(array('usr_users','cmt_comments.user_id = usr_users.id'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
					//pr($userDetail);
					$this->common_model->deleteData('cmt_comments',array('id'=>$userId));
					/****************Remove Mail******************/
					if(!empty($userDetail))
					{
						//$to = 'sayan@digitalaptech.com';
						$to = $userDetail['email'];
						$sub = getAdminLang('Your_pin_text_has_been_removed',$userDetail['userlanguage']);
						$body= '<p>'.getAdminLang('Unfortunately_your_pin_text_has_been_removed',$userDetail['userlanguage']).'!</p>';
						$body.= '<p>'.getAdminLang('Castleevents_is_known_as_probably_the_most_exclusive',$userDetail['userlanguage']).'</p>';
						$body.= '<p>'.getAdminLang('when_writing_profile_texts',$userDetail['userlanguage']).'</p>';
						$body.= '<ul>';
						$body.= '<li>'.getAdminLang('Protect_your_anonymity',$userDetail['userlanguage']).'</li>';
						$body.= '<li>'.getAdminLang('Texts_should_be_written_in_a_good_quality',$userDetail['userlanguage']).'</li>';
						$body.= '</ul>';
						$body.= '<p>'.getAdminLang('On_our_website_you_will_find',$userDetail['userlanguage']).'</p>';
						
						
						$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
			                    <tr>
			                       <td>
			                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
			                             <tr>
			                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
			                                   <h2>Dear <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
			                                </td>
			                             </tr>
			                             <tr>
			                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
			                                   '.$body.'
			                                </td>
			                             </tr>
			                             <tr>
			                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
			                             		'.getAdminLang('Best_regards',$userDetail['userlanguage']).' <br>
			                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$userDetail['userlanguage']).'</p> 
			                             	</td>
			                             </tr>
			                          </table>
			                       </td>
			                    </tr>
			                </table>';


						$this->utility->sendCIMail($to,$sub,$bodys);
					}
				}
				/****************Remove Mail******************/
			}
			$this->utility->setMsg('Pin text deleted','SUCCESS');	
			redirect(base_url().'admin/users/pin_text');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/pin_text');
		}
	}

	public function pinedit($enc_userID='')
	{
		if($enc_userID!='')
		{
			$archieveId=base64_decode($enc_userID);
			if($this->input->post())
			{
				$this->load->library('Utility');
				$text=$this->utility->info_cleanQuery($this->input->post('text'));
				
				$archDetails_con=array(
							'comment'=>$text
					);
				$this->common_model->UpdateData('cmt_comments',$archDetails_con,array('id'=>$archieveId));

				$this->utility->setMsg('Pin text update','SUCCESS');	
				redirect(base_url().'admin/users/pinedit/'.$enc_userID);
			}

			$content_data = array();
			$content_data['profile_text'] = $this->common_model->getAllRow('cmt_comments',array('id'=>$archieveId),array('feu_userdetails','feu_userdetails.user_id = cmt_comments.user_id '),'cmt_comments.created DESC','','','','',array('alias_path'=>'community/profil'));
		
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$data['content'] = $this->load->view('admin/pin_text/edit', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/pin_text');
		}
	}
	public function todayexipry()
	{
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['users'] = $this->common_model->getAllMultipleJoin('charge_card',array('user_id !='=>0),array(array('usr_users','usr_users.id = charge_card.user_id')),'charge_card.date DESC') ;
		//print_r($content_data['users']); die;
		$data['content'] = $this->load->view('admin/users/todayexipry', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function verify($enc_userID='',$uri='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('feu_userdetails',array('verified'=>1),array('user_id'=>$userId));
			$this->utility->setMsg('Member verified','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function update_number()
	{
		$user_id = $this->input->post('user_id');
		$mobile_number = str_replace(' ', '', $this->input->post('mobile_number'));
		$userDetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$user_id));
		if($userDetails['mobile_number']=='' || $userDetails['mobile_number']==0)
		{
			$this->common_model->UpdateData('feu_userdetails',array('mobile_number'=>$mobile_number),array('user_id'=>$user_id));
		}
		else
		{
			$this->common_model->insertData('usr_phones',array('user_id'=>$user_id,'mobile_number'=>$mobile_number));
		}
		$this->common_model->UpdateData('usr_users',array('otp'=>''),array('id'=>$user_id));
		$this->utility->setMsg('Member verified','SUCCESS');	
		redirect(base_url().'admin/users/edit/'.base64_encode($user_id));
	}
	public function contactlist(){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$arr = array();
		$content_data['contact'] = $this->common_model->getAllMultipleJoin('feu_userdetails',array('feu_userdetails.mobile_number >'=>0),array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'usr_users.id DESC','','') ;
		$content_data['contact_new'] = $this->common_model->getAllMultipleJoin('usr_phones',array('usr_phones.mobile_number >'=>0),array(array('usr_users','usr_phones.user_id = usr_users.id'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')),'usr_users.id DESC','*,usr_phones.mobile_number') ;
		$arr = array_merge($content_data['contact_new'],$content_data['contact']);
		$content_data['contacts'] = $arr;
		$data['content'] = $this->load->view('admin/users/contactlist', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	function downloadContacts(){
		$arr = array();
		$content_data['contact'] = $this->common_model->getAllMultipleJoin('feu_userdetails',array('feu_userdetails.mobile_number >'=>0),array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'usr_users.id DESC','','') ;
		$content_data['contact_new'] = $this->common_model->getAllMultipleJoin('usr_phones',array('usr_phones.mobile_number >'=>0),array(array('usr_users','usr_phones.user_id = usr_users.id'),array('feu_userdetails','feu_userdetails.user_id = usr_users.id')),'usr_users.id DESC','*,usr_phones.mobile_number') ;
		$arr = array_merge($content_data['contact_new'],$content_data['contact']);
		//pr($arr);
		if(!empty($arr))
		{
			$csv_fields=array();
			$csv_fields[] = 'User ID';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Contact Number';
			
			$output_filename = 'Contact List.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($arr as $Result) {
				$qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) and user_id = '.$Result['user_id'].' order by b.created DESC');
		 		$membership = $qry->row_array();
		 		$star = '';
		 		if(!empty($membership))
		 		{
		 			if($membership['article_id']==4)
		 			{
		 				$star = '*';
		 			}
		 		}
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['User ID']=$Result['user_id'];
				$leadArray['Username']=$Result['username'].$star;
				$leadArray['Email']=$Result['email'];
				$leadArray['Contact Number']=$Result['mobile_number'];
				// Add row to file
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
	}
	public function paidlist($page=''){
		$content_data = array();
		if($page=='')
		{
			$page=0;
		}
		$limit = 10;

		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) order by b.created DESC limit '.$page.','.$limit);
		$activegetUserListData = $activeqry->result_array();
		$content_data['users'] = $activegetUserListData;
		//echo $this->db->last_query(); die;
		$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) order by b.created DESC');
		$userlist = $activeqry->result_array();
		if($this->input->post())
		{
			if($this->input->post('search') && $this->input->post('search_name'))
			{
				$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) AND email like "%'.$this->input->post('search').'%" AND username like "%'.$this->input->post('search_name').'%" order by b.created DESC limit '.$page.','.$limit);
				$activegetUserListData = $activeqry->result_array();
				$content_data['users'] = $activegetUserListData;
				//echo $this->db->last_query(); die;
				$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4)  AND email like "%'.$this->input->post('search').'%" AND username like "%'.$this->input->post('search_name').'%" order by b.created DESC');
				$userlist = $activeqry->result_array();
			}
			if($this->input->post('search'))
			{
				$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) AND email like "%'.$this->input->post('search').'%" order by b.created DESC limit '.$page.','.$limit);
				$activegetUserListData = $activeqry->result_array();
				$content_data['users'] = $activegetUserListData;
				//echo $this->db->last_query(); die;
				$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4)  AND email like "%'.$this->input->post('search').'%" order by b.created DESC');
				$userlist = $activeqry->result_array();
			}
			if($this->input->post('search_name'))
			{
				$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4) AND username like "%'.$this->input->post('search_name').'%" order by b.created DESC limit '.$page.','.$limit);
				$activegetUserListData = $activeqry->result_array();
				$content_data['users'] = $activegetUserListData;
				//echo $this->db->last_query(); die;
				$activeqry = $this->db->query('select * from (select * from (SELECT accounttype,email_confirmed,username,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` INNER JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a ORDER BY a.user_id DESC) as b where case when time = 365 then b.created >('.time().' - (365 * 86400)) when time = 182 then b.created >('.time().' - (182 * 86400)) end AND article_id in (5,4)  AND username like "%'.$this->input->post('search_name').'%" order by b.created DESC');
				$userlist = $activeqry->result_array();
			}
			
		}
		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/users/paidlist/';
		$config['total_rows'] = count($userlist);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$content_data['link'] = $this->pagination->create_links();

		$data['content'] = $this->load->view('admin/users/paidlist', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function authenticate($enc_userID='',$uri='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('feu_userdetails',array('reality_authenticated'=>1),array('user_id'=>$userId));
			$userDetail = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$userId),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
			//pr($userDetail);
			/****************Stop Renewal Mail******************/
			if(!empty($userDetail))
			{
				$to = $userDetail['email'];
				$sub = getAdminLang('Confirmation_of_authenticity_confirmed',$userDetail['userlanguage']);
				$body= '<p>'.getAdminLang('your_authenticity_was_confirmed',$userDetail['userlanguage']).'!</p>';
				$body.= '<p>'.getAdminLang('Thank_you_very_much',$userDetail['userlanguage']).'</p>';
				
				$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
	                    <tr>
	                       <td>
	                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
	                             <tr>
	                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
	                                   <h2>'.getAdminLang('Hello',$userDetail['userlanguage']).' <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   '.$body.'
	                                </td>
	                             </tr>
	                             <tr>
	                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
	                             		'.getAdminLang('Your_team_from_Castleevents',$userDetail['userlanguage']).' </p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';

	                //echo $bodys;die;
				$this->utility->sendCIMail($to,$sub,$bodys);
			}
			$this->utility->setMsg('Reality authenticated','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function dirToArray($dir){
  
			$result = array();
			$cdir = scandir($dir);
		   foreach ($cdir as $key => $value)
		   {
			  if (!in_array($value,array(".","..")))
			  {
				 if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
				 {
					$result[$value] = $this->dirToArray($dir . DIRECTORY_SEPARATOR . $value);
				 }
				 else
				 {
					$result[] = $value;
				 }
			  }
		   }
  		return $result;
	}
	public function createThumb($spath, $dpath, $maxd) {
	$info = getimagesize($spath);
    $mime = $info['mime'];
	//var_dump($mime);
	if($mime=='image/png'){
		
			$src = ImageCreateFromPNG($spath);
			if (!$src) {return false;} else {
		  $srcw=imagesx($src);
		  $srch=imagesy($src);
		  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
		  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
		  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
		  $thumb=imagecreatetruecolor($width, $height);
			imagealphablending($thumb, false);
		 //if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
		 // else {
			imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));
			//  }
			
				imagepng($thumb, $dpath,9);
			}
		 return true;
	}else{
	
		$src=@imagecreatefromjpeg($spath);

	if (!$src) {return false;} else {
	  $srcw=imagesx($src);
	  $srch=imagesy($src);
	  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
	  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
	  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
	  $thumb=imagecreatetruecolor($width, $height);
	// if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
	//  else {
		imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));
		//  }
		
			imagejpeg($thumb, $dpath,90);
		}
		 return true;
	}
  
 
	}
	public function avater($picval=''){
	$sizes=array('80','160','320');
	   $picdir[]=$this->dirToArray('assets');
		$avatar=$picdir[0]['userfiles']['avatars'];
				foreach($sizes as $size){
				
				$toWidth=$toHeight=$size;
				//destination path
				$folderpath = 'assets/userfiles/avatars/'.$toWidth;

				$org_path = 'assets/userfiles/avatars'; //source path
				if (!file_exists($folderpath)) { // file exist in target folder
					mkdir($folderpath, 0777, true);
				}
				$source_path = $org_path.'/'.$picval;
				$d_path = $folderpath.'/'.$picval;
				$this->createThumb($source_path,$d_path,$toWidth);
			}//end of avaters resizer
		
		return '1';
	}
	public function add_delete_date()
	{
		$user_id = $this->input->post('delete_user_id');
		$delete_date = $this->input->post('delete_date');
		if($user_id!='' && $delete_date!='')
		{
			$uri = $this->input->post('uri');
			$this->common_model->UpdateData('usr_users',array('delete_date'=>$delete_date,'cancellation_date'=>date('Y-m-d')),array('id'=>$user_id));
			$this->utility->setMsg('Member delete date updated','SUCCESS');	
		}
		redirect(base_url().str_replace('-', '/', $uri));
	}
	public function remove_delete_date($enc_userID='',$uri='')
	{
		$user_id=base64_decode($enc_userID);
		if($user_id!='')
		{
			$this->common_model->UpdateData('usr_users',array('delete_date'=>NULL,'cancellation_date'=>NULL),array('id'=>$user_id));
			$this->utility->setMsg('Member delete date removal updated','SUCCESS');	
		}
		redirect(base_url().str_replace('-', '/', $uri));
	}
	public function ban($enc_userID='',$status='',$uri='')
	{
		if($enc_userID!='')
		{
			if($status==2)
			{
				$new = 0;
				$ban_date = '0';
			}
			else
			{
				$new = 1;
				$ban_date = date('Y-m-d');
			}
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('usr_users',array('ban_status'=>$new,'ban_date'=>$ban_date),array('id'=>$userId));
			$this->utility->setMsg('Member ban status changed successfully','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
	}
	public function stop_renewal($enc_userID='',$status='',$uri='')
	{
		if($enc_userID!='')
		{
			if($status==2)
			{
				$new = 0;
			}
			else
			{
				$new = 1;
			}
			$userId=base64_decode($enc_userID);
			$this->common_model->UpdateData('usr_users',array('stop_renewal'=>$new,'pause_date'=>date('Y-m-d')),array('id'=>$userId));

			$userDetail = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$userId),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
			//pr($userDetail);
			/****************Stop Renewal Mail******************/
			if(!empty($userDetail))
			{
				if($status==1){
					$to = $userDetail['email'];
					$sub = getAdminLang('paused_automatic_debit_credit_card',$userDetail['userlanguage']);
					$body= '<p>'.getAdminLang('we_have_paused_the_automatic',$userDetail['userlanguage']).'!</p>';
					$body.= '<p>'.getAdminLang('hope_to_win_you_as_a_regular',$userDetail['userlanguage']).'</p>';
					$body.= '<p>'.getAdminLang('Your_favorite_event_organizer',$userDetail['userlanguage']).'</p>';
					
					$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
		                    <tr>
		                       <td>
		                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
		                             <tr>
		                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <h2>'.getAdminLang('Hello',$userDetail['userlanguage']).' <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
		                                </td>
		                             </tr>
		                             <tr>
		                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
		                                   '.$body.'
		                                </td>
		                             </tr>
		                             <tr>
		                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
		                             		'.getAdminLang('Your_favorite_event_organizer',$userDetail['userlanguage']).' <br>
		                             		<p style="margin:5px 0 0">Castleevents.com</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table>';

		                //echo $bodys;die;
					$this->utility->sendCIMail($to,$sub,$bodys);
				} else {
					$to = $userDetail['email'];
					$sub = getAdminLang('Continued_membership',$userDetail['userlanguage']);
					$body= '<p>'.getAdminLang('pleased_that_you_have_decided',$userDetail['userlanguage']).'!</p>';
					$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
		                    <tr>
		                       <td>
		                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
		                             <tr>
		                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <h2>'.getAdminLang('Hello',$userDetail['userlanguage']).' <span style="text-transform:capitalize">'.$userDetail['username'].'</span> </h2>
		                                </td>
		                             </tr>
		                             <tr>
		                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
		                                   '.$body.'
		                                </td>
		                             </tr>
		                             <tr>
		                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
		                             		'.getAdminLang('Your_favorite_event_organizer',$userDetail['userlanguage']).' <br>
		                             		<p style="margin:5px 0 0">Castleevents.com</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table>';

		                //echo $bodys;die;
					$this->utility->sendCIMail($to,$sub,$bodys);
				}
			}
		/****************Stop Renewal Mail******************/
			$this->utility->setMsg('Member renewal status changed successfully','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
	}
	public function having_delete_user($page=''){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['users'] = $this->common_model->getAll('usr_users',array('delete_date !='=>NULL),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),'delete_date ASC');
		$data['content'] = $this->load->view('admin/users/having_delete_user', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function direct_message($enc_userID='')
	{
		if($enc_userID!='')
		{
			$userId=base64_decode($enc_userID);
			if($this->input->post())
			{
				$type = 0;
				if($this->input->post('instant_message') && $this->input->post('email'))
				{
					$type = 1;
				}
				elseif($this->input->post('instant_message'))
				{
					$type = 2;
				}
				elseif($this->input->post('email'))
				{
					$type = 3;
				}

				if($this->input->post('test'))
				{
					/*$userId = 25267;
					$to_email = 'sayan@digitalaptech.com';
					$to_name = 'Sumit';
					$to_number = '+919748116201';*/
					$userDetail = $this->common_model->getAllRow('usr_users',array('id'=>$userId),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
					$langId = 2;
					$userId = 19624;
					$to_email = 'info@castleevents.com';
					$to_name = 'Andrej';
					$to_number = '+415880285';
				}
				else
				{
					$userId = $userId;
					$userDetail = $this->common_model->getAllRow('usr_users',array('id'=>$userId),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
					$to_email = $userDetail['email'];
					$to_name = $userDetail['username'];
					$langId = $userDetail['userlanguage'];
					$to_number = '';
					$userPhones = $this->common_model->getAllRow('usr_phones',array('user_id'=>$userId));
					if($userDetail['mobile_number']!='')
					{
						if(strpos($userDetail['mobile_number'],'+') === false)
						{
							$to_number = '+'.$userDetail['mobile_number'];
						}
						else
						{
							$to_number = $userDetail['mobile_number'];
						}
					}
					elseif($userPhones)
					{
						if(strpos($userPhones['mobile_number'],'+') === false)
						{
							$to_number = '+'.$userPhones['mobile_number'];
						}
						else
						{
							$to_number = $userPhones['mobile_number'];
						}
					}
				}

				$array = array(
								'date'=>date('Y-m-d'),
								'category'=>$this->input->post('sms_msg'),
								'title'=>'USER PROFILE',
								'subject'=>$this->input->post('subject')?$this->input->post('subject'):'SMS',
								'message'=>$this->input->post('message') ? $this->input->post('message') : $this->input->post('message1'),
								'type'=>$type,
								'send_to_paid_only'=>0,
								'priority'=>$this->input->post('priority')?$this->input->post('priority'):0,
								'event_id'=>0,
								'language_id'=>2
							);
				$communicator_id = $this->common_model->insertData('communicator',$array);
				//echo $this->db->last_query();die;
				$cont='<!DOCTYPE html>
	                    <html>
	                       <head>
	                          <meta charset="utf-8">
	                          <meta name="viewport" content="width=device-width">
	                          <meta http-equiv="X-UA-Compatible" content="IE=edge">
	                          <title>Varification</title>
	                          <style type="text/css">
	                             html,
	                             body {
	                             margin: 0 auto !important;
	                             padding: 0 !important;         
	                             width: 100% !important;
	                             }
	                             
	                             * {
	                             -ms-text-size-adjust: 100%;
	                             -webkit-text-size-adjust: 100%;
	                             }
	                             
	                             div[style*="margin: 16px 0"] {
	                             margin:0 !important;
	                             }
	                             
	                             table,
	                             td {
	                             mso-table-lspace: 0pt !important;
	                             mso-table-rspace: 0pt !important;
	                             }
	                          
	                             table {
	                             border-spacing: 0 !important;
	                             border-collapse: collapse !important;
	                             table-layout: fixed !important;
	                             Margin: 0 auto !important;
	                             }
	                             table table table {
	                             table-layout: auto; 
	                             }
	                           
	                             img {
	                             -ms-interpolation-mode:bicubic;
	                             }
	                            
	                             .mobile-link--footer a,
	                             a[x-apple-data-detectors] {
	                             color:inherit !important;
	                             text-decoration: underline !important;
	                             }
	                             @media only screen and (max-width: 767px)
	                             {
	                             	.content_td{padding: 40px 0 !important; }
	                             }
	                          </style>
	                         
	                          <style>
	                            
	                             .button-td,
	                             .button-a {
	                             transition: all 100ms ease-in;
	                             }
	                             .button-td:hover,
	                             .button-a:hover {
	                             background: #555555 !important;
	                             border-color: #555555 !important;
	                             }
	                          </style>
	                       </head>
	                       <body width="100%" style="Margin: 0;">
	                          <center style="width: 100%;">
	                             <div style="max-width: 90%; margin: 40px auto;">
	                               <table cellspacing="0" cellpadding="0" border="0" width="100%" style="max-width: 90%">
					                    <tr>
					                       <td>
					                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
					                             <tr>
					                                <td class="content_td" style="padding: 40px 0 0 40px; font-family: helvetica; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #000;">
					                                   <h2 style="font-weight:normal;">'.getAdminLang('Dear',$langId).' <span style="text-transform:capitalize">'.$to_name.'</span> 
					                                   </h2>
					                                </td>
					                                <td>
					                                   <a href="'.base_url().'" style="float:right;"><img src="'.base_url().'newsletter_image/crown.gif" width="70" alt="Castleevents" border="0"></a>
					                                </td>
					                             </tr>
					                             <tr>
					                                <td class="content_td" colspan="2" style="font-family: sans-serif; color: #000; padding: 40px; font-size: 16px; line-height: 30px;">
					                                   <p>'.$this->input->post('message').'
					                                   </p>
					                                   <br>
					                                </td>
					                             </tr>
					                             <tr>
					                             	<td class="content_td" colspan="2" align="" style="font-family: sans-serif; color: 000; padding: 20px 40px;">
					                             		<p style="padding-bottom: 20px; margin: 0">'.getAdminLang('Kind_regards',$langId).' </p>
					                             		<p style="margin:10px 0 0; font-weight: bold; ">CASTLEEVENTS.COM</p>
					                             		<p style="margin: 5px 0;">The Worlds Leading Eyes Wide Shut Parties</p>
					                             		<p style="margin: 5px 0;">info@castleevents.com </p>
					                             	</td>
					                             </tr>
					                          </table>
					                       </td>
					                    </tr>
					                </table></div>
	                              </center>
	                           </body>
	                        </html>';
	                        //echo $cont;die;
				if($this->input->post('email') || $this->input->post('instant_message'))
				{
					$from='info@castleevents.com';
					$email_config = Array(
						'protocol' => 'smtp',
			              'smtp_host' => 'smtp.sendgrid.net',
			              'smtp_user' => 'apikey',
			              'smtp_pass' => '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',
			              'smtp_port' => 587,
			              'mailtype' => 'html',
			              'priority'=>$this->input->post('priority')?$this->input->post('priority'):3,
			              'crlf' => "rn",
			              'newline' => "rn",
			              'charset' => 'utf-8',
			              'wordwrap' => TRUE
					);

					$this->load->library('email');
					$this->email->initialize($email_config);
					$this->email->from($from, 'CASTLEEVENTS');
					$this->email->bcc('info@castleevents.com','CASTLEEVENTS'); 
					//$this->email->bcc('sayan@digitalaptech.com','Sumit'); 
					$this->email->to($to_email,$to_name); 
					//$this->email->to($value['email'],$value['username']); 
					$this->email->subject($this->input->post('subject'));
					$this->email->message($cont);
					$mail = $this->email->send();
				}
				if($this->input->post('instant_message'))
				{
					$adminDetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('email'=>'info@castleevents.com'),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
					$meg_conv_instId = $this->common_model->insertData('msg_conversations',array('created'=>time()));
					$meg_conv_user_instId = $this->common_model->insertData('msg_conversations_users',array('conversation_id'=>$meg_conv_instId,'user_id'=>$userId,'latest_read'=>0));
					$meg_message_instId = $this->common_model->insertData('msg_messages',array('created'=>time(),'conversation_id'=>$meg_conv_instId,'from_user_id'=>$adminDetails['user_id'],'text'=>$this->input->post('message')));
				}
				if($this->input->post('sms'))
				{
					if($to_number!='')
					{
						$url = "https://api.budgetsms.net/sendsms/?username=CASTLE&handle=ba04586987ec104e74b2374f59d51593&userid=18554&msg=".str_replace('%C2%A0','+',urlencode(html_entity_decode(strip_tags($this->character_resolve($this->input->post('message1'))),ENT_QUOTES)))."&from=Castle&to=".$to_number; 
						//$url = "https://bulksms.vsms.net/eapi/submission/send_sms/2/2.0?username=Sakrileg&password=ppp79111&message=".str_replace('%C2%A0','+',urlencode(html_entity_decode(strip_tags($this->character_resolve($this->input->post('message'))),ENT_QUOTES)))."&msisdn=".$to_number; 
	                    $curl = curl_init($url);
	                    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
	                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
	                    $result = curl_exec($curl);
					}
					
				}
				$array = array(
								'communicator_id'=>$communicator_id,
								'user_id'=>$userId,
								'order_id'=>0,
							);
				$this->common_model->insertData('communicator_to_user',$array);

				$this->utility->setMsg('Message send successfully','SUCCESS');
				redirect(base_url().'admin/users/direct_message/'.$enc_userID);
			}

			$content_data = array();
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$content_data['userDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$userId),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			
			$to_number = '';
			$userPhones = $this->common_model->getAllRow('usr_phones',array('user_id'=>$userId));
			if($content_data['userDetails']['mobile_number']!='')
			{
				if(strpos($content_data['userDetails']['mobile_number'],'+') === false)
				{
					$to_number = '+'.$content_data['userDetails']['mobile_number'];
				}
				else
				{
					$to_number = $content_data['userDetails']['mobile_number'];
				}
			}
			elseif($userPhones)
			{
				if(strpos($userPhones['mobile_number'],'+') === false)
				{
					$to_number = '+'.$userPhones['mobile_number'];
				}
				else
				{
					$to_number = $userPhones['mobile_number'];
				}
			}
			$content_data['to_number'] = $to_number;
			$data['content'] = $this->load->view('admin/users/direct_message', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/users/alllist');
		}
	}
	public function send_message()
	{
		
		if($this->input->post())
		{
			$userId=$this->input->post('user_id');
			$uri=$this->input->post('uri');
			$type = 0;
			if($this->input->post('instant_message') && $this->input->post('email'))
			{
				$type = 1;
			}
			elseif($this->input->post('instant_message'))
			{
				$type = 2;
			}
			elseif($this->input->post('email'))
			{
				$type = 3;
			}

			if($this->input->post('test'))
			{
				/*$userId = 25267;
				$to_email = 'sayan@digitalaptech.com';
				$to_name = 'Sumit';
				$to_number = '+919748116201';*/
				$userDetail = $this->common_model->getAllRow('usr_users',array('id'=>$userId),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
				$langId = 2;
				$userId = 19624;
				$to_email = 'alorenc@me.com';
				$to_name = 'Andrej';
				$to_number = '+415880285';
			}
			else
			{
				$userId = $userId;
				$userDetail = $this->common_model->getAllRow('usr_users',array('id'=>$userId),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
				$to_email = $userDetail['email'];
				$to_name = $userDetail['username'];
				$langId = $userDetail['userlanguage'];
				$to_number = '';
				$userPhones = $this->common_model->getAllRow('usr_phones',array('user_id'=>$userId));
				if($userDetail['mobile_number']!='')
				{
					if(strpos($userDetail['mobile_number'],'+') === false)
					{
						$to_number = '+'.$userDetail['mobile_number'];
					}
					else
					{
						$to_number = $userDetail['mobile_number'];
					}
				}
				elseif($userPhones)
				{
					if(strpos($userPhones['mobile_number'],'+') === false)
					{
						$to_number = '+'.$userPhones['mobile_number'];
					}
					else
					{
						$to_number = $userPhones['mobile_number'];
					}
				}
			}

			$array = array(
							'date'=>date('Y-m-d'),
							'category'=>$this->input->post('sms_msg'),
							'title'=>'USER PROFILE',
							'subject'=>$this->input->post('subject')?$this->input->post('subject'):'SMS',
							'message'=>$this->input->post('message'),
							'type'=>$type,
							'send_to_paid_only'=>0,
							'priority'=>$this->input->post('priority')?$this->input->post('priority'):0,
							'event_id'=>0,
							'language_id'=>2
						);
			$communicator_id = $this->common_model->insertData('communicator',$array);
			//echo $this->db->last_query();die;
			$cont='<!DOCTYPE html>
                    <html>
                       <head>
                          <meta charset="utf-8">
                          <meta name="viewport" content="width=device-width">
                          <meta http-equiv="X-UA-Compatible" content="IE=edge">
                          <title>Varification</title>
                          <style type="text/css">
                             html,
                             body {
                             margin: 0 auto !important;
                             padding: 0 !important;         
                             width: 100% !important;
                             }
                             
                             * {
                             -ms-text-size-adjust: 100%;
                             -webkit-text-size-adjust: 100%;
                             }
                             
                             div[style*="margin: 16px 0"] {
                             margin:0 !important;
                             }
                             
                             table,
                             td {
                             mso-table-lspace: 0pt !important;
                             mso-table-rspace: 0pt !important;
                             }
                          
                             table {
                             border-spacing: 0 !important;
                             border-collapse: collapse !important;
                             table-layout: fixed !important;
                             Margin: 0 auto !important;
                             }
                             table table table {
                             table-layout: auto; 
                             }
                           
                             img {
                             -ms-interpolation-mode:bicubic;
                             }
                            
                             .mobile-link--footer a,
                             a[x-apple-data-detectors] {
                             color:inherit !important;
                             text-decoration: underline !important;
                             }
                             @media only screen and (max-width: 767px)
                             {
                             	.content_td{padding: 40px 0 !important; }
                             }
                          </style>
                         
                          <style>
                            
                             .button-td,
                             .button-a {
                             transition: all 100ms ease-in;
                             }
                             .button-td:hover,
                             .button-a:hover {
                             background: #555555 !important;
                             border-color: #555555 !important;
                             }
                          </style>
                       </head>
                       <body width="100%" style="Margin: 0;">
                          <center style="width: 100%;">
                             <div style="max-width: 90%; margin: 40px auto;">
                               <table cellspacing="0" cellpadding="0" border="0" width="100%" style="max-width: 90%">
				                    <tr>
				                       <td>
				                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
				                             <tr>
					                                <td style="padding: 40px; font-family: helvetica; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #000;">
					                                   <h2 style="font-weight:normal;">'.getAdminLang('Dear',$langId).' <span style="text-transform:capitalize">'.$to_name.'</span> 
					                                   </h2>
					                                </td>
					                                <td>
					                                   <a href="'.base_url().'" style="float:right;"><img src="'.base_url().'newsletter_image/crown.gif" width="70" alt="Castleevents" border="0"></a>
					                                </td>
					                             </tr>
					                             <tr>
					                                <td colspan="2" style="font-family: sans-serif; color: #000; padding: 0px 180px 40px 40px; font-size: 16px; line-height: 30px;">
					                                   <p>'.$this->input->post('message').'
					                                   </p>
					                                   <br>
					                                </td>
					                             </tr>
					                             <tr>
					                             	<td class="content_td" colspan="2" align="" style="font-family: sans-serif; color: 000; padding: 20px 40px;">
					                             		<p style="padding-bottom: 20px; margin: 0">'.getAdminLang('Kind_regards',$langId).' </p>
					                             		<p style="padding-bottom: 20px; margin: 0">'.getAdminLang('your_castleevents_team_communicator',$langId).' </p>
					                             		<p style="margin:10px 0 0; font-weight: bold; ">CASTLEEVENTS.COM</p>
					                             		<p style="margin: 5px 0;">The Worlds Leading Eyes Wide Shut Parties</p>
					                             		<p style="margin: 5px 0;">info@castleevents.com </p>
					                             	</td>
					                             </tr>
				                          </table>
				                       </td>
				                    </tr>
				                </table></div>
                              </center>
                           </body>
                        </html>';
			if($this->input->post('email') || $this->input->post('instant_message'))
			{
				$from='info@castleevents.com';
				$email_config = Array(
					'protocol' => 'smtp',
		              'smtp_host' => 'smtp.sendgrid.net',
		              'smtp_user' => 'apikey',
		              'smtp_pass' => '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',
		              'smtp_port' => 587,
		              'mailtype' => 'html',
		              'priority'=>$this->input->post('priority')?$this->input->post('priority'):3,
		              'crlf' => "rn",
		              'newline' => "rn",
		              'charset' => 'utf-8',
		              'wordwrap' => TRUE
				);

				$this->load->library('email');
				$this->email->initialize($email_config);
				$this->email->from($from, 'CASTLEEVENTS');
				$this->email->bcc('info@castleevents.com','CASTLEEVENTS'); 
				//$this->email->to('testdevloper007@gmail.com','Andrej'); 
				$this->email->to($to_email,$to_name); 
				//$this->email->to($value['email'],$value['username']); 
				$this->email->subject($this->input->post('subject'));
				$this->email->message($cont);
				$mail = $this->email->send();
			}
			if($this->input->post('instant_message'))
			{
				$adminDetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('email'=>'info@castleevents.com'),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
				$meg_conv_instId = $this->common_model->insertData('msg_conversations',array('created'=>time()));
				$meg_conv_user_instId = $this->common_model->insertData('msg_conversations_users',array('conversation_id'=>$meg_conv_instId,'user_id'=>$userId,'latest_read'=>0));
				$meg_message_instId = $this->common_model->insertData('msg_messages',array('created'=>time(),'conversation_id'=>$meg_conv_instId,'from_user_id'=>$adminDetails['user_id'],'text'=>$this->input->post('message')));
			}
			if($this->input->post('sms'))
			{
				if($to_number!='')
				{
					$url = "https://api.budgetsms.net/sendsms/?username=CASTLE&handle=ba04586987ec104e74b2374f59d51593&userid=18554&msg=".str_replace('%C2%A0','+',urlencode(html_entity_decode(strip_tags($this->character_resolve($this->input->post('message'))),ENT_QUOTES)))."&from=Castle&to=".$to_number; 
					//$url = "https://bulksms.vsms.net/eapi/submission/send_sms/2/2.0?username=Sakrileg&password=ppp79111&message=".str_replace('%C2%A0','+',urlencode(html_entity_decode(strip_tags($this->character_resolve($this->input->post('message'))),ENT_QUOTES)))."&msisdn=".$to_number; 
	                $curl = curl_init($url);
	                curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
	                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
	                $result = curl_exec($curl);
	            }
			}
			$array = array(
							'communicator_id'=>$communicator_id,
							'user_id'=>$userId,
							'order_id'=>0,
						);
			$this->common_model->insertData('communicator_to_user',$array);

			$this->utility->setMsg('Message send successfully','SUCCESS');
			redirect(base_url().str_replace('-', '/', $uri));
		}
		
	}
	public function character_resolve($body) {
		$special_chrs = array(
		  'Δ'=>'0xD0', 'Φ'=>'0xDE', 'Γ'=>'0xAC', 'Λ'=>'0xC2', 'Ω'=>'0xDB',
		  'Π'=>'0xBA', 'Ψ'=>'0xDD', 'Σ'=>'0xCA', 'Θ'=>'0xD4', 'Ξ'=>'0xB1',
		  '¡'=>'0xA1', '£'=>'0xA3', '¤'=>'0xA4', '¥'=>'0xA5', '§'=>'0xA7',
		  '¿'=>'0xBF', 'Ä'=>'0xC4', 'Å'=>'0xC5', 'Æ'=>'0xC6', 'Ç'=>'0xC7',
		  'É'=>'0xC9', 'Ñ'=>'0xD1', 'Ö'=>'0xD6', 'Ø'=>'0xD8', 'Ü'=>'0xDC',
		  'ß'=>'0xDF', 'à'=>'0xE0', 'ä'=>'0xE4', 'å'=>'0xE5', 'æ'=>'0xE6',
		  'è'=>'0xE8', 'é'=>'0xE9', 'ì'=>'0xEC', 'ñ'=>'0xF1', 'ò'=>'0xF2',
		  'ö'=>'0xF6', 'ø'=>'0xF8', 'ù'=>'0xF9', 'ü'=>'0xFC',
		);

		$ret_msg = '';
		if( mb_detect_encoding($body, 'UTF-8') != 'UTF-8' ) {
		    $body = utf8_encode($body);
		}
		for ( $i = 0; $i < mb_strlen( $body, 'UTF-8' ); $i++ ) {
		    $c = mb_substr( $body, $i, 1, 'UTF-8' );
		    if( isset( $special_chrs[ $c ] ) ) {
		      $ret_msg .= chr( $special_chrs[ $c ] );
		    }
		    else {
		      $ret_msg .= $c;
		    }
		}
		return $ret_msg;
	}
	public function order_delete($enc_userID='',$uri='')
	{
		if($enc_userID!='')
		{
			$orderId=base64_decode($enc_userID);
			$this->common_model->deleteData('shop_orders',array('order_id'=>$orderId));
			$this->utility->setMsg('Order deleted','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
	}
	public function downgrade_membership()
	{
		$downgrade_user_id = $this->input->post('downgrade_user_id');
		$uri = $this->input->post('uri');
		$downgrade_membership_value = $this->input->post('downgrade_membership_value');
		if($downgrade_membership_value > 0)
		{
			$userdetails = $this->common_model->getAllRow('usr_users',array('id'=>$downgrade_user_id), array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
			if($userdetails)
			{
				$orderdetails = $this->common_model->getAllRow('shop_orders',array('invoiceAddress'=>$userdetails['email'],'payed'=>1,'is_booking'=>0),'','created DESC');

				$base_full_details = $this->common_model->getAllRow('shop_articles',array('id'=>5));
				$base_half_details = $this->common_model->getAllRow('shop_new_articles',array('alias'=>'basic'));
				//pr($orderdetails);
				if($orderdetails)
				{
					$cartdetails = $this->common_model->getAllRow('shop_carts', array('id'=>$orderdetails['cart_id']));
					/*if($downgrade_membership_value == 1)
					{
						$total_base = $base_half_details['base_price'];
						$time = 182;
					}
					else
					{
						$total_base = $base_full_details['base_price'];
						$time = 365;
					}
					$payment_fee = ($total_base*2.5)/100;
					$total_sum = 0;
					$vat = 0;
					if($orderdetails['vat'] > 0)
					{
						$vat = (($total_base + $payment_fee)*7.7)/100;
					}
					$total_sum = ($total_base + $payment_fee + $vat);
					$this->common_model->UpdateData('shop_orders',array('total_base'=>$total_base,'payment_fee'=>$payment_fee,'vat'=>$vat,'total_sum'=>$total_sum,'time'=>$time),array('order_id'=>$orderdetails['order_id']));
					$this->common_model->UpdateData('shop_articles_carts',array('article_id'=>5),array('cart_id'=>$orderdetails['cart_id']));*/
					$downgrade_date = date('Y-m-d', ($orderdetails['created'] + ($orderdetails['time'] * 86400)));
					$this->common_model->insertData('usr_downgraded', array('users_id'=>$cartdetails['user_id'], 'membership_type'=>$downgrade_membership_value, 'downgrade_date'=>$downgrade_date));

					$to = $userdetails['email'];
					$sub = getAdminLang('Your_membership_status_has_just_been_changed',$userdetails['userlanguage']);
					$body= '<p>'.getAdminLang('This_change_will_take_effect_on',$userdetails['userlanguage']).'!</p>';
					$body.= '<p>'.getAdminLang('Many_thanks_for_your_loyalty',$userdetails['userlanguage']).'!</p>';
					$body.= '<p>'.getAdminLang('We_appreciate_very_much',$userdetails['userlanguage']).'</p>';
					$body.= '<p>'.getAdminLang('Please_do_not_hesitate_to_contact',$userdetails['userlanguage']).'</p>';
					
					
					$bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
		                    <tr>
		                       <td>
		                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
		                             <tr>
		                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <h2>Dear <span style="text-transform:capitalize">'.$userdetails['username'].'</span> </h2>
		                                </td>
		                             </tr>
		                             <tr>
		                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
		                                   '.$body.'
		                                </td>
		                             </tr>
		                             <tr>
		                             	<td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
		                             		'.getAdminLang('Best_regards',$userdetails['userlanguage']).' <br>
		                             		<p style="margin:5px 0 0">'.getAdminLang('Your_team_of_castleevents',$userdetails['userlanguage']).'</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table>';
		                //echo $bodys; die;
						$this->utility->sendOrderMail($to,$sub,$bodys);
				}
				else
				{
					$this->utility->setMsg('Order not found','ERROR');	
					redirect(base_url().str_replace('-', '/', $uri));
				}
			}
			$this->utility->setMsg('Membership downgrade successfully','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
		else
		{
			$this->utility->setMsg('No membership selected','ERROR');	
			redirect(base_url().str_replace('-', '/', $uri));
		}
	}

	public function free_users($page=''){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$free_users = $this->common_model->getAll('usr_users',array('free_member'=>1),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),'usr_users.created DESC');
		foreach ($free_users as $key => $value) {
			$approved_images = $this->common_model->getAll('sys_files',array('filename !='=>'','free_membership_image'=>1,'accepted'=>1,'ugal_images.user_id'=>$value['user_id']),array('ugal_images','ugal_images.file_id = sys_files.id'),'sys_files.created DESC','*,sys_files.created,sys_files.id');
			if(count($approved_images)==3){
				$free_users[$key]['approved'] = 1;
			}
		}
		$content_data['free_users'] = $free_users;
		$data['content'] = $this->load->view('admin/users/free_members', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function delete_pics_profile()
	{
		//pr($this->input->post('image_ids'));
		if($this->input->post('image_ids'))
		{
			$image_ids = explode(',',$this->input->post('image_ids'));
			//pr($image_ids);
			foreach ($image_ids as $key => $ugalId) {
				$fileFromuserDetails = $this->common_model->getAllRowMultipleJoin('sys_files',array('sys_files.id'=>$ugalId),array(array('feu_userdetails','feu_userdetails.avatar_file_id = sys_files.id'),array('usr_users','usr_users.id = feu_userdetails.user_id')));
				if(!empty($fileFromuserDetails['user_id']))
				{
					$userdata = $fileFromuserDetails;
				}
				else
				{
					$filesFromUserData = $this->common_model->getAllRowMultipleJoin('sys_files',array('sys_files.id'=>$ugalId),array(array('ugal_images','ugal_images.file_id = sys_files.id'),array('feu_userdetails','feu_userdetails.user_id = ugal_images.user_id'),array('usr_users','usr_users.id = feu_userdetails.user_id')));
					if(!empty($filesFromUserData))
					{
						$userdata = $filesFromUserData;
					}
					else
					{
						$userdata = array();
					}
				}
				//pr($userdata);
				if($userdata['filename']=='' && $userdata['temp_name']!=''){
					$this->common_model->UpdateData('sys_files',array('temp_name'=>''),array('id'=>$ugalId));
				} else if($userdata['filename']=='' && $userdata['temp_name']==''){
					$this->common_model->deleteData('ugal_images',array('file_id'=>$ugalId));
					$this->common_model->deleteData('sys_files',array('id'=>$ugalId));
					$this->common_model->deleteData('notification',array('file_id'=>$ugalId));
				}else{
					$this->common_model->deleteData('ugal_images',array('file_id'=>$ugalId));
					$this->common_model->deleteData('sys_files',array('id'=>$ugalId));
					$this->common_model->deleteData('notification',array('file_id'=>$ugalId));
				}
			}
			$this->utility->setMsg('Image rejected','SUCCESS');	
			redirect(base_url().str_replace('-', '/', $this->input->post('uri')));
			//redirect(base_url().'admin/dashboard/allPicture');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().str_replace('-', '/', $this->input->post('uri')));
			//redirect(base_url().'admin/dashboard');
		}
	}
	public function blockedusers()
	{
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$qry = $this->db->query("SELECT *, `usr_users`.`created` as `registered`, `usr_block`.`created` as `blocked_at`,feu_userdetails.username, a.username as blocking_name FROM `usr_block` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_block`.`to_id` LEFT JOIN `usr_users` ON `usr_users`.`id` = `feu_userdetails`.`user_id` LEFT JOIN `feu_userdetails` a ON a.`user_id` = `usr_block`.`from_id` ORDER BY `usr_block`.`created` DESC");

		//$content_data['blocekdusers'] = $this->common_model->getAllMultipleJoin('usr_block','',array(array('feu_userdetails', 'feu_userdetails.user_id = usr_block.to_id'),array('usr_users', 'usr_users.id = feu_userdetails.user_id')),'usr_block.created DESC','*, usr_users.created as registered, usr_block.created as blocked_at') ;

		$content_data['blocekdusers'] = $qry->result_array();
		//echo $this->db->last_query();die;
		//echo '<pre>';print_r($content_data['blocekdusers']); die;
		$data['content'] = $this->load->view('admin/users/blockedusers', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function activity_to_premium($page=''){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id'));

		$qry = $this->db->query("SELECT * FROM (SELECT usr_activity_to_premium.*,feu_userdetails.username, usr_users.email,feu_userdetails.user_id FROM `usr_activity_to_premium` LEFT JOIN `usr_users` ON `usr_activity_to_premium`.`users_id` = `usr_users`.`id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` ORDER BY `created_at` DESC) a GROUP BY user_id");

		$users = $qry->result_array();

		//echo $this->db->last_query();die;
		if($users){
			foreach ($users as $key => $user) {
				$user_membership = $this->common_model->getAllRowMultipleJoin('shop_orders', array('shop_orders.is_booking'=>0, 'shop_orders.cancelled'=>0, 'payed'=>1, 'user_id'=>$user['user_id']), array(array('shop_carts', 'shop_carts.id = shop_orders.cart_id'), array('shop_articles_carts', 'shop_articles_carts.cart_id = shop_carts.id')), 'shop_carts.created DESC');
				$article_id = 0;
				if($user_membership){
					$article_id = $user_membership['article_id'];
				}
				//pr($user_membership);
				if($article_id != 4){
					unset($users[$key]);
				}
			}
		}
		$content_data['users'] = $users;

		$data['content'] = $this->load->view('admin/users/activity_to_premium', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}

		public function ajaxUserReceivedMessage($enc_userID){
		if($this->input->post()){
            //dd($req->post());
            $userId=base64_decode($enc_userID);
            $draw = $this->input->post('draw');
            $row = $this->input->post('start');
            $rowperpage = $this->input->post('length'); // Rows display per page
            $columnIndex = $this->input->post('order')[0]['column']; // Column index
            $columnName = $this->input->post('columns')[$columnIndex]['data'] ? $this->input->post('columns')[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $this->input->post('order')[0]['dir']; // asc or desc
            
            if($columnName == 'slno') {
                $columnName = 'msg_messages.created';
                $columnSortOrder = 'DESC';
            }
            if($columnName == 'created') {
                $columnName = 'msg_messages.created';
                $columnSortOrder = 'DESC';
            }

            $orderClause = $columnName.' '.$columnSortOrder;
            $searchValue = $_POST['search']['value']; // Search value
            ## Total number of records without filtering
            $receivedWhere = "(text !='' OR image_path != '') AND msg_conversations_users.user_id =".$userId;
            if($searchValue != ''){
			   $receivedWhere .= " AND (username like '%".$searchValue."%' or 
			      text like '%".$searchValue."%' ) ";
			}
            $testtotalRecordSql = $this->common_model->getAllMultipleJoin('msg_messages',$receivedWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','*,msg_messages.created as msg_create');
            $testtotalRecord = count($testtotalRecordSql);
            ## Total number of record with filtering
            $testtotalRecordwithFilterSql = $this->common_model->getAllMultipleJoin('msg_messages',$receivedWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','*,msg_messages.created as msg_create');
            $testtotalRecordwithFilter = count($testtotalRecordwithFilterSql);
            ## Fetch records
            //echo $orderClause.'='.$row.'='.$rowperpage; die;
            $tests = $this->common_model->getAllMultipleJoin('msg_messages',$receivedWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),$orderClause,'*,msg_messages.created as msg_create','', $row, $rowperpage);

            //echo $tests->toSql(); die;
            //echo '<pre>';print_r($tests);die;
            $data = array();
            $status_btn = '';
            $suspend_btn = '';
            $suspend_btn = '';
            if($tests){
                foreach($tests as $key => $test){
                	$file_exist = 0;
                	$image = '';
	                if($test['image_path']!=''){
	                    $file_exist_exp = explode('assets/userfiles/img/message/', $test['image_path']);
	                    if(count($file_exist_exp)>0){
	                      	if(strlen($file_exist_exp[1]>1)){
	                        	$file_exist = 1;
	                      	}
	                    }
	                }	                
	                if(($test['text']!='' && $test['image_path']=='') || $file_exist==1){
                      	if($test['image_path']){ 
                      		$image = '<a class="downloadAnchor" href="'.base_url().str_replace('assets/userfiles/img/message/', 'message_big/', $test['image_path']).'" download><img src="'.base_url().$test['image_path'].'"></a>'; 
                  		}
                    }
                    if(file_exists(FCPATH.'assets/userfiles/'.$test['path'].'/'.$test['filename'].'.'.$test['extension']))
                    {
                      $imageFile = base_url().'assets/userfiles/'.$test['path'].'/'.$test['filename'].'.'.$test['extension'];
                    }
                    else
                    {
                      $imageFile = base_url().'assets/images/default-avatar.jpg';
                    }
                    $data[] = array( 
                        "slno"=>$key + $row + 1,
                        "created"=>date('d-m-Y', $test['msg_create']),
                        "username"=>'<a href="'.base_url().'admin/users/edit/'.base64_encode($test['user_id']).'" target="_blank"><img class="direct-chat-img" src="'.$imageFile.'" title=""><br/>'.$test['username'].'</a>',
                        "text"=>$test['text'].'<p>'.$image.'</p>'
                    );
                }
            }
            

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $testtotalRecord,
                "iTotalDisplayRecords" => $testtotalRecordwithFilter,
                "aaData" => $data
            );

            echo json_encode($response);die;
        }
	}

	public function ajaxUserSendMessage($enc_userID){
		if($this->input->post()){
			$userId=base64_decode($enc_userID);
            //dd($req->post());
            $draw = $this->input->post('draw');
            $row = $this->input->post('start');
            $rowperpage = $this->input->post('length'); // Rows display per page
            $columnIndex = $this->input->post('order')[0]['column']; // Column index
            $columnName = $this->input->post('columns')[$columnIndex]['data'] ? $this->input->post('columns')[$columnIndex]['data'] : 'id'; // Column name
            $columnSortOrder = $this->input->post('order')[0]['dir']; // asc or desc
            $searchValue = $_POST['search']['value']; // Search value
            if($columnName == 'slno') {
                $columnName = 'msg_messages.created';
                $columnSortOrder = 'DESC';
            }
            if($columnName == 'created') {
                $columnName = 'msg_messages.created';
                $columnSortOrder = 'DESC';
            }

            $orderClause = $columnName.' '.$columnSortOrder;
            ## Total number of records without filtering
            $givenWhere = "(text !='' OR image_path != '') AND feu_userdetails.user_id > 0 AND msg_messages.from_user_id =".$userId;
            if($searchValue != ''){
			   $givenWhere .= " AND (username like '%".$searchValue."%' or 
			      text like '%".$searchValue."%' ) ";
			}
            $testtotalRecordSql = $this->common_model->getAllMultipleJoin('msg_messages',$givenWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_conversations_users.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','*,msg_messages.created as msg_create');
            $testtotalRecord = count($testtotalRecordSql);
            ## Total number of record with filtering
            $testtotalRecordwithFilterSql = $this->common_model->getAllMultipleJoin('msg_messages',$givenWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_conversations_users.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','*,msg_messages.created as msg_create');
            $testtotalRecordwithFilter = count($testtotalRecordwithFilterSql);
            ## Fetch records
            //echo $orderClause.'='.$row.'='.$rowperpage; die;
            $tests = $this->common_model->getAllMultipleJoin('msg_messages',$givenWhere,array(array('msg_conversations_users','msg_messages.conversation_id = msg_conversations_users.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_conversations_users.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),$orderClause,'*,msg_messages.created as msg_create, msg_conversations_users.user_id','', $row, $rowperpage);

            //echo $this->db->last_query(); die;
            //echo '<pre>';print_r($tests);die;
            $data = array();
            $status_btn = '';
            $suspend_btn = '';
            $suspend_btn = '';
            if($tests){
                foreach($tests as $key => $test){
                	$file_exist = 0;
                	$image = '';
	                if($test['image_path']!=''){
	                    $file_exist_exp = explode('assets/userfiles/img/message/', $test['image_path']);
	                    if(count($file_exist_exp)>0){
	                      	if(strlen($file_exist_exp[1]>1)){
	                        	$file_exist = 1;
	                      	}
	                    }
	                }	                
	                if(($test['text']!='' && $test['image_path']=='') || $file_exist==1){
                      	if($test['image_path']){ 
                      		$image = '<a class="downloadAnchor" href="'.base_url().str_replace('assets/userfiles/img/message/', 'message_big/', $test['image_path']).'" download><img src="'.base_url().$test['image_path'].'"></a>'; 
                  		}
                    }
                    if(file_exists(FCPATH.'assets/userfiles/'.$test['path'].'/'.$test['filename'].'.'.$test['extension']) && $test['filename'])
                    {
                      $imageFile = base_url().'assets/userfiles/'.$test['path'].'/'.$test['filename'].'.'.$test['extension'];
                    }
                    else
                    {
                      $imageFile = base_url().'assets/images/default-avatar.jpg';
                    }
                    $data[] = array( 
                        "slno"=>$key + $row + 1,
                        "created"=>date('d-m-Y', $test['msg_create']),
                        "username"=>'<a href="'.base_url().'admin/users/edit/'.base64_encode($test['user_id']).'" target="_blank"><img class="direct-chat-img" src="'.$imageFile.'" title=""><br/>'.$test['username'].'</a>',
                        "text"=>$test['text'].'<p>'.$image.'</p>'
                    );
                }
            }
            

            $response = array(
                "draw" => intval($draw),
                "iTotalRecords" => $testtotalRecord,
                "iTotalDisplayRecords" => $testtotalRecordwithFilter,
                "aaData" => $data
            );

            echo json_encode($response);die;
        }
	}
}