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

class Profile extends CI_Controller
{
	public function __construct()
	{ 
		parent:: __construct();
		$this->load->model('common_model');
		$this->load->model('users_model');
		if(get_cookie('user_id'))
		{
			$this->session->set_userdata('user_id',get_cookie('user_id'));
		}
		if(!$this->session->userdata('user_id'))
		{
			redirect('home/login');
		}
		$this->load->library('Mobile_detect');
		$this->load->helper('text');
		avatarCron();
	}
	public function index()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
			if($this->session->userdata('user_id'))
			{
				$this->common_model->UpdateData('feu_userdetails',array('userlanguage'=>$langId),array('user_id'=>$this->session->userdata('user_id')));
				//echo $this->db->last_query(); die;
			}
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['expiry'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		
		/*$shop_order = $this->common_model->getAllRow('shop_orders',array('is_renewed'=>1 , 'invoiceAddress'=>$content_data['expiry'][0]['email'] ),'','created DESC'); 
		$unpaid_temp_order = $this->common_model->getAllRow('usr_temp_unpaid_orders',array('user_id'=>$this->session->userdata('user_id'),'is_renewed'=>1,'payed'=>0,'is_booking'=>0),array('shop_orders','shop_orders.order_id = usr_temp_unpaid_orders.order_id'),'created_at ASC'); 
		//print_r($unpaid_temp_order); die;
		if(count($shop_order)>0){
			if($shop_order['is_booking']== 0){
				if($shop_order['payed']==0){
					$shop_order_id=base64_encode($shop_order['order_id']);
					redirect(base_url().'add_card/index/'.$shop_order_id);
				} elseif($unpaid_temp_order){
					$this->common_model->insertData('feu_user_steps',array('user_id'=>$this->session->userdata('user_id'),'step'=>6,'created'=>time()));
					$shop_order_id=base64_encode($unpaid_temp_order['order_id']);
					redirect(base_url().'add_card/index/'.$shop_order_id);
				}
			}
		}*/

		$content_data['last_paid_membership'] = $last_paid_membership = $this->common_model->getAllRow('shop_orders',array('is_booking'=>0, 'payed'=>1, 'cancelled'=>0, 'invoiceAddress'=>$content_data['expiry'][0]['email'] ),'','created DESC');
		if($last_paid_membership){
			$time_of = ($last_paid_membership['created'] + ($last_paid_membership['time']*86400));
			if($time_of < time()){
				$this->session->set_userdata('member_msg',getLang('Expired').' '.date('d.m.Y',$time_of).', '.getLang('please_re_activate_your'));
				//$update = $this->common_model->insertData('feu_user_steps',array('user_id'=>$this->session->userdata('user_id'),'step'=>6,'created'=>time()));
			}
		}
		
		$content_data['steps'] = $data['steps'] = $this->common_model->getAllRow('feu_user_steps',array('user_id'=>$this->session->userdata('user_id'))) ;
		
		//print_r($data['steps']); die;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		$content_data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$content_data['userMembershipDetails'] = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		//echo $this->db->last_query(); die;
		$content_data['userImages'] = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id'),'filename !='=>'','free_membership_image'=>0),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC','*,sys_files.id as fileID') ;
		if(!empty($content_data['userImages']))
		{
			$i = 0;
			foreach ($content_data['userImages'] as $value) {
				$userLikes = $this->common_model->getAllMultipleJoin('like_likes','',array(array('feu_userdetails','feu_userdetails.user_id = like_likes.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'like_likes.created DESC','*,feu_userdetails.user_id','',0,5,array('identifier'=>$value['fileID'])) ;
				$content_data['userImages'][$i]['likeUsers'] = $userLikes;
				$i++;
			}
		}
		$userFreeImages = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id'),'filename !='=>'','free_membership_image'=>1,'accepted'=>1),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC') ;
		$content_data['userImages'] = array_merge($content_data['userImages'],$userFreeImages);
		
		$content_data['userPreferences'] = $this->common_model->getAll('feu_sexual_preference',array('user_id'=>$this->session->userdata('user_id')));
		$lngID = 2;
		if($content_data['userDetials'])
		{
			$lngID = $content_data['userDetials']['userlanguage'];
		}
		$content_data['userParticipation'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0,'evt_language_values.lang_id'=>$lngID),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_language_values.title,evt_events.alias','evt_events.id,shop_booking_details.cart_id');
		
		$ids = '';
		if(!empty($content_data['userParticipation']))
		{
			foreach ($content_data['userParticipation'] as $key => $value) {
				if($value['event_id']>0)
				{
					$ids = $ids.$value['event_id'].',';
				}
			}
			//echo $ids;die;
		}
		$where="";
		if($ids != '')
		{
			$where = " `shop_carts`.`user_id` = ".$this->session->userdata('user_id')." AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0 and evt_events.id not in (".trim($ids,',').") AND evt_language_values.lang_id = ".$lngID;
		}
		else
		{
			$where = " `shop_carts`.`user_id` = ".$this->session->userdata('user_id')." AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0 AND evt_language_values.lang_id = ".$lngID;
		}
		//echo $where;die;
		//$content_data['userParticipation_old'] = array();
		$content_data['userParticipation_old'] = $this->common_model->getAllMultipleJoin('shop_orders',$where,array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_events.title,evt_events.alias','evt_events.id,shop_articles_carts.event_id');
		
		//echo $this->db->last_query(); die;
		$membersWhere = 'avatar_file_id > 0 and feu_userdetails.user_id !='.$this->session->userdata('user_id').' and filename !=""';
		
		if($content_data['userDetials']['accounttype'] =='lady')
		{
			$membersWhere .= ' and interested_in_ladies = 1';
		}
		if($content_data['userDetials']['accounttype'] =='gentleman')
		{
			$membersWhere .= ' and interested_in_gentlemen = 1';
		}
		if($content_data['userDetials']['accounttype'] =='couple')
		{
			$membersWhere .= ' and interested_in_couples = 1';
		}
		if($content_data['userMembershipDetails']['id']==5)
		{
			$membersWhere .= ' and feu_userdetails.accounttype != "lady"';
		}
		$content_data['latestMembers'] = $this->common_model->getAllMultipleJoin('feu_userdetails',$membersWhere,array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'RAND()','','',0,8);
		//echo $this->db->last_query();
		$content_data['comments'] = $this->common_model->getAllMultipleJoin('feu_userdetails',array('alias_path'=>'community/profil/'.$content_data['userDetials']['alias']),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('cmt_comments','cmt_comments.user_id = feu_userdetails.user_id')),'cmt_comments.created DESC','*,cmt_comments.created,cmt_comments.id','',0,8);
		$content_data['lifestyles'] = $this->common_model->getAll('lifestyles');
		//print_r($content_data['comments']); die;
		$content_data['languages'] = $this->common_model->getAll('sys_languages') ;
		$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id Desc') ;
		$content_data['memberships_half'] = $this->common_model->getAll('shop_new_articles','','','id Asc') ;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		/******************FREE MEMBERSHIP*******************/
		$content_data['freeImages'] = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id'),'filename !='=>'','free_membership_image'=>1),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC','','',0,3) ;
		$free_image = $content_data['freeApprovedImages'] = $this->common_model->getAll('sys_files',array('filename !='=>'','free_membership_image'=>1,'accepted'=>1,'ugal_images.user_id'=>$this->session->userdata('user_id')),array('ugal_images','ugal_images.file_id = sys_files.id'),'sys_files.created DESC','*,sys_files.created,sys_files.id');
		if($content_data['userDetials']['free_member']==1 && $content_data['userDetials']['accounttype']=='lady')
        {
        	if(count($free_image)>=3)
        	{
        		$isExistNoti = $this->common_model->getAllRow('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>11));
        		//pr($isExistNoti);
        		if(count($isExistNoti)==0)
        		{
        			$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>11,'created'=>time()));
        			$this->common_model->UpdateData('feu_userdetails',array('created'=>time()),array('user_id'=>$this->session->userdata('user_id')));
        		}
        		$this->common_model->deleteData('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
        	}
        }
        /******************FREE MEMBERSHIP*******************/
        /****************** UNIQUE CODE***********************/
        if($content_data['loginDetails'][0]['unique_code']==0)
		{
			$unique_code = mt_rand(100000, 999999);
			$codeDetails = $this->common_model->getAllRow('usr_users',array('unique_code'=>$unique_code));
			if(count($codeDetails)>0)
			{
				$unique_code = mt_rand(100000, 999999);
			}
			$this->common_model->UpdateData('usr_users',array('unique_code'=>$unique_code),array('id'=>$this->session->userdata('user_id')));
		}
		$content_data['recomendData'] = $this->common_model->getAllRow('usr_users',array('used_code >'=>0));
		$content_data['recomendAmount'] = $this->common_model->getAllRow('sys_settings',array('key'=>'Recomendation_amount'));
		/****************** UNIQUE CODE***********************/
		$content_data['countries'] = $this->common_model->getAll('feu_countries') ;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Profile')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('profile', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function approve_free_images()
	{
		$this->common_model->deleteData('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
		$this->session->set_userdata('Freemessage',1);
		redirect('setting');
	}
	public function step1()
	{
		$userlanguage = $this->input->post('userlanguage');
		$country = $this->input->post('country');
		$interest_lady = $this->input->post('interest_lady');
		$interest_gentleman = $this->input->post('interest_gentleman');
		$interest_couples = $this->input->post('interest_couples');
		$escort_interest = $this->input->post('escort_interest');
		$interest_private = $this->input->post('interest_private');
		$preferences = $this->input->post('preferences');
		$experience = $this->input->post('experience');
		$arr = array(
					'country'=>$country,
					'userlanguage'=>$userlanguage,
					'interested_in_ladies'=>$interest_lady,
					'interested_in_gentlemen'=>$interest_gentleman,
					'interested_in_couples'=>$interest_couples,
					'interested_in_private_meeting'=>$interest_private,
					'escort_interest'=>$escort_interest,
					'preferences'=>$preferences,
					'same_room'=>($preferences=='full_swap')?1:0,
					'separate_room'=>($preferences=='full_swap')?1:0,
					'experience'=>$experience,
			);
		$this->common_model->UpdateData('feu_userdetails',$arr,array('user_id'=>$this->session->userdata('user_id')));
		$update = $this->common_model->UpdateData('feu_user_steps',array('step'=>2),array('user_id'=>$this->session->userdata('user_id')));
		/*if($update>0)
		{
			echo 1;
		}
		else
		{
			echo 0;
		}*/
		echo 1;exit;
	}
	public function step2()
	{
		$she_year = $this->input->post('she_year');
		$she_month = $this->input->post('she_month');
		$she_date = $this->input->post('she_date');
		$she_physis = $this->input->post('she_physis');
		$he_year = $this->input->post('he_year');
		$he_month = $this->input->post('he_month');
		$he_date = $this->input->post('he_date');
		$he_physis = $this->input->post('he_physis');
		$arr = array(
					'dob_lady'=>strtotime($she_date.'-'.$she_month.'-'.$she_year),
					'dob_gentleman'=>strtotime($he_year.'-'.$he_month.'-'.$he_date),
					'physis_lady'=>$she_physis,
					'physis_gentleman'=>$he_physis
			);
		$this->common_model->UpdateData('feu_userdetails',$arr,array('user_id'=>$this->session->userdata('user_id')));
		$update = $this->common_model->UpdateData('feu_user_steps',array('step'=>3),array('user_id'=>$this->session->userdata('user_id')));
		/*if($update>0)
		{
			echo 1;
		}
		else
		{
			echo 0;
		}*/
		echo 1;exit;
	}
	public function step10()
	{
		$sexual_preference = $this->input->post('sexual_preference');
		foreach ($sexual_preference as $key => $value) {
			$arr = array(
					'user_id'=>$this->session->userdata('user_id'),
					'sex_preference'=>$value,
			);
			$this->common_model->insertData('feu_sexual_preference',$arr);
		}
		
		$update = $this->common_model->UpdateData('feu_user_steps',array('step'=>4),array('user_id'=>$this->session->userdata('user_id')));
		/*if($update>0)
		{
			echo 1;
		}
		else
		{
			echo 0;
		}*/
		echo 1;exit;
	}
	public function step3()
	{
		$about = $this->utility->info_cleanQuery($this->input->post('about'));

		$text = $about;
		$text = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i','',$text); // extract email
		$text = preg_replace('/(\d{5,})/', '', $text); // extract phonenumber
		$main = explode('@', $text);
		$pos = strpos($text,'@');
		if(count($main)>0 && $pos!==false)
		{
			if(count($main)>0)
				$start = explode(' ', trim($main[0]));
				array_pop($start);
				$text1 = implode(' ', $start);
			if(count($main)>1)
				$end = explode(' ', trim($main[1]));
				array_shift($end);
				$text2 = implode(' ', $end);
			$text = $text1.' '.$text2;	
		}

		$arr = array(
					'about'=>$text,
			);
		$this->common_model->UpdateData('feu_userdetails',$arr,array('user_id'=>$this->session->userdata('user_id')));
		$update = $this->common_model->UpdateData('feu_user_steps',array('step'=>5),array('user_id'=>$this->session->userdata('user_id')));
		/*if($update>0)
		{
			echo 1;
		}
		else
		{
			echo 0;
		}*/
		echo 1;exit;
	}
	/******************FREE MEMBERSHIP*******************/
	public function free_lady_membership_upload()
	{
		if($_FILES)
		{
			for($i=0;$i<count($_FILES['freeFile']['name']);$i++)
			{
				if($_FILES['freeFile']['name'][$i]!='')
				{
					$_FILES['userFile']['name'] = $_FILES['freeFile']['name'][$i];
		            $_FILES['userFile']['type'] = $_FILES['freeFile']['type'][$i];
		            $_FILES['userFile']['tmp_name'] = $_FILES['freeFile']['tmp_name'][$i];
		            $_FILES['userFile']['error'] = $_FILES['freeFile']['error'][$i];
		            $_FILES['userFile']['size'] = $_FILES['freeFile']['size'][$i];

					$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().'pictures/');
			        }

			        $uploaddata = $this->upload->data();
			        $this->load->library('Utility');
					$file = array(
				            'user_id' 	=> $this->session->userdata('user_id'),
				            'path' 		=> $imagefolder,
				            'filename' 	=> $uploaddata['raw_name'],
				            'extension' => substr($uploaddata['file_ext'], 1),
				            'mimetype' 	=> $uploaddata['file_type'],
				            'is_image' 	=> $uploaddata['is_image'],
				            'created'	=> time(),
				            //'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' 	=> $this->session->userdata('user_id'),
				            'file_id' 	=> $fileId,
				            'is_private'=> 0,
				            'created'	=>time(),
				            'free_membership_image'=>1
				        );
				    $galId = $this->common_model->insertData('ugal_images',$dataset);
					//$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>12,'created'=>time(),'file_id'=>$fileId));
				}
				$this->common_model->UpdateData('feu_userdetails',array('free_member'=>1),array('user_id'=>$this->session->userdata('user_id')));
			}
		}
		echo 1;exit;
	}
	/******************FREE MEMBERSHIP*******************/
	public function step4()
	{
		if($_POST['image']!='')
		{
			$imagefolder = 'avatars/' ;
	        $uploadpath = 'assets/userfiles/'. $imagefolder;
			/*if (!file_exists(FCPATH . $uploadpath)) {
			    mkdir(FCPATH . $uploadpath, 0777, true);
			} */ 
			/*$filename = microtime().$_FILES['file']['name'];
	        $config = array(
	            'upload_path' 		=> FCPATH . $uploadpath . '/',
	            'allowed_types' 	=> 'jpg|JPG|png|PNG|jpeg|JPEG',
	            'encrypt_name' 		=> false,
	            '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('file')) {

	            echo $this->upload->display_errors(); exit;
	        }

	        $uploaddata = $this->upload->data();*/
	        $data = $_POST["image"];
			//print_r($_POST);die;
	        $imageName = time();
			$image_array_1 = explode(";", $data);
			$image_array_2 = explode(",", $image_array_1[1]);
			$data = base64_decode($image_array_2[1]);
			$imageFullName = $imageName . '.png';

			$getimagesize = getimagesizefromstring($data);
			//print_r($image_array_1);die;
			//print_r($getimagesize);die;

			file_put_contents($uploadpath.$imageFullName, $data);
			$mimetype = 'image/png';
			$width = '0';
			$height = '0';
			if($getimagesize){
				$mimetype = $getimagesize['mime'];
				$width = $getimagesize[0];
				$height = $getimagesize[1];
			}
	        //if($uploaddata)
	        //{
	        	$file = array(
	            'user_id' 	=> $this->session->userdata('user_id'),
	            'path' 		=> $imagefolder,
	            'filename' 	=> '',
	            'extension' => 'png',
	            'mimetype' 	=> $mimetype,
	            'is_image' 	=> 1,
	            'attr_alt' 	=> 'Bild von ' ,
	            'created'	=> time(),
	            'temp_name'	=> $imageName
		        );
		        
		        $imagesize = getimagesize($uploadpath.$imageFullName);
		        $file['width'] 	= $width;
		        $file['height'] = $height;


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

				$resize = $this->avater($imageFullName);
				if(file_exists(FCPATH . 'assets/userfiles/avatars/80/'.$imageFullName)){
					$im = new Imagick(FCPATH . 'assets/userfiles/avatars/80/'.$imageFullName);
			        $im->blurImage(5,3);
			        $blurredImg = FCPATH . 'assets/userfiles/avatars/blur/'.$imageFullName;
			        $fp = fopen($blurredImg, "x");
			        $im->writeImageFile($fp);
		    	}
		        $this->common_model->UpdateData('feu_userdetails',array('avatar_file_id'=>$fileId),array('user_id'=>$this->session->userdata('user_id')));
				$update = $this->common_model->UpdateData('feu_user_steps',array('step'=>6),array('user_id'=>$this->session->userdata('user_id')));
				$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>11,'created'=>time()));
				
	        //}
	        
		}
		
		echo 1;exit;
	}
	public function createOrder()
	{
		$origPrice = $this->input->post('price');
		$feePrice = $this->input->post('feePrice');
		$vatPrice = $this->input->post('vatPrice');
		$type = $this->input->post('type');
		$user_id = $this->session->userdata('user_id');
		$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));

		$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
			);
		$cartId = $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' 	=> 0,
			'invoice_address_id' 	=> 0,
			'ip_address' 			=> $this->input->ip_address(),
			'total_base' 			=> $origPrice*100,
			'shipping_fee' 			=> 0,
			'payment_fee' 			=> ($feePrice - $origPrice)*100,
			'vat' 					=> ($vatPrice - $feePrice)*100,
			'total_sum' 			=> ($origPrice+$feePrice+$vatPrice)*100 ,
			'payment_method_id' 	=> 13,
			'checkin_required' 		=> 0,
			'checkin_amount' 		=> 0,
			'invoiceAddress' 		=> $user->email,//$invoiceAdress['shipping']['email'],
            'discount'              => 0,
		);
		$orderId = $this->common_model->insertData('shop_orders',$dataset);

		$this->common_model->UpdateData('shop_orders',array('order_id_masked'=>'CE-'.$orderId),array('order_id'=>$orderId));
	}

	public function confirmOrder()
	{
		$memberships_half = $this->common_model->getAll('shop_new_articles','','','id Asc') ;
		$origPrice = $this->input->post('price');
		$feePrice = $this->input->post('feePrice');
		$vatPrice = $this->input->post('vatPrice');
		$type = $this->input->post('type')?$this->input->post('type'):5;
		$user_id = $this->session->userdata('user_id');
		$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));
		$userData = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		$finaltotal = 0;
		if($type==0)
		{
			$type=5;
		}
		if($vatPrice > 0)
		{
			$finaltotal = $vatPrice;
		}
		else
		{
			$finaltotal = $feePrice;
		}
		$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');
		//echo $origPrice.'='.(($memberships_half[1]['base_price']/100)-(($memberships_half[1]['base_price']/100)*0.15));
		$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*100,
			'shipping_fee' 			=> 0,
			'payment_fee' 			=> ($feePrice - $origPrice)*100,
			'vat' 					=> ($vatPrice - $feePrice)*100,
			'total_sum' 			=> $finaltotal*100 ,
			'payment_method_id' 	=> 13,
			'invoiceAddress' 		=> $userDetails['email'],
            'discount'              => 0,
            'time'					=>(int)$origPrice==(int)($memberships_half[0]['base_price']/100) || (int)$origPrice==(int)($memberships_half[1]['base_price']/100) ? 182 : 365,
            'created'				=> time(),
            'terms_accept_date'		=> time()
		);
		$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));
		/*********TEST*************/
		/*$CustomerId = 246934;	
		$TerminalId = 17951970;	
		$username = 'API_246934_23183450';
		$password = 'JsonApiPwd1_a8EpfvCy';	*/
		/*********TEST*************/

		/*********LIVE*************/
		$CustomerId = 403547;
		$TerminalId = 17799239;	
		$username = 'API_403547_78643204';
		$password = 'JsonApiPwdAnexus1_a8EpfvCy';	
		/*********LIVE*************/
		/***********************Create Card Alias Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "PaymentMeans": {
			    "Card": {
			      "Number": "'.$this->input->post('card_number').'",
			      "ExpYear": '.$this->input->post('exp_year').',
			      "ExpMonth": '.$this->input->post('exp_month').',
			      "HolderName": "'.$this->input->post('card_holder').'",
			      "VerificationCode": "'.$this->input->post('card_cvc').'"
			    }
			  },
			  "RegisterAlias": {
			    "IdGenerator": "RANDOM"
			  }
			}';
			//$url = 'https://test.saferpay.com/api/Payment/v1/Alias/InsertDirect';
			$url = 'https://www.saferpay.com/api/Payment/v1/Alias/InsertDirect';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	} else {
		    		$fail_reason = 'Authorization denied';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $aliasresponse = json_decode($jsonResponse, true);
		    //echo "<pre>";
		  	//print_r($aliasresponse);die;
		/***********************Create Card Alias Direct********************/


		/***********************Create Transaction Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TerminalId": "'.$TerminalId.'",
			  "Payment": {
			    "Amount": {
			      "Value": "'.(int)($finaltotal*100).'",
			      "CurrencyCode": "EUR"
			    },
			    "Description": "Membership",
			    "PayerNote": "Membership"
			  },
			  "PaymentMeans": {
			    "Alias": {
			      "Id": "'.$aliasresponse['Alias']['Id'].'"
			    }
			  }
			}';

			//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
			$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $transactionresponse = json_decode($jsonResponse, true);
		    $this->common_model->UpdateData('shop_orders',array('real_name'=>$transactionresponse['PaymentMeans']['Card']['HolderName'], 'card_origin'=>$transactionresponse['PaymentMeans']['Card']['CountryCode']),array('order_id'=>$orderId));
		  	//echo "<pre>";
			//print_r($transactionresponse);die;
		/***********************Create Transaction Direct********************/


		/***********************Create Capture Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TransactionReference": {
			    "TransactionId": "'.$transactionresponse['Transaction']['Id'].'"
			  }
			}';
			//echo $JSONObj;die;
			//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Capture';
			$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Capture';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $response = json_decode($jsonResponse, true);
		    
		  	//echo "<pre>";
			//print_r($response);die;
		/***********************Create Capture Direct********************/
		//print_r($cc_ref_id_result);die;

		if($response)
		{
			$this->common_model->deleteData('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
			$this->common_model->UpdateData('shop_orders',array('payed'=>1,'trn_id'=>$transactionresponse['Transaction']['Id'],'fail_reason'=>''),array('order_id'=>$orderId));
			$cc_pan = 'xxxx xxxx xxxx '.substr($this->input->post('card_number'), -4);
			$expYr = substr($this->input->post('exp_year'), -2);
			$expMth = str_pad($this->input->post('exp_month'), 2, '0', STR_PAD_LEFT);
			$saferpay_exp = $expMth.$expYr;
			$this->common_model->UpdateData('usr_users',array('card_alias'=>$aliasresponse['Alias']['Id'],'cc_pan'=>$cc_pan,'saferpay_exp'=>$saferpay_exp),array('id'=>$this->session->userdata('user_id')));
			//$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>11,'created'=>time()));
			
			$delete_unpaids = $this->common_model->getAll('shop_orders',array('invoiceAddress'=>$userDetails['email'],'payed'=>0,'is_booking'=>0,'is_renewed'=>0));
			if(count($delete_unpaids) < 5 && $userDetails['email']!='')
			{
				$this->common_model->deleteData('shop_orders',array('invoiceAddress'=>$userDetails['email'],'payed'=>0,'is_booking'=>0,'is_renewed'=>0));
			}

			$avatarData = $this->common_model->getAllRow('sys_files',array('id'=>$userData['avatar_file_id']));
			if($avatarData['filename']=='' && $avatarData['temp_name']!='')
			{
				$this->common_model->UpdateData('sys_files',array('filename'=>$avatarData['temp_name'],'temp_name'=>''),array('id'=>$avatarData['id']));
			}

			$to = $userDetails['email'];
			$sub = getLang('Membership_Invoice_mail_from').' Castleevents';
			//$body= '<p>Dear '.$userData['username'].',</p>';
			$body= '';
			$body.= '<p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('Invoice_Number').': CE-'.$orderId.'</p><p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('Generated_On').': '.date('Y-m-d',time()).'</p><p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('Paid_Amount').': '.number_format($finaltotal,2, '.', '').' EUR</p>';
			$body.= '<p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('Invoice_will_be_located').' www.castleevents.com.</p>';
			$body.= '<p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('We_appreciate_very_much').'.</p>';
			$body.= '<p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('Please_do_not_hesitate_to_contact').'.</p>';
			//$body.= '<p>Best regards,</p><p>Your Castleevents Team </p>';

			$bodys='<table cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 800px;" >
            <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 style="font-size: 17px; padding-bottom: 10px; text-transform: capitalize; color: #c1c1c1; margin: 0;">'.getLang('Dear').' <span style="text-transform:capitalize">'.$userData['username'].'</span> </h2>
                           <p style=" color: #c1c1c1; font-size: 14px; line-height: 16px; padding-bottom: 10px; margin: 0;">'.getLang('We_have_received_your_payment').'!</p>
                        </td>
                     </tr>
                     <tr>
                        <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                        	<div style="background: #1F1F27; padding: 30px; border-radius: 30px; text-align: left; display: block; ">
	                           '.$body.'
	                        </div>
                        </td>
                     </tr>
                     <tr>
                        <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 12px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
                           <span style="color: #a2a2a2">This payment is related to our <a href="'.base_url('terms').'" style="text-decoration: none; color: #B4975B;">terms and conditions</a> confirmed from you on '.date('d-m-Y H:i:s').'.</span>                                                 
                        </td>
                     </tr>
                     <tr>
                     	<td align="center" style="font-family: sans-serif; color: #a7a7a7; padding: 30px 40px 15px;">
                     		<p style="margin:5px 0 0; color: #a7a7a7">'.getLang('Your_Castleevents_Team').'</p> 
                     	</td>
                     </tr>
                  </table>
               </td>
            </tr>
        </table>';


		$this->utility->sendOrderMail($to,$sub,$bodys);


		/****extra mail****/
			$to = 'alorenc@me.com';
			$sub = 'Payment recieved';
			$body= 'CE-'.$orderId.', EUR '.number_format($finaltotal, 2,',', '.');
			$body.= '<p>Paid New Membership Fees</p>';
			$body.= '<p>'.$userData['username'].'</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 style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
			                           '.$body.'
			                        </td>
			                     </tr>
			                  </table>
			               </td>
			            </tr>
			        </table>';
			$this->utility->sendOrderMail($to,$sub,$bodys);
		/****extra mail****/


			//$this->utility->sendMail($to,$sub,$body);
			echo 2;
		}
		else
		{
			$this->common_model->UpdateData('shop_orders',array('fail_reason'=>'Card authorization denied','payment_method_id'=>13),array('order_id'=>$orderId));
			echo 'Card authorization denied';
		}
		exit;
	}
	public function invoice()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		if(checkStep()==1)
		{
			redirect('profile');
		}
		if(checkCardUpdated()==2)
		{
			redirect('profile');
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['invoices'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_language_values.event_id = evt_events.id'),array('loc_events_locations','loc_events_locations.event_id = evt_events.id'),array('loc_locations','loc_locations.id = loc_events_locations.location_id')),'shop_orders.created DESC','*,evt_events.id as evt_id,evt_events.alias,shop_orders.created as created','shop_booking_details.cart_id');
		$content_data['old_invoices'] = $this->common_model->getAllMultipleJoin('shop_articles',array('shop_articles_carts.event_id !='=>'','shop_carts.user_id'=>$this->session->userdata('user_id'),'evt_language_values.lang_id'=>$langId),array(array('shop_articles_carts','shop_articles_carts.article_id = shop_articles.id'),array('shop_carts','shop_carts.id = shop_articles_carts.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_language_values.event_id = evt_events.id'),array('loc_events_locations','loc_events_locations.event_id = evt_events.id'),array('loc_locations','loc_locations.id = loc_events_locations.location_id')),'shop_orders.created DESC','*,evt_events.id as evt_id,evt_events.alias,shop_orders.created as created','shop_orders.cart_id');
		//echo $this->db->last_query();die;
		$content_data['orders'] = $this->common_model->getAllMultipleJoin('shop_articles_carts',array('is_booking'=>0,'payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_articles_carts.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id')),'shop_orders.order_id DESC','*,shop_orders.created','shop_articles_carts.cart_id');
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		
		//print_r($content_data['orders']);die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$content_data['userDetials'] = $data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		/******************FREE MEMBERSHIP*******************/
		/*if($content_data['userDetials']['free_member']==1)
		{
			$this->session->set_userdata('upgrade',1);
			redirect('profile');
		}*/
		/******************FREE MEMBERSHIP*******************/
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Invoice')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('invoice', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function orderDetails()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$cart_id = $this->input->post('cart_id');
		$type = $this->input->post('type');
		if($type==2)
		{
			$orderData = $this->common_model->getAllRowMultipleJoin('shop_orders',array('cart_id'=>$cart_id));
			$orderDetails = $this->common_model->getAllMultipleJoin('shop_booking_details',array('cart_id'=>$cart_id));
			$html='<table class="order-table"><tr><td>'.getLang('Feature').'</td><td>'.getLang('Quantity').'</td><td width="250">'.getLang('Price').'(EUR)</td></tr>';
			$total = 0;
			if(!empty($orderDetails))
			{
				$count = 0;
				foreach ($orderDetails as $value)
				{
					$eventSData = $this->common_model->getAllRow('evt_events',array('id'=>$value['event_id']));
					$percentage = 0;
					$percent = "";
					$user_discount = "";
					if(!empty($eventSData))
					{
						$percentage = $eventSData['discount'];
						$percent = " <p style='color:#b3975b'>( ".$eventSData['discount']."% Discount )</p>";						
					}
					if($value['feature_type'] == 1) {
						if($orderData['user_discount'] > 0) {
							$user_discount = " <span style='color:#b3975b'>( ".$orderData['user_discount']."% Discount )</span>";
						}
					}
					if($value['price'] > 0)
                    {
						$total = $total + $value['price'];
						if($value['feature_type'] == 1) {
							if($orderData['discount'] > 0) {
								$value['price'] = $value['price'] - ($orderData['discount']/100);
								$total = $total - ($orderData['discount']/100);
							}
						}
						//$name = getValue('event_features_lang_values',array('event_feature_id'=>$value['feature_id']));
						$name = getValue('event_features_lang_values',array('event_feature_id'=>$value['feature_id'],'lang_id'=>$langId));
						if(empty($name))
						{
							$name = getValue('event_features_lang_values',array('event_feature_id'=>$value['feature_id'],'lang_id'=>2));
						}
						$dates = explode(',', $value['feature_id']);
	                    $date='';
	                    if(!empty($dates))
	                    {
	                      foreach ($dates as $dateVal) {
	                        $val = getValue('event_features',array('id'=>$value['feature_id']));
	                        $date .= date('d.m.Y',$val['date']).',';
	                      }
	                    }
						if(!empty($name))
						{
							$title = $name['title'];
						}
						else
						{
							$title = getLang('Extra_Nights').' ('.rtrim($date,',').')';
						}
						$quantity = count(explode(',', $value['feature_id']));
					$html.='<tr><td>'.$title.$user_discount.'</td><td>'.$quantity.'</td><td>'.number_format($value['price'],2,',','.').'</td></tr>';
					//$html.='<tr><td>'.$title.'</td><td>'.$quantity.'</td><td>'.number_format($value['price'],2,',','.').''.(($count==0 && $percentage>0)?$percent:'').'</td></tr>';
		            }

		            $count++;
	        	}
	        	/*Reservation*/
	        	$reservation_total = '';
	        	if($orderData['is_recomended'] == 1) {
	        		$setting = getValue('sys_settings', array('key'=>'reservation_fee')); 
					$reservation_charge = $setting ? $setting['value'] : 0;
					$total = (($total * $reservation_charge)/100);
					$reservation_total = ' (40% Deposit)';
				}
	            if($orderData['is_recomended'] == 1) {
	            	$html.='<tr><td style="color: #b3975b;border-top: 1px solid #b3975b;"></td><td style="color: #b3975b;border-top: 1px solid #b3975b;">'.getLang('Total').$reservation_total.'</td><td style="color: #b3975b;border-top: 1px solid #b3975b;">'.number_format($total,2,',','.').'</td></tr>';
	            	$html.='<tr><td></td><td>Rest payment at arrival</td><td>'.number_format(($orderData['reservation_rest_amount']/100),2,',','.').'</td></tr>';
	            } else {
	            /*Reservation*/
	            	$html.='<tr><td></td><td>'.getLang('Total').'</td><td>'.number_format($total,2,',','.').'</td></tr>';
	            }
			}
			$html.='</table>';
		}
		else
		{
			$orderDetails = $this->common_model->getAllRowMultipleJoin('shop_articles_carts',array('shop_orders.cart_id'=>$cart_id),array(array('shop_carts','shop_carts.id = shop_articles_carts.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id')),'shop_orders.created DESC','*,shop_orders.created','shop_articles_carts.cart_id');
			$html='<table class="order-table"><tr><td></td><td>'.getLang('Feature').'</td><td>'.getLang('Price').'(EUR)</td></tr>';
			$total = 0;
			if(!empty($orderDetails))
			{
				$html.='<tr><td></td><td>'.ucfirst($orderDetails['alias']).'</td><td>'.number_format($orderDetails['total_base']/100,2,',','.').'</td></tr>';
				$html.='<tr><td></td><td>'.getLang('Payment_Fee').'</td><td>'.number_format($orderDetails['payment_fee']/100,2,',','.').'</td></tr>';
				$html.='<tr><td></td><td>'.getLang('Vat').'</td><td>'.number_format($orderDetails['vat']/100,2,',','.').'</td></tr>';
				$html.='<tr><td></td><td>'.getLang('Total').'</td><td>'.number_format($orderDetails['total_sum']/100,2,',','.').'</td></tr>';
			}
			$html.='</table>';
		}
		echo $html;exit;
	}
	public function Invoicepay()
	{
		$userData = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$this->input->post('cart_id')));
		$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));
		/*********TEST*************/
		/*$CustomerId = 246934;	
		$TerminalId = 17951970;	
		$username = 'API_246934_23183450';
		$password = 'JsonApiPwd1_a8EpfvCy';	*/
		/*********TEST*************/

		/*********LIVE*************/
		$CustomerId = 403547;
		$TerminalId = 17799239;	
		$username = 'API_403547_78643204';
		$password = 'JsonApiPwdAnexus1_a8EpfvCy';	
		/*********LIVE*************/
		/***********************Create Transaction Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TerminalId": "'.$TerminalId.'",
			  "Payment": {
			    "Amount": {
			      "Value": "'.$orderDetail['total_sum'].'",
			      "CurrencyCode": "EUR"
			    },
			    "Description": "Event Service",
			    "PayerNote": "Event Service"
			  },
			  "PaymentMeans": {
			    "Card": {
			      "Number": "'.$this->input->post('card_number').'",
			      "ExpYear": '.$this->input->post('exp_year').',
			      "ExpMonth": '.$this->input->post('exp_month').',
			      "HolderName": "'.$this->input->post('card_holder').'",
			      "VerificationCode": "'.$this->input->post('card_cvc').'"
			    }
			  }
			}';

			//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
			$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('cart_id'=>$this->input->post('cart_id')));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $transactionresponse = json_decode($jsonResponse, true);
		    $this->common_model->UpdateData('shop_orders',array('real_name'=>$transactionresponse['PaymentMeans']['Card']['HolderName'], 'card_origin'=>$transactionresponse['PaymentMeans']['Card']['CountryCode']),array('cart_id'=>$this->input->post('cart_id')));
		  	//echo "<pre>";
			//print_r($transactionresponse);die;
		/***********************Create Transaction Direct********************/


		/***********************Create Capture Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TransactionReference": {
			    "TransactionId": "'.$transactionresponse['Transaction']['Id'].'"
			  }
			}';
			//echo $JSONObj;die;
			//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Capture';
			$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Capture';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('cart_id'=>$this->input->post('cart_id')));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $response = json_decode($jsonResponse, true);
		    
		  	//echo "<pre>";
			//print_r($response);die;
		/***********************Create Capture Direct********************/
			if($response)
			{
					$this->common_model->UpdateData('shop_orders',array('payed'=>1,'trn_id'=>$transactionresponse['Transaction']['Id'],'payment_method_id'=>13,'fail_reason'=>'','payment_date'=>date('Y-m-d')),array('cart_id'=>$this->input->post('cart_id')));
					
					$to = $userDetails['email'];
					$sub = getLang('Confirmation').': '.getLang('Successful_payment');
					//$sub = 'Your booking: Order CE-'.$orderDetail['order_id'];
					//$body= '<p>Dear '.$userData['username'].',</p>';
					$bookingDetails = $this->common_model->getAllRow('shop_booking_details',array('cart_id'=>$this->input->post('cart_id')),array('evt_events','evt_events.id = shop_booking_details.event_id'));
					
					$body= '<p>'.getLang('We_have_received_your_payment').'!</p>';
					if(count($bookingDetails)>0)
					{
						$body.= '<p>Event Date and Place: '.date('d M Y',$bookingDetails['time_from']).' - '.eventDetails($bookingDetails['event_id']).'</p>';
					}
					$body.= '<p>'.getLang('Invoice_Number').': CE-'.$orderDetail['order_id'].'</p><p>'.getLang('Generated_On').': '.date('Y-m-d',time()).'</p><p>'.getLang('Paid_Amount').': '.number_format($this->input->post('price'),2, '.', '').' EUR</p>';
					$body.= '<p>'.getLang('Invoice_will_be_located').' www.castleevents.com.</p>';
					$body.= '<p>'.getLang('We_appreciate_very_much').'.</p>';
					$body.= '<p>'.getLang('Please_do_not_hesitate_to_contact').'.</p>';

					$body.= '<p></p>';
					$body.= '<p>This payment is related our <a href="'.base_url('terms').'">terms and conditions</a> confirmed from you on '.date('d-m-Y H:i:s').' </p>';
					//$body.= '<p>Best regards,</p><p>Your Castleevents Team </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>'.getLang('Dear').' <span style="text-transform:capitalize">'.$userData['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;">
                             		'.getLang('Best_regards').' <br>
                             		<p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
                             	</td>
                             </tr>
                          </table>
                       </td>
                    </tr>
                </table>';


				$this->utility->sendOrderMail($to,$sub,$bodys);

				/****extra mail****/
					$to = 'alorenc@me.com';
					$sub = 'Payment recieved';
					$body_purpose = '';
					if($orderDetail['is_booking']==1){
						$body_purpose = 'Paid Party Booking Fees';
					} else {
						$body_purpose = 'Paid New Membership Fees';
					}
					$body= 'CE-'.$orderDetail['order_id'].', EUR '.number_format(($orderDetail['total_sum']/100), 2,',', '.');
					$body.= '<p>'.$body_purpose.'</p>';
					$body.= '<p>'.$userData['username'].'</p>';
					$body.= '<p>Event Name: '.$bookingDetails['title'].'</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 style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
					                           '.$body.'
					                        </td>
					                     </tr>
					                  </table>
					               </td>
					            </tr>
					        </table>';
					$this->utility->sendOrderMail($to,$sub,$bodys);
				/****extra mail****/
					echo 2;
			}
			else
			{
				$this->common_model->UpdateData('shop_orders',array('fail_reason'=>'Card authorization denied','payment_method_id'=>13),array('cart_id'=>$this->input->post('cart_id')));
				echo 'Card authorization denied';
			}
			exit;
	}
	public function printDetails()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$cart_id = $this->input->post('cart_id');
		$type = $this->input->post('type');
		
        $html='';
        if($type==2)
        {
        	$orderDetails = $this->common_model->getAllMultipleJoin('shop_booking_details',array('cart_id'=>$cart_id));
	        $orderDetail = $this->common_model->getAllRowMultipleJoin('shop_orders',array('cart_id'=>$cart_id));
	        $total = number_format($orderDetail['total_sum']/100,2,',','.');
	        if(!empty($orderDetails))
			{
				/*Reservation*/
	        	$reservation_total = '';
	        	if($orderDetail['is_recomended'] == 1) {
	        		$setting = getValue('sys_settings', array('key'=>'reservation_fee')); 
					$reservation_charge = $setting ? $setting['value'] : 0;
					$reservation_total = '(40% Deposit)';
				}
				$html.='<div class="printInner" id="printInner">
	                        <p>'.getLang('Please_transfer_the_full_amount_of').' <span class="total">EUR '.$total.'</span> '.getLang('to_the_bank_accunt_below').'!</p><br>
	                         <p><strong>'.getLang('Invoice_Number').':</strong> <span class="invoiceID">'.$orderDetail['order_id_masked'].'</span></p>
	                         <p><strong>'.getLang('Generated_On').':</strong> '.date('Y-m-d',$orderDetail['created']).'</p>
	                         <p><strong>'.getLang('Due_to').':</strong> '.date('Y-m-d',strtotime(date('Y-m-d',$orderDetail['created'])." + 10days")).'</p>
	                         <p><strong>'.getLang('Outstanding_Amount').$reservation_total.': </strong><span class="total">'.$total.' EUR</span></p>
	                         <br>
	                         <strong>'.getLang('Details_of_your_Order').':</strong>';
				foreach ($orderDetails as $value)
				{
					if($value['price'] > 0)
                    {
						$name = getValue('event_features_lang_values',array('event_feature_id'=>$value['feature_id'],'lang_id'=>$langId));
						if(empty($name))
						{
							$name = getValue('event_features_lang_values',array('event_feature_id'=>$value['feature_id'],'lang_id'=>2));
						}
						
						$dates = explode(',', $value['feature_id']);
	                    $date='';
	                    if(!empty($dates))
	                    {
	                      foreach ($dates as $dateVal) {
	                        $val = getValue('event_features',array('id'=>$value['feature_id']));
	                        $date .= date('d.m.Y',$val['date']).',';
	                      }
	                    }
						if(!empty($name))
						{
							$title = $name['title'];
						}
						else
						{
							$title = getLang('Extra_Nights').' ('.rtrim($date,',').')';
						}
		        		$html.=' <p><span>-</span> <span class="entryDetails">'.$title.'</span></p>';
		        	}
	            }
	            $site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
				$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
				$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));
	            $html.=' <br>
	                         <strong>'.getLang('Bank_Details').':</strong>
	                         <br>
	                         <p><strong>IBAN:</strong> CH810023123110716660E</p>
	                         <p><strong>'.getLang('Clearing').':</strong> 231</p>
	                         <p><strong>Swift:</strong> UBSWCHZH80A</p>
	                         <p><strong>'.getLang('Payment_Reason').':</strong> '.$orderDetail['order_id_masked'].'</p>
	                         <p><strong>'.getLang('Amount').':</strong> <span class="total">'.$total.'</span></p>
	                         <p><strong>'.getLang('Bank').':</strong> UBS, Bahnhofstrasse 1, 5000 Aarau, Switzerland</p>
	                         <p><strong>'.getLang('Recipient').':</strong> '.$site_address_name['value'].', '.$site_address_city['value'].', '.$site_address_country_zip['value'].'</p>
	                        </div> ';
	        } 
        }
        else
        {
        	$orderDetails = $this->common_model->getAllRowMultipleJoin('shop_articles_carts',array('shop_orders.cart_id'=>$cart_id),array(array('shop_carts','shop_carts.id = shop_articles_carts.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id')),'shop_orders.created DESC','*,shop_orders.created','shop_articles_carts.cart_id');
	        if(!empty($orderDetails))
			{
				$html.='<div class="printInner" id="printInner">
                        <p><strong>'.getLang('Invoice_Number').':</strong> <span class="invoiceID">'.$orderDetails['order_id_masked'].'</span></p>
                        <p><strong>'.getLang('Generated_On').':</strong> '.date('Y-m-d',$orderDetails['created']).'</p>
                        <p><strong>'.getLang('Outstanding_Amount').': </strong><span class="total">'.number_format($orderDetails['total_sum']/100,2,',','.').' EUR</span></p>
                        <br>
                         <strong>'.getLang('Details_of_your_Order').':</strong>';
                $html.='<table class="order-table" style="width: 100%;">';
                $html.='<tr><td><strong></strong></td><td><strong>'.getLang('Feature').'</strong></td><td><strong>'.getLang('Price').'(EUR)</strong></td></tr>';         
                $html.='<tr><td></td><td>'.ucfirst($orderDetails['alias']).'</td><td>'.number_format($orderDetails['total_base']/100,2,',','.').'</td></tr>';
				$html.='<tr><td></td><td>'.getLang('Payment_Fee').'</td><td>'.number_format($orderDetails['payment_fee']/100,2,',','.').'</td></tr>';
				$html.='<tr><td></td><td>'.getLang('Vat').'</td><td>'.number_format($orderDetails['vat']/100,2,',','.').'</td></tr>';
				$html.='<tr><td></td><td>'.getLang('Total').'</td><td>'.number_format($orderDetails['total_sum']/100,2,',','.').'</td></tr>';         
				$html.='</table></div>'; 
	        }                 
        }               
        echo $html; exit;               
	}
	public function logout()
	{
		$this->common_model->UpdateData('feu_userdetails',array('online_status'=>0),array('user_id'=>$this->session->userdata('user_id')));
		$this->common_model->UpdateData('usr_users',array('last_login'=>time(),'logout_time'=>time(),'reminder_mail_send'=>0),array('id'=>$this->session->userdata('user_id')));
		$this->common_model->insertData('usr_log',array('log_time'=>time(),'user_id'=>$this->session->userdata('user_id'),'type'=>2));
		$this->session->unset_userdata('user_id');
		$cookie = array(
		        'name'   => 'user_id',
		        'value'  => '',
		        'expire' => 0,
		        );
		 
		delete_cookie($cookie);
		redirect(base_url());
	}
	public function other($alias = '')
	{
		$userdata = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		if($userdata['alias'] == $alias)
		{
			redirect(base_url().'profile');
		}
		$steps = getValue('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
		if(count($steps)>0)
		{
			redirect(base_url().'profile');
		}
		if($this->session->userdata('user_id')){
			if(getOpenBookingInvoices() > 0)
			{
				$this->session->set_userdata('pay_book_first',1);
				redirect('invoice');
			}
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$user = $this->common_model->getAllRow('feu_userdetails',array('alias'=>$alias));
		$content_data['friend'] = $this->common_model->getAllRowMultipleJoin('feu_relationships',array('user_id_1'=>$this->session->userdata('user_id'),'user_id_2'=>$user['user_id'],'type'=>'friend'));
		$content_data['unfriend'] = $this->common_model->getAllRowMultipleJoin('feu_relationships',array('user_id_2'=>$this->session->userdata('user_id'),'user_id_1'=>$user['user_id'],'type'=>'friend'));
		$content_data['friendGuest'] = $this->common_model->getAllRowMultipleJoin('feu_relationships',array('user_id_1'=>$this->session->userdata('user_id'),'user_id_2'=>$user['user_id'],'type'=>'guest'));
		$content_data['unfriendGuest'] = $this->common_model->getAllRowMultipleJoin('feu_relationships',array('user_id_2'=>$this->session->userdata('user_id'),'user_id_1'=>$user['user_id'],'type'=>'guest'));
		$content_data['message_data'] = $this->common_model->getAllRowMultipleJoin('msg_messages',array('user_id'=>$this->session->userdata('user_id'),'from_user_id'=>$user['user_id']),array(array('msg_conversations_users','msg_conversations_users.conversation_id = msg_messages.conversation_id')));
		//pr($content_data['message_data']);
		$content_data['blocked_data'] = $this->common_model->getAllRowMultipleJoin('usr_block',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$user['user_id']));

		$user_blocked_data = $this->common_model->getAllRowMultipleJoin('usr_block',array('to_id'=>$this->session->userdata('user_id'),'from_id'=>$user['user_id']));
		/*if($user_blocked_data){
			$this->session->set_userdata('you_are_blocked','1');
			redirect('profile');
		}*/
		/******************FREE MEMBERSHIP*******************/
		/*if($userdata['free_member']==1 && count($content_data['friend'])==0 && count($content_data['unfriend'])==0 && count($content_data['message_data'])==0)
		{
			$this->session->set_userdata('upgrade',1);
			redirect('profile');
		}*/
		/******************FREE MEMBERSHIP*******************/
		$percent = profile_percent($this->session->userdata('user_id')); 
		if($percent<80)
		{
			if($userdata['she_height']==0 && $userdata['she_weight']==0 && $userdata['he_height']==0 && $userdata['he_weight']==0)
			{
				$this->session->set_userdata('other_error_height','1');
				redirect(base_url().'setting');
			}
			else
			{
				$this->session->set_userdata('other_error','1');
				redirect(base_url().'setting');
			}
			
		}	
		if(!empty($user))
		{
			$visitorData = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')));
			$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$user['user_id'],'type'=>10,'created'=>time()));
			

			/*****************VISIT MAIL****************/
			include APPPATH.'libraries/Mailins.php';
            $mailin = new Mailin('https://api.sendinblue.com/v2.0','bs8yJF0cRaCOGMPt', 5000);
			$visitedData = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$user['user_id']),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
			$visitEntry = $this->common_model->getAllRow('feu_profilevisits',array('from_user_id'=>$this->session->userdata('user_id'),'to_user_id'=>$user['user_id']));
			if($visitedData['visitor_mail']==1 && $visitedData['accept_terms']==1)
			{
				
				$visitorPreference = $this->common_model->getAll('feu_sexual_preference',array('user_id'=>$this->session->userdata('user_id'))); 	
				 	$genteman_age = (time() - $visitorData['dob_gentleman'])/(365*24*60*60);
	                $lady_age = (time() - $visitorData['dob_lady'])/(365*24*60*60);
				//print_r($visitorData); die;	
				$to = $visitedData['email'];
				//$to = $visitedData['email'];
				$sub = getLang('New_visitor').': '.$visitorData['username'];
				if($visitorData['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension']))     
                {
	                $cidurl = base_url().'/newsletter_image/'.$visitorData['filename'].'.'.$visitorData['extension'];
	                $this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$visitorData['filename'].'.'.$visitorData['extension']);
	            }
	            else
	            {
	                $cidurl = base_url().'/newsletter_image/default-avatar.jpg';
	            }
				
						
	            $from='noreply@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',
		              '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->to($to); 
				$this->email->subject($sub);
				$body='<!DOCTYPE html>
								<html>
								   <head>
									  <meta http-equiv="content-type" content="text/html" 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;
										 }
									  </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%; background-color: #252530;" >
										 <div style="max-width: 600px; margin: 40px auto;">
										   
													 <table cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 800px;">
														<tr>
														   <td style="padding: 20px 0; text-align: center; background:#131218;">
															  <a href="'.base_url().'"><img src="'.base_url().'newsletter_image/new-logo-mail.png" width="250" alt="Castleevents" border="0"></a>
														   </td>
														</tr>
													 </table>
													 <table cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 800px;" >
						            <tr>
						               <td>
						                  <table cellspacing="0" cellpadding="0" border="0" width="100%">
		                             <tr>
		                                <td align="center" style="color: #e4e4e4;font-family: sans-serif;font-size: 15px;line-height: 20px;padding: 40px;">
		                                   <h5 style="font-size: 17px;padding-bottom: 10px;text-transform: capitalize; color: #c1c1c1; margin: 0;">'.getLang('Hello').' '.$visitedData['username'].'</h5>
										   <span style="color: #c1c1c1;">'.getLang('Your_profile_got_visited_on').' '.date('d.M.Y',time()).' '.getLang('at').' '.date('H:i',time()).'</span>												    
		                                </td>
		                             </tr>


		                             <tr>
		                                <td align="center" style="padding: 0 40px 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <div style="background: #1F1F27; padding: 30px; border-radius: 41px; text-align: center; display: block; ">
		                                   <h2 style="text-transform:capitalize; font-size: 16px; padding-bottom: 5px; margin: 0; line-height: 16px; color: #B4975B;">'.$visitorData['username'].'</h2>
											    <span style=" text-transform: capitalize; color: #dddddd; font-size: 13px; display: block; margin-bottom: 20px;">'.$visitorData['accounttype'].'-'.$visitorData['country_name'].',';
			                                    if($visitorData['dob_lady']>0){ 
			        $body.=							round($lady_age);
			                                    } 
			                                    elseif($visitorData['dob_gentleman']>0){ 
			        $body.=							round($genteman_age);
			                                    }  
			        $body.='                    </span>
			        							<!--<img src="'.$image.'" width="100" >-->
												<span style="width: 100px; height: 100px; border-radius: 100%; overflow: hidden; display: inline-block; line-height: 100px;"><img src="'.$cidurl.'" width="100" ></span>

			        							<p style="color: #666; font-size: 14px; padding-bottom: 20px; padding-top: 20px;">';
					                            $usermeetingdata = '';
				                                if($visitorData['experience']==1)
				                                {
				                                  $usermeetingdata .= getLang('New_experience').', ';
				                                }
				                                $usermeetingdata .= getLang(str_replace('-', '_', str_replace(' ', '_', $visitorData['preferences'])));
				                                if($visitorData['preferences']=='full_swap' && ($visitorData['same_room']==1 || $visitorData['separate_room']==1))
				                                {
				                                    $usermeetingdata .= ' (';
				                                    if($visitorData['same_room']==1)
				                                    {
				                                      $usermeetingdata .= getLang('Same_Room');
				                                    } 
				                                    if($visitorData['same_room']==1 && $visitorData['separate_room']==1)
				                                    {
				                                      $usermeetingdata .= ',';
				                                    } 
				                                    if($visitorData['separate_room']==1)
				                                    {
				                                      $usermeetingdata .= getLang('Separate_Room');
				                                    } 
				                                    $usermeetingdata .= ') ';  
				                                }
				                                $usermeetingdata .= ', ';
				                                if($visitorData['escort_interest']==1)
				                                {
				                                    $usermeetingdata .= ' '.getLang('Looking_for_companion').', ';
				                                }
				                                if($visitorData['interested_in_private_meeting']==1)
				                                {
				                                    $usermeetingdata .= ' '.getLang('Ceremony').', ';
				                                }
				            $body.=                 $usermeetingdata;

				            					if(!empty($visitorPreference)){ 
				                                    $i=1;
				                                    foreach ($visitorPreference as $preference) {
				                                      $comma = '';
				                                        if($i!=count($visitorPreference))
				                                        {
				                                          $comma = ',';
				                                        }
				                                    
				            $body.=                     getLang(str_replace('-', '_', str_replace(' ', '_', $preference['sex_preference']))).' '.$comma;
				                                    $i++; } } 

		        $body.='                  </p>
		        							<h5 style="color: #b9b9b9; font-size: 12px; padding-bottom: 10px; margin: 0; font-weight: normal;">'.getLang('visit_the_profile').':</h5>
										   	<span><a style="color: #898989; font-size: 12px; text-decoration: none;" href="https://castleevents.com/profil/'.$visitorData['alias'].'">https://castleevents.com/profil/'.$visitorData['alias'].'</a></span>	
		        							</div>
		                                </td>
		                             </tr>';
		                        

		        $body.='             <tr>
		                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 12px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
		                                   <span style="color: #a2a2a2">'.getLang('If_you_do_not_wish_any_mail').'.</span>												    
		                                </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;">
		                             		'.getUserLang('Best_regards', $this->input->post('user_id')).' <br>
		                             		<p style="margin:5px 0 0">'.getUserLang('Your_Castleevents_Team', $this->input->post('user_id')).'</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table></div>
										  </center>
									   </body>
									</html>';
		        //echo  $body.'='.$to; die; 
				if($template){
					  $cont='<!DOCTYPE html>
								<html>
								   <head>
									  <meta http-equiv="content-type" content="text/html" 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;
										 }
									  </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%" bgcolor="#222222" style="Margin: 0;">
									  <center style="width: 100%; background-color: #252530;" >
										 <div style="max-width: 600px; margin: 40px auto;">
										   
													 <table cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 800px;">
														<tr>
														   <td style="padding: 20px 0; text-align: center; background:#131218;">
															  <a href="'.base_url().'"><img src="'.base_url().'newsletter_image/new-logo-mail.png" width="250" alt="Castleevents" border="0"></a>
														   </td>
														</tr>
													 </table>'.$body.'</div>
										  </center>
									   </body>
									</html>';
					}
					else{
					 	$cont=$body;
					}
					 //echo $cont; die; 
					
		        if(!empty($visitEntry)) 
		        {
		        	if(date('Ymd') == date('Ymd', $visitEntry['created']))
		        	{
		        		//$mail = $mailin->send_email($data);
		        	}
		        	else
		        	{
		        		$this->email->message($cont);
						$mail = $this->email->send();
		        	} 
		        }
		        else
		        {
		        	$this->email->message($cont);
					$mail = $this->email->send();
		        }    
				//$this->utility->sendCIMail($to,$sub,$body);
						
			}
			/*****************VISIT MAIL****************/

			
			if(empty($visitEntry)){
				$this->common_model->insertData('feu_profilevisits',array('from_user_id'=>$this->session->userdata('user_id'),'to_user_id'=>$user['user_id'],'created'=>time()));	
			}
			else
			{
				$this->common_model->UpdateData('feu_profilevisits',array('created'=>time()),array('from_user_id'=>$this->session->userdata('user_id'),'to_user_id'=>$user['user_id']));
			}
			$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
			$content_data['loggeduserDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'','*,feu_userdetails.user_id') ;
			$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$user['user_id']),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'','*,feu_userdetails.user_id') ;
			$userLocations = $this->common_model->getAll('feu_addresses',array('user_id'=>$user['user_id'])); 
			
			if(empty($userLocations)){
				if($content_data['userDetials']['country_name']!=''){
					$new_add = $content_data['userDetials']['country_name'].', '.$content_data['userDetials']['capital_name'];
					$prepAddr = str_replace(' ','+',$new_add);
				    $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?key=AIzaSyBhS6E7uMfyWdUstf1PXpYiEFay86uUj4A&address='.$prepAddr.'&sensor=false');
				    $output= json_decode($geocode);
				    //pr($output);
				    if(!empty($output))
				    {
				    	if(!empty($output->results))
				    	{
				    		$latitude = $output->results[0]->geometry->location->lat;
						    $longitude = $output->results[0]->geometry->location->lng;
						    $addArr = array(
						    				'user_id'=>$user['user_id'],
						    				'address'=>$new_add,
						    				'user_lat'=>$latitude,
						    				'user_long'=>$longitude
						    				);
							$this->common_model->insertData('feu_addresses',$addArr);
				    	}
				    }
				}
			}
			$content_data['userLocations'] = $this->common_model->getAll('feu_addresses',array('user_id'=>$user['user_id'])); 
			$content_data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
			$content_data['loggedInUserMembershipDetails'] = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
			$content_data['userMembershipDetails'] = $this->users_model->getMembershipDetails($user['user_id']);
			$content_data['loggedInUserImages'] = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC') ;
			$userImages = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$user['user_id'],'filename !='=>'','free_membership_image'=>0),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC','*,sys_files.id as fileID') ;
			$userFreeImages = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$user['user_id'],'filename !='=>'','free_membership_image'=>1,'accepted'=>1),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC','*,sys_files.id as fileID') ;
			//echo $this->db->last_query();die;

			$userVideos = $this->common_model->getAll('sys_videos', array('accepted'=>1, 'user_id'=>$user['user_id']),'','','*, id as video_id');
			if(count($userVideos)>0){
				$this->load->library('s3_cloudfront');
				$my_config = $this->config->load('s3', true);
				$s3_config = $this->config->item('s3');
				$private_key_filename = $s3_config['cl_private_key'];
				$key_pair_id = $s3_config['cl_key_pair_id'];
				$expires = time() + 86400;
				foreach ($userVideos as $keys => $todaysVideos) {	
					$video_path = 'https://d3klt2dtr6705l.cloudfront.net/'.$todaysVideos['user_id'].'/'.$todaysVideos['filename'];				
					$link = $this->s3_cloudfront->get_canned_policy_stream_name($video_path, $private_key_filename, $key_pair_id, $expires);
					$userVideos[$keys]['videolink'] = $link;
				}
			}
			$userImages = array_merge($userImages,$userFreeImages);

			//$userImages = array_merge($userImages,$userFreeImages);
			//print_r($userImages); die;
			$content_data['userImages'] = $userImages;
			$content_data['userVideos'] = $userVideos;
			if(!empty($userImages))
			{
				$i = 0;
				foreach ($userImages as $value) {
					$userLikes = $this->common_model->getAllMultipleJoin('like_likes','',array(array('feu_userdetails','feu_userdetails.user_id = like_likes.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'like_likes.created DESC','*,feu_userdetails.user_id','',0,5,array('identifier'=>$value['fileID'])) ;
					$content_data['userImages'][$i]['likeUsers'] = $userLikes;
					$i++;
				}
			}
			$hasBlurImage = count($this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$user['user_id'],'is_private'=>1),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC')) ;
			$content_data['hasBlurImage'] = 0;
			if($hasBlurImage>0)
			{
				$content_data['hasBlurImage'] = 1;
			}
			$content_data['userPrivacy'] = $this->common_model->getAllRowMultipleJoin('ugal_images_user_privacy',array('from_user_id'=>$this->session->userdata('user_id'),'to_user_id'=>$user['user_id'])) ;
			$content_data['userPreferences'] = $this->common_model->getAll('feu_sexual_preference',array('user_id'=>$user['user_id']));
			//$content_data['userParticipation'] = $this->common_model->getAllMultipleJoin('event_guest',array('username'=>$content_data['userDetials']['username'],'event_guest.payment'=>1),array(array('evt_events','evt_events.id = event_guest.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'event_guest.confirmed','','event_guest.event_id');
			$lngID = 2;
			if($content_data['userDetials'])
			{
				$lngID = $content_data['userDetials']['userlanguage'];
			}
			$content_data['userParticipation'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_carts.user_id'=>$user['user_id'],'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0,'evt_language_values.lang_id'=>$lngID),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id');
			$ids = '';

			if(!empty($content_data['userParticipation']))
			{
				foreach ($content_data['userParticipation'] as $key => $value) {
					if($value['event_id']>0)
					{
						$ids = $ids.$value['event_id'].',';
					}
				}
			}
			if($ids != '')
			{
				$where = " `shop_carts`.`user_id` = ".$user['user_id']." AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0 and evt_events.id not in (".trim($ids,',').") AND evt_language_values.lang_id =".$lngID;
			}
			else
			{
				$where = " `shop_carts`.`user_id` = ".$user['user_id']." AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0 AND evt_language_values.lang_id =".$lngID;
			}
			$content_data['userParticipation_old'] = $this->common_model->getAllMultipleJoin('shop_orders',$where,array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_events.title,evt_events.alias','evt_events.id,shop_articles_carts.event_id');
			//$content_data['userParticipation_old'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_carts.user_id'=>$user['user_id'],'payed'=>1,'shop_articles_carts.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_events.title,evt_events.alias','shop_articles_carts.event_id');
			//$content_data['userParticipation'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$user['user_id']),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id')),'shop_orders.created','','shop_booking_details.cart_id');
			
			$content_data['latestMembers'] = $this->common_model->getAllMultipleJoin('feu_userdetails',array('avatar_file_id >'=>0,'feu_userdetails.user_id !='=>$this->session->userdata('user_id'),'filename !='=>''),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'RAND()','','',0,8);
			$content_data['comments'] = $this->common_model->getAllMultipleJoin('feu_userdetails',array('alias_path'=>'community/profil/'.$user['alias']),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('cmt_comments','cmt_comments.user_id = feu_userdetails.user_id')),'cmt_comments.created DESC','*,cmt_comments.created,cmt_comments.id','',0,8);
			$content_data['languages'] = $this->common_model->getAll('sys_languages') ;
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
			if(empty($data['upcomingEvents']))
			{
				$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
			}
			if(empty($data['lastEvents']))
			{
				$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
			}
			$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
			$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
			//echo $this->db->last_query();die;
			
			$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
			$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
			$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
			$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
			$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
			$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
			//$data['friend'] = $this->common_model->getAllRowMultipleJoin('feu_relationships',array('user_id_2'=>$user['user_id'],'type'=>'friend','status'=>'pending'));
			$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
			$data['title'] = getLang('Profile')." | ".$user['username'];
			$data['content'] = $this->load->view('other_profile', $content_data, TRUE);
			$this->load->view('template', $data);
		}
		else
		{
			redirect(base_url().'profile');
		}	
	}
	public function sendComment()
	{
		$from_id = $this->input->post('from_id');
		$alias = $this->input->post('alias');
		$comment = $this->utility->info_cleanQuery($this->input->post('cmt_text'));

		$text = $comment;
		if($this->session->userdata('user_id') != 11330)
		{
			$text = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i','',$text); // extract email
			$text = preg_replace('/(\d{5,})/', '', $text); // extract phonenumber
			$main = explode('@', $text);
			$pos = strpos($text,'@');
			if(count($main)>0 && $pos!==false)
			{
				if(count($main)>0)
					$start = explode(' ', trim($main[0]));
					array_pop($start);
					$text1 = implode(' ', $start);
				if(count($main)>1)
					$end = explode(' ', trim($main[1]));
					array_shift($end);
					$text2 = implode(' ', $end);
				$text = $text1.' '.$text2;	
			}
		}

		$arr = array(
					'created'=>time(),
					'user_id'=>$from_id,
					'alias_path'=>'community/profil/'.$alias,
					'comment'=>$text,
					'visible'=>1
					);
		$cmtId = $this->common_model->insertData('cmt_comments',$arr);
		$comments = $this->common_model->getAllMultipleJoin('feu_userdetails',array('alias_path'=>'community/profil/'.$alias),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('cmt_comments','cmt_comments.user_id = feu_userdetails.user_id')),'cmt_comments.created DESC','*,cmt_comments.created,cmt_comments.id','',0,8);
		$html='';
		if(!empty($comments))
		{
			foreach ($comments as $comment) {
				$html.='<div class="comment_list clearfix">
                           <a href="javascript:void(0)" class="avatar_small">                        
                           <img src="';
                            if(!empty($comment['filename']) && file_exists(FCPATH.'assets/userfiles/'.$comment['path'].'/'.$comment['filename'].'.'.$comment['extension']))
                            { 
                $html.=base_url().'assets/userfiles/'.$comment['path'].'/'.$comment['filename'].'.'.$comment['extension'];
                      		} 
                      		else 
                      		{ 
                $html.='images/default-avatar.jpg';
                      		}	
                $html.='" alt="">                         
                           </a>
                           <div class="cmntlist_content">
                              <span class="close_cmnt" data-id="'.$comment['id'].'" style="cursor:pointer;">x</span>
                              <h4><a href="javascript:void(0)">'.$comment['username'].'</a></h4>
                              <p>'.$comment['comment'].'</p>
                              <time><span class="time">'.date('d.m.Y H:i:s',$comment['created']).'</span></time>
                              <span class="type-commenticon"></span>
                           </div>
                        </div>';
			}
		}
		echo $html;exit;
	}
	public function addblockUser()
	{
		$user_id = $this->input->post('user_id');
		$type = $this->input->post('type');
		$from_id = $this->session->userdata('user_id');
		$getRecord = $this->common_model->getAllRow('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$user_id));
		$getOldRecord = $this->common_model->getAllRow('feu_relationships',array('user_id_2'=>$from_id,'user_id_1'=>$user_id));
		if(empty($getRecord) && empty($getOldRecord))
		{
			$this->common_model->insertData('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$user_id,'created'=>time(),'type'=>'friend','status'=>'pending'));
			$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$user_id,'type'=>1,'created'=>time()));
		}
		else
		{
			if($type==2)
			{
				$this->common_model->UpdateData('feu_relationships',array('type'=>'block','status'=>'accepted'),array('user_id_1'=>$from_id,'user_id_2'=>$user_id));
				$this->common_model->UpdateData('feu_relationships',array('type'=>'block','status'=>'accepted'),array('user_id_2'=>$from_id,'user_id_1'=>$user_id));
			}
			else
			{
				$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$user_id,'type'=>1,'created'=>time()));
				$this->common_model->UpdateData('feu_relationships',array('type'=>'friend','status'=>'pending'),array('user_id_1'=>$from_id,'user_id_2'=>$user_id));
				$this->common_model->UpdateData('feu_relationships',array('type'=>'friend','status'=>'pending'),array('user_id_2'=>$from_id,'user_id_1'=>$user_id));
			}
		}
		exit;
	}
	public function addblockUsersFromMembers()
	{
		$user_id = $this->input->post('user_id');
		$type = $this->input->post('type');
		$from_id = $this->session->userdata('user_id');
		$getRecord = $this->common_model->getAllRow('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$user_id));
		//echo $this->db->last_query();
		$getOldRecord = $this->common_model->getAllRow('feu_relationships',array('user_id_2'=>$from_id,'user_id_1'=>$user_id));
		//echo $this->db->last_query();
		if(empty($getRecord) && empty($getOldRecord))
		{
			$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$user_id,'type'=>1,'created'=>time()));
			$this->common_model->insertData('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$user_id,'created'=>time(),'type'=>'friend','status'=>'pending'));
			echo getLang('Connected__please_wait');
		}
		else
		{
			if(isset($getRecord['status']) && $getRecord['status']=='accepted' && isset($getRecord['type']) && $getRecord['type']=='friend')
			{
				echo getLang('Already_conected');
			}
			elseif(isset($getOldRecord['status']) && $getOldRecord['status']=='accepted' && isset($getOldRecord['type']) && $getOldRecord['type']=='friend')
			{
				echo getLang('Already_conected');
			}
			else
			{
				if($type==2)
				{
					$this->common_model->UpdateData('feu_relationships',array('type'=>'block','status'=>'accepted'),array('user_id_1'=>$from_id,'user_id_2'=>$user_id));
					$this->common_model->UpdateData('feu_relationships',array('type'=>'block','status'=>'accepted'),array('user_id_2'=>$from_id,'user_id_1'=>$user_id));
				}
				else
				{
					$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$user_id,'type'=>1,'created'=>time()));
					$this->common_model->UpdateData('feu_relationships',array('type'=>'friend','status'=>'pending'),array('user_id_1'=>$from_id,'user_id_2'=>$user_id));
					$this->common_model->UpdateData('feu_relationships',array('type'=>'friend','status'=>'pending'),array('user_id_2'=>$from_id,'user_id_1'=>$user_id));
					echo getLang('Connected__please_wait');
				}
			}
		}
		exit;
	}
	public function deleteComment()
	{
		$cmt_id = $this->input->post('cmt_id');
		$this->common_model->deleteData('cmt_comments',array('id'=>$cmt_id));exit;
	}
	
	public function getRequest()
	{
		$userMembershipDetails = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		$usersFeuDetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		$usersDetail = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));
		$membershipDeta = $this->common_model->getAllRow('shop_orders',array('invoiceAddress'=>$usersDetail['email'],'is_booking'=>0,'payed'=>1),'','created DESC');
		//pr($membershipDeta);
		$not_member = 0;
		$blur_not_member_class = '';
		$notPics = '';
		if($membershipDeta) {
			$notPics = 'notPics';
			if(($membershipDeta['created']+($membershipDeta['time']*86400)) < time()){
				$not_member = 1;
				$blur_not_member_class = 'blur_msg';
				$notPics = '';
			}
		}
		if(empty($userMembershipDetails))
		{
			$userMembershipDetails['id']=0;
		}
		$userImages = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id'),'filename !='=>''),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC') ;
		$qry = "SELECT *, `notification`.`created` FROM `notification` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `notification`.`from_id` JOIN `sys_files` ON `sys_files`.`id` = `feu_userdetails`.`avatar_file_id` WHERE ((to_id = ".$this->session->userdata('user_id').") OR (`to_id` = 1 and `type` in (11,12,13) and from_id != ".$this->session->userdata('user_id').")) and `read_unread` =0 and filename != '' ORDER BY `notification`.`created` DESC";
		//$qry = "SELECT *, `notification`.`created` FROM `notification` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `notification`.`from_id` JOIN `sys_files` ON `sys_files`.`id` = `feu_userdetails`.`avatar_file_id` WHERE ((to_id = ".$this->session->userdata('user_id').") OR (`to_id` = 1 and `type` in (11,12,13) and from_id != ".$this->session->userdata('user_id').")) and `notification`.`created` > ".(time()-86400)." and `read_unread` =0 and filename != '' ORDER BY `notification`.`created` DESC LIMIT 50";
		$notificationQry = $this->db->query($qry);
		$notifications = $notificationQry->result_array();

		$tot_qry = "SELECT *, `notification`.`created` FROM `notification` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `notification`.`from_id` JOIN `sys_files` ON `sys_files`.`id` = `feu_userdetails`.`avatar_file_id` WHERE ((to_id = ".$this->session->userdata('user_id').") OR (`to_id` = 1 and `type` in (11,12,13) and from_id != ".$this->session->userdata('user_id').")) and `notification`.`created` > ".$usersDetail['last_login']." and `read_unread` =0 and filename != '' ORDER BY `notification`.`created` DESC";
		$tot_notificationQry = $this->db->query($tot_qry);
		//echo $this->db->last_query(); die;
		//$tot_notifications = $tot_notificationQry->result_array();
		//print_r($tot_notifications); die;
		$tot_notifications = array();
		if($tot_notificationQry !== FALSE && $tot_notificationQry->num_rows() > 0){
		    $tot_notifications = $tot_notificationQry->result_array();
		}
		$html='';
		$fileDetails = array();
		$partyDetails = array();
		//echo $userMembershipDetails['id'].'|'.$usersFeuDetails['free_member'];die;
		if(($userMembershipDetails['id']>0) || $usersFeuDetails['free_member']==1)
		{
			if(!empty($notifications))
			{
				$fileDetails = array();
				$partyDetails = array();
				foreach ($notifications as $key => $notify) 
				{
					if($key<50)
					{
						$fileDetails = array();
						$partyDetails = array();
						$html.='<li class="'.$blur_not_member_class.'"><div class="messageBoxes"><a href="'.base_url().'profil/'.$notify['alias'].'" class="avatar_profile">';
						if(!empty($notify['filename']) && file_exists(FCPATH.'assets/userfiles/'.$notify['path'].'/80/'.$notify['filename'].'.'.$notify['extension']))
						{ 
							$image = base_url().'assets/userfiles/'.$notify['path'].'/80/'.$notify['filename'].'.'.$notify['extension']; 
							$image1 = base_url().'assets/userfiles/'.$notify['path'].'/160/'.$notify['filename'].'.'.$notify['extension']; 
						} 
						else 
						{ 
							$image = base_url().'assets/images/default-avatar.jpg';
							$image1 = base_url().'assets/images/default-avatar.jpg';
						}
						if($notify['file_id']>0)
						{
							//$filedata = getValue('sys_files',array('id'=>$notify['file_id']));
							$filedata = getValues(array('sys_files.id'=>$notify['file_id']));
							//echo $this->db->last_query();
							if(!empty($filedata))
							{
								if($filedata['is_private']==1){
									if(isset($filedata['filename']) && file_exists(FCPATH.'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'_blur.'.$filedata['extension']))
									{
										$fileDetails = base_url().'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'_blur.'.$filedata['extension']; 
									}
									else 
									{ 
										$fileDetails = base_url().'assets/images/default-avatar.jpg';
									}
								}
								else{
									if(isset($filedata['filename']) && file_exists(FCPATH.'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'.'.$filedata['extension']))
									{
										$fileDetails = base_url().'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'.'.$filedata['extension']; 
									}
									else 
									{ 
										$fileDetails = base_url().'assets/images/default-avatar.jpg';
									}
								}
							}
							else
							{
								$fileDetails = base_url().'assets/images/default-avatar.jpg';
							}
						}
						if($notify['request_id']>0)
						{
							$partydata = $this->common_model->getAllRowMultipleJoin('evt_event_files',array('event_id'=>$notify['request_id']),array(array('sys_files','sys_files.id = evt_event_files.file_id')));
							if(isset($partydata['filename']) && file_exists(FCPATH.'assets/userfiles/'.$partydata['path'].'/'.$partydata['filename'].'.'.$partydata['extension']))
							{
								$partyDetails = base_url().'assets/userfiles/'.$partydata['path'].'/'.$partydata['filename'].'.'.$partydata['extension']; 
							}
						}
						$toUserDetails = getValue('feu_userdetails',array('user_id'=>$notify['to_id']));
						//print_r($partyDetails); 
						if($userMembershipDetails['id']==5 && count($userImages)<3)
						{
							$html.='<img src="'.$image.'" alt="" srcset="'.$image.' 1x, '.$image1.' 2x" class="">';
							//$html.='<img src="'.$image.'" alt="" srcset="'.$image.' 1x, '.$image1.' 2x" class="blur_profile">';
						}
						else
						{
							$html.='<img src="'.$image.'" alt="" srcset="'.$image.' 1x, '.$image1.' 2x">';
						}
						$html.='</a>
						<div class="msgContent">';
						if($notify['file_id']>0 && $fileDetails!='')
						{
							if($userMembershipDetails['id']==5 || count($userImages)<3)
							{
								$html.='<div class="pic files '.$notPics.'" data-file="'.$notify['file_id'].'" data-pic="'.$fileDetails.'" data-source="'.$notify['request_id'].'"><div style="background:url('.$fileDetails.') no-repeat center center / cover;"></div></div>';
							}
							else
							{
								$html.='<div class="pic files '.$notPics.'" data-file="'.$notify['file_id'].'" data-pic="'.$fileDetails.'" data-source="'.$notify['request_id'].'"><div style="background:url('.$fileDetails.') no-repeat center center / cover;"></div></div>';
							}
							//$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.resizeImage($fileDetails).') no-repeat center center / cover;"></div></div>';
						}
						if($notify['request_id']>0 && $partyDetails!='')
						{
							if($userMembershipDetails['id']==5 || count($userImages)<3)
							{
								$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.$partyDetails.') no-repeat center center / cover;"></div></div>';
							}
							else
							{
								$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.$partyDetails.') no-repeat center center / cover;"></div></div>';
							}
							//$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.resizeImage($partyDetails).') no-repeat center center / cover;"></div></div>';
						}
						if($notify['video_id']>0)
						{
							$videodata = $this->common_model->getAllRow('sys_videos',array('id'=>$notify['video_id']));
							if(isset($videodata['filename'])){
								$video_name = explode('.', $videodata['filename']);
								if(count($video_name)>1){
									if(file_exists(FCPATH.'assets/videos/uploads/thumb/'.$video_name[0].'.jpg')){
										$html.='<div class="pic files '.$notPics.'" ><div style="background:url('.base_url().'assets/videos/uploads/thumb/'.$video_name[0].'.jpg) no-repeat center center / cover;"></div></div>';
									}
								}
							}
												
						}
						$html.='<div class="textcont">';
						$html.='<h4><a href="'.base_url().'profil/'.$notify['alias'].'">'.$notify['username'].'</a></h4>';
						if($notify['type']==1)
		                {
		                	$html.='<p>'.getLang('send_you_connection_request').'</a> </p>';
		                }
		                if($notify['type']==2)
		                {
		                	$html.='<p>'.getLang('accepted_your_connection_request').'</a> </p>';
		                }
		                if($notify['type']==3)
		                {
		                	$html.='<p>'.getLang('rejected_your_connection_request').'</a> </p>';
		                }
		                if($notify['type']==4)
		                {
		                	$html.='<p><a href="'.base_url().'messages/'.base64_encode($notify['from_id']).'">'.getLang('send_you_message').'</a> </p>';
		                }
		                if($notify['type']==5)
		                {
		                	$html.='<p>'.getLang('send_you_private_picture').'</a> </p>';
		                }
		                if($notify['type']==6)
		                {
		                	$html.='<p>'.getLang('accept_your_private_picture').'</a> </p>';
		                }
		                if($notify['type']==7)
		                {
		                	$html.='<p>'.getLang('reject_your_private_picture').'</a> </p>';
		                }
		                if($notify['type']==8)
		                {
		                	$html.='<p>'.getLang('send_you_a_hotshot').'</a> </p>';
		                }
		                if($notify['type']==9)
		                {
		                	$html.='<p>'.getLang('send_you_a_picture_hotshot').'</a> </p>';
		                }
		                if($notify['type']==10)
		                {
		                	$html.='<p>'.getLang('visited_your_profile').'</a> </p>';
		                }
		                if($notify['type']==11)
		                {
		                	$html.='<p>'.getLang('new_memberhsip_registration').'</a> </p>';
		                }
		                if($notify['type']==12)
		                {
		                	$html.='<p>'.getLang('upload_new_picture').'</a> </p>';
		                }
		                if($notify['type']==13)
		                {
		                	$html.='<p>'.getLang('send_a_party_hotshot').'</a> </p>';
		                }
		                if($notify['type']==15)
		                {
		                	$html.='<p>'.getLang('upload_new_video').'</a></p>';
		                }

		                $html.='<span class="time">'.get_time_ago($notify['created']).'</span>';
						if($notify['type']==1)
						{
							$html.=' <a href="javascript:void(0);" class="accept" data-type="1" data-id="'.$notify['from_id'].'" style="cursor: pointer; margin: 0 5px; "><i class="fa fa-check"></i></a> <a href="javascript:void(0);" class="accept" data-type="0" data-id="'.$notify['from_id'].'" style="cursor: pointer;"><i class="fa fa-trash"></i></a> ';
						}
						if($notify['type']==5)
						{
							$html.=' <a href="javascript:void(0);" class="accept_privacy" data-type="1" data-id="'.$notify['from_id'].'" style="cursor: pointer; margin: 0 5px; "><i class="fa fa-check"></i></a> <a href="javascript:void(0);" class="accept_privacy" data-type="0" data-id="'.$notify['from_id'].'" style="cursor: pointer;"><i class="fa fa-trash"></i></a> ';
						}
						$html.='</div></div></div></li>';
					}
				}
				if(count($notifications)>50 && $userMembershipDetails['id']==4)
				{
					$html.='<li><div class="ajax-loader_msg" style="display:none;">
	        <img src="images/Rolling.svg" class="img-responsive" />
	      </div><div class="messageBoxes load_more_msg" data-id="50" style="cursor:pointer;text-align: center;">'.getLang('Read_more').'</div></li>';
				}
			}
			else
			{
				$html.='<li><div class="messageBoxes">'.getLang('No_notification_found').'</div></li>';
			}
			echo $html.'|'.count($tot_notifications);
		}
		else
		{
			$html.='<li><div class="messageBoxes">'.getLang('No_notification_found').'</div></li>';
			echo $html.'|'.'0';
		}
		
		exit;
	}
	public function getRequestNext()
	{
		$limit = $this->input->post('limit');
		$userMembershipDetails = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		
		$userImages = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id'),'filename !='=>''),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC') ;
		$qry = "SELECT *, `notification`.`created` FROM `notification` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `notification`.`from_id` JOIN `sys_files` ON `sys_files`.`id` = `feu_userdetails`.`avatar_file_id` WHERE ((to_id = ".$this->session->userdata('user_id').") OR (`to_id` = 1 and `type` in (11,12,13) and from_id != ".$this->session->userdata('user_id').")) and `read_unread` =0 and filename != '' ORDER BY `notification`.`created` DESC limit 50, ".$limit;
		//$qry = "SELECT *, `notification`.`created` FROM `notification` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `notification`.`from_id` JOIN `sys_files` ON `sys_files`.`id` = `feu_userdetails`.`avatar_file_id` WHERE ((to_id = ".$this->session->userdata('user_id').") OR (`to_id` = 1 and `type` in (11,12,13) and from_id != ".$this->session->userdata('user_id').")) and `notification`.`created` > ".(time()-86400)." and `read_unread` =0 and filename != '' ORDER BY `notification`.`created` DESC LIMIT 50";
		$notificationQry = $this->db->query($qry);
		$notifications = $notificationQry->result_array();
		//echo count($notifications);die;
		$tot_notifications = array();
		$html='';
		$fileDetails = array();
		$partyDetails = array();
		if(!empty($notifications))
		{
			$fileDetails = array();
			$partyDetails = array();
			foreach ($notifications as $key => $notify) 
			{
					$fileDetails = array();
					$partyDetails = array();
					$html.='<li><div class="messageBoxes"><a href="'.base_url().'profil/'.$notify['alias'].'" class="avatar_profile">';
					if(!empty($notify['filename']) && file_exists(FCPATH.'assets/userfiles/'.$notify['path'].'/80/'.$notify['filename'].'.'.$notify['extension']))
					{ 
						$image = base_url().'assets/userfiles/'.$notify['path'].'/80/'.$notify['filename'].'.'.$notify['extension']; 
						$image1 = base_url().'assets/userfiles/'.$notify['path'].'/160/'.$notify['filename'].'.'.$notify['extension']; 
					} 
					else 
					{ 
						$image = base_url().'assets/images/default-avatar.jpg';
						$image1 = base_url().'assets/images/default-avatar.jpg';
					}
					if($notify['file_id']>0)
					{
						//$filedata = getValue('sys_files',array('id'=>$notify['file_id']));
						$filedata = getValues(array('sys_files.id'=>$notify['file_id']));
						//echo $this->db->last_query();
						if(!empty($filedata))
						{
							if($filedata['is_private']==1){
								if(isset($filedata['filename']) && file_exists(FCPATH.'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'_blur.'.$filedata['extension']))
								{
									$fileDetails = base_url().'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'_blur.'.$filedata['extension']; 
								}
								else 
								{ 
									$fileDetails = base_url().'assets/images/default-avatar.jpg';
								}
							}
							else{
								if(isset($filedata['filename']) && file_exists(FCPATH.'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'.'.$filedata['extension']))
								{
									$fileDetails = base_url().'assets/userfiles/'.$filedata['path'].'/'.$filedata['filename'].'.'.$filedata['extension']; 
								}
								else 
								{ 
									$fileDetails = base_url().'assets/images/default-avatar.jpg';
								}
							}
						}
						else
						{
							$fileDetails = base_url().'assets/images/default-avatar.jpg';
						}
					}
					if($notify['request_id']>0)
					{
						$partydata = $this->common_model->getAllRowMultipleJoin('evt_event_files',array('event_id'=>$notify['request_id']),array(array('sys_files','sys_files.id = evt_event_files.file_id')));
						if(isset($partydata['filename']) && file_exists(FCPATH.'assets/userfiles/'.$partydata['path'].'/'.$partydata['filename'].'.'.$partydata['extension']))
						{
							$partyDetails = base_url().'assets/userfiles/'.$partydata['path'].'/'.$partydata['filename'].'.'.$partydata['extension']; 
						}
					}
					$toUserDetails = getValue('feu_userdetails',array('user_id'=>$notify['to_id']));
					//print_r($partyDetails); 
					if($userMembershipDetails['id']==5 && count($userImages)<3)
					{
						$html.='<img src="'.$image.'" alt="" srcset="'.$image.' 1x, '.$image1.' 2x" class="">';
						//$html.='<img src="'.$image.'" alt="" srcset="'.$image.' 1x, '.$image1.' 2x" class="blur_profile">';
					}
					else
					{
						$html.='<img src="'.$image.'" alt="" srcset="'.$image.' 1x, '.$image1.' 2x">';
					}
					$html.='</a>
					<div class="msgContent">';
					if($notify['file_id']>0 && $fileDetails!='')
					{
						if($userMembershipDetails['id']==5 || count($userImages)<3)
						{
							$html.='<div class="pic files notPics" data-file="'.$notify['file_id'].'" data-pic="'.$fileDetails.'" data-source="'.$notify['request_id'].'"><div style="background:url('.$fileDetails.') no-repeat center center / cover;"></div></div>';
						}
						else
						{
							$html.='<div class="pic files notPics" data-file="'.$notify['file_id'].'" data-pic="'.$fileDetails.'" data-source="'.$notify['request_id'].'"><div style="background:url('.$fileDetails.') no-repeat center center / cover;"></div></div>';
						}
						//$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.resizeImage($fileDetails).') no-repeat center center / cover;"></div></div>';
					}
					if($notify['request_id']>0 && $partyDetails!='')
					{
						if($userMembershipDetails['id']==5 || count($userImages)<3)
						{
							$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.$partyDetails.') no-repeat center center / cover;"></div></div>';
						}
						else
						{
							$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.$partyDetails.') no-repeat center center / cover;"></div></div>';
						}
						//$html.='<div class="pic files" data-file="'.$notify['file_id'].'" data-source="'.$notify['request_id'].'"><div style="background:url('.resizeImage($partyDetails).') no-repeat center center / cover;"></div></div>';
					}
					if($notify['video_id']>0)
					{
						$videodata = $this->common_model->getAllRow('sys_videos',array('id'=>$notify['video_id']));
						if(isset($videodata['filename'])){
							$video_name = explode('.', $videodata['filename']);
							if(count($video_name)>1){
								if(file_exists(FCPATH.'assets/videos/uploads/thumb/'.$video_name[0].'.jpg')){
									$html.='<div class="pic files '.$notPics.'" ><div style="background:url('.base_url().'assets/videos/uploads/thumb/'.$video_name[0].'.jpg) no-repeat center center / cover;"></div></div>';
								}
							}
						}
											
					}
					$html.='<div class="textcont">';
					$html.='<h4><a href="'.base_url().'profil/'.$notify['alias'].'">'.$notify['username'].'</a></h4>';
					if($notify['type']==1)
	                {
	                	$html.='<p>'.getLang('send_you_connection_request').'</a> </p>';
	                }
	                if($notify['type']==2)
	                {
	                	$html.='<p>'.getLang('accepted_your_connection_request').'</a> </p>';
	                }
	                if($notify['type']==3)
	                {
	                	$html.='<p>'.getLang('rejected_your_connection_request').'</a> </p>';
	                }
	                if($notify['type']==4)
	                {
	                	$html.='<p><a href="'.base_url().'messages/'.base64_encode($notify['from_id']).'">'.getLang('send_you_message').'</a> </p>';
	                }
	                if($notify['type']==5)
	                {
	                	$html.='<p>'.getLang('send_you_private_picture').'</a> </p>';
	                }
	                if($notify['type']==6)
	                {
	                	$html.='<p>'.getLang('accept_your_private_picture').'</a> </p>';
	                }
	                if($notify['type']==7)
	                {
	                	$html.='<p>'.getLang('reject_your_private_picture').'</a> </p>';
	                }
	                if($notify['type']==8)
	                {
	                	$html.='<p>'.getLang('send_you_a_hotshot').'</a> </p>';
	                }
	                if($notify['type']==9)
	                {
	                	$html.='<p>'.getLang('send_you_a_picture_hotshot').'</a> </p>';
	                }
	                if($notify['type']==10)
	                {
	                	$html.='<p>'.getLang('visited_your_profile').'</a> </p>';
	                }
	                if($notify['type']==11)
	                {
	                	$html.='<p>'.getLang('new_memberhsip_registration').'</a> </p>';
	                }
	                if($notify['type']==12)
	                {
	                	$html.='<p>'.getLang('upload_new_picture').'</a> </p>';
	                }
	                if($notify['type']==13)
	                {
	                	$html.='<p>'.getLang('send_a_party_hotshot').'</a> </p>';
	                }
	                if($notify['type']==15)
	                {
	                	$html.='<p>'.getLang('upload_new_video').'</a> </p>';
	                }

	                $html.='<span class="time">'.get_time_ago($notify['created']).'</span>';
					if($notify['type']==1)
					{
						$html.=' <a href="javascript:void(0);" class="accept" data-type="1" data-id="'.$notify['from_id'].'" style="cursor: pointer; margin: 0 5px; "><i class="fa fa-check"></i></a> <a href="javascript:void(0);" class="accept" data-type="0" data-id="'.$notify['from_id'].'" style="cursor: pointer;"><i class="fa fa-trash"></i></a> ';
					}
					if($notify['type']==5)
					{
						$html.=' <a href="javascript:void(0);" class="accept_privacy" data-type="1" data-id="'.$notify['from_id'].'" style="cursor: pointer; margin: 0 5px; "><i class="fa fa-check"></i></a> <a href="javascript:void(0);" class="accept_privacy" data-type="0" data-id="'.$notify['from_id'].'" style="cursor: pointer;"><i class="fa fa-trash"></i></a> ';
					}
					$html.='</div></div></div></li>';
				
			}
			$html.='<li><div class="ajax-loader_msg" style="display:none;">
        <img src="images/Rolling.svg" class="img-responsive" />
      </div><div class="messageBoxes load_more_msg" data-id="'.($limit+50).'" style="cursor:pointer;text-align: center;">'.getLang('Read_more').'</div></li>';
			
		}
		else
		{
			$html.='<li><div class="messageBoxes">'.getLang('No_notification_found').'</div></li>';
		}
		echo $html.'|'.count($tot_notifications);
		exit;
	}

	public function accept()
	{
		$from_id = $this->input->post('user_id');
		$type = $this->input->post('type');
		$to_id = $this->session->userdata('user_id');
		if($type==1)
		{
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>1));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>2,'created'=>time()));
			$this->common_model->UpdateData('feu_relationships',array('status'=>'accepted','type'=>'friend'),array('user_id_1'=>$from_id,'user_id_2'=>$to_id));
		}
		else
		{
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>1));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>3,'created'=>time()));
			$this->common_model->deleteData('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$to_id));
		}
		exit;
	}
	public function accept_privacy()
	{
		$from_id = $this->input->post('user_id');
		$type = $this->input->post('type');
		$to_id = $this->session->userdata('user_id');
		if($type==1)
		{
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>5));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>6,'created'=>time()));
			$this->common_model->UpdateData('ugal_images_user_privacy',array('privacy'=>1),array('from_user_id'=>$from_id,'to_user_id'=>$to_id));
			$alreadyInContact = $this->common_model->getAllRow('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$to_id));
			if($alreadyInContact){
				$this->common_model->UpdateData('feu_relationships',array('status'=>'accepted','type'=>'friend'),array('user_id_1'=>$from_id,'user_id_2'=>$to_id));
			} else {
				$this->common_model->insertData('feu_relationships',array('status'=>'accepted','type'=>'friend','user_id_1'=>$from_id,'user_id_2'=>$to_id,'created'=>time()));
			}
		}
		else
		{
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>5));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>7,'created'=>time()));
			$this->common_model->deleteData('ugal_images_user_privacy',array('from_user_id'=>$from_id,'to_user_id'=>$to_id));
		}
		exit;
	}
	public function settings()
	{
		$referer = $_SERVER['HTTP_REFERER'];
		if($referer){
			$type = 0;
			$user_id = $this->session->userdata('user_id');
			$referer_exp_base_url = explode(base_url(), $referer);
			$referer_exp = explode('/', end($referer_exp_base_url));
			//print_r($referer_exp_base_url);die;
			if(count($referer_exp) > 0){
				if($referer_exp[0]=='messages'){
					$type = 1;
				} else if($referer_exp[0]=='profil'){
					$type = 2;
				} else if($referer_exp[0]=='parties'){
					$type = 3;
				} else if($referer_exp[0]=='members'){
					$type = 4;
				}
				if($type > 0){
					$usr_activity_to_premium = $this->common_model->getAllRow('usr_activity_to_premium',array('users_id'=>$user_id,'type'=>$type));//print_r($usr_activity_to_premium);die;
					$user_membership = $this->common_model->getAllRowMultipleJoin('shop_orders', array('shop_orders.is_booking'=>0, 'shop_orders.cancelled'=>0, 'payed'=>1, 'user_id'=>$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(!$usr_activity_to_premium && ($article_id == 5 || $article_id == 0)){
						$this->common_model->insertData('usr_activity_to_premium',array('users_id'=>$user_id,'type'=>$type,'created_at'=>time()));
					}
				}
			}
		}
		
		if($this->input->post())
		{
			$inputPassword ='';
			if($this->input->post('new_password') && ($this->input->post('new_password')==$this->input->post('confirm_password')))
			{
				$inputPassword  = $this->common_model->generateHash($this->input->post('confirm_password'));
			}
			if($this->input->post('preferences')!='full_swap')
			{
				$same_room = 0;
				$separate_room = 0;
			}
			else
			{
				$same_room = $this->input->post('same_room');
				$separate_room = $this->input->post('separate_room');
			}

			$about = $this->utility->info_cleanQuery($this->input->post('about'));
			
			$text = $about;
			$text = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i','',$text); // extract email
			$text = preg_replace('/(\d{5,})/', '', $text); // extract phonenumber
			$main = explode('@', $text);
			$pos = strpos($text,'@');
			if(count($main)>0 && $pos!==false)
			{
				if(count($main)>0)
					$start = explode(' ', trim($main[0]));
					array_pop($start);
					$text1 = implode(' ', $start);
				if(count($main)>1)
					$end = explode(' ', trim($main[1]));
					array_shift($end);
					$text2 = implode(' ', $end);
				$text = $text1.' '.$text2;	
			}
			$arr = array(
						'about'=>$text,
						'country'=>$this->input->post('country'),
						'interested_in_ladies'=>$this->input->post('interest_lady'),
						'interested_in_couples'=>$this->input->post('interest_couples'),
						'interested_in_gentlemen'=>$this->input->post('interest_gentleman'),
						'interested_in_private_meeting'=>$this->input->post('interest_private'),
						'interested_financial_interests'=>$this->input->post('interested_financial_interests'),
						'escort_interest'=>$this->input->post('escort_interest'),
						'dob_lady'=>strtotime($this->input->post('she_year').'-'.$this->input->post('she_month').'-'.$this->input->post('she_date')),
						'dob_gentleman'=>strtotime($this->input->post('he_year').'-'.$this->input->post('he_month').'-'.$this->input->post('he_date')),
						'physis_lady'=>$this->input->post('she_physis'),
						'physis_gentleman'=>$this->input->post('he_physis'),
						'preferences'=>$this->input->post('preferences'),
						'she_height'=>$this->input->post('she_height')?$this->input->post('she_height'):0,
						'she_weight'=>$this->input->post('she_weight')?$this->input->post('she_weight'):0,
						'he_height'=>$this->input->post('he_height')?$this->input->post('he_height'):0,
						'he_weight'=>$this->input->post('he_weight')?$this->input->post('he_weight'):0,
						'experience'=>$this->input->post('experience')?$this->input->post('experience'):0,
						'same_room'=>$same_room,
						'separate_room'=>$separate_room,
						'visitor_mail'=>$this->input->post('visitor_mail')?$this->input->post('visitor_mail'):0,
						'subscribe'=>$this->input->post('unsub')?$this->input->post('unsub'):0,
						//'mobile_number'=>$this->input->post('mobile_number')?$this->input->post('mobile_number'):0,
						);
			$update = $this->common_model->UpdateData('feu_userdetails',$arr,array('user_id'=>$this->session->userdata('user_id')));
			
			if($this->input->post('subs'))
			{
				$userdata = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
				$this->common_model->UpdateData('feu_userdetails',array('subscribe'=>1),array('user_id'=>$this->session->userdata('user_id')));
				$apiKey = "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";
				if($userdata['userlanguage']==1) {
					$list_id = "0d39d0f4-79dd-468e-b4dc-1f2530f3d4f2";
				} elseif($userdata['userlanguage']==2) {
					$list_id = "73aea249-0467-42ca-aa41-71fa61aacd71";
				} else {
					$list_id = "2b3fb3b4-686f-4504-8757-f61ec725dc53";
				}
				$contacts = [];
				$arr['email'] = $userdata['email'];
				$arr['username'] = $userdata['username'];	
				array_push($contacts, $arr);
				$postData = [
					'list_ids' => [$list_id],
					'contacts' => $contacts
				];
				//print_r($postData);
				//echo json_encode($postData);
				$curl = curl_init();
				curl_setopt_array($curl, array(
				  CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
				  CURLOPT_RETURNTRANSFER => true,
				  CURLOPT_ENCODING => "",
				  CURLOPT_MAXREDIRS => 10,
				  CURLOPT_TIMEOUT => 30,
				  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				  CURLOPT_CUSTOMREQUEST => "PUT",
				  CURLOPT_POSTFIELDS => json_encode($postData),
				  CURLOPT_HTTPHEADER => array(
				    "authorization: Bearer ".$apiKey,
				    "content-type: application/json"
				  ),
				));

				$response = curl_exec($curl);
				$err = curl_error($curl);

				curl_close($curl);
				if ($err) {
				  //echo "cURL Error #:" . $err;
				} else {
				  //echo $response;
				}
			}

			if($this->input->post('unsub')) {
				$userdata = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
				$this->common_model->UpdateData('feu_userdetails',array('subscribe'=>0),array('user_id'=>$this->session->userdata('user_id')));
				
				$apiKey = "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";
				$this->load->model('common_model');
				$curl = curl_init();
				$unemail = $userdata['email'];
				curl_setopt_array($curl, array(
				  CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts/search/emails",
				  CURLOPT_RETURNTRANSFER => true,
				  CURLOPT_ENCODING => "",
				  CURLOPT_MAXREDIRS => 10,
				  CURLOPT_TIMEOUT => 30,
				  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				  CURLOPT_CUSTOMREQUEST => "POST",
				  CURLOPT_POSTFIELDS => "{\"emails\":[\"$unemail\"]}",
				  CURLOPT_HTTPHEADER => array(
				    "authorization: Bearer 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",
				    "content-type: application/json"
				  ),
				));

				$response = curl_exec($curl);
				$err = curl_error($curl);

				curl_close($curl);
				if ($err) {
				  //echo 2;die;
				} else {
				  	$outout = json_decode($response, true);
				  	//pr($outout);
				  	$ids = '';
					if(isset($outout['result'])) {
						if(isset($outout['result'][$userdata['email']])) {
							if(isset($outout['result'][$userdata['email']]['contact'])) {
								$ids = $outout['result'][$userdata['email']]['contact']['id'];
							}
						}
					}
				  /*delete*/
				  	if($ids) {
					  	$curl = curl_init();
						curl_setopt_array($curl, array(
						  CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts?ids=".$ids,
						  CURLOPT_RETURNTRANSFER => true,
						  CURLOPT_ENCODING => "",
						  CURLOPT_MAXREDIRS => 10,
						  CURLOPT_TIMEOUT => 30,
						  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
						  CURLOPT_CUSTOMREQUEST => "DELETE",
						  CURLOPT_POSTFIELDS => "{}",
						  CURLOPT_HTTPHEADER => array(
						    "authorization: Bearer ".$apiKey,
						  ),
						));
						$response = curl_exec($curl);
						$err = curl_error($curl);
						curl_close($curl);
					}
				}
			}

			//print_r($this->input->post()); die;
			if($inputPassword !='')
			{
				$this->common_model->UpdateData('usr_users',array('password'=>$inputPassword),array('id'=>$this->session->userdata('user_id')));
			}
			if($this->input->post('couple_alter_email'))
			{
				$this->common_model->UpdateData('usr_users',array('couples_alter_email'=>$this->input->post('couple_alter_email')),array('id'=>$this->session->userdata('user_id')));
			}
			$sexual_preference = $this->input->post('sexual_preference');
			if(!empty($sexual_preference))
			{
				$this->common_model->deleteData('feu_sexual_preference',array('user_id'=>$this->session->userdata('user_id')));
				foreach ($sexual_preference as $key => $value) {
					$arr = array(
							'user_id'=>$this->session->userdata('user_id'),
							'sex_preference'=>$value,
					);
					$this->common_model->insertData('feu_sexual_preference',$arr);
				}
			}
			if($this->input->post('location'))
			{
				$prepAddr = str_replace(' ','+',$this->input->post('location'));
			    $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?key=AIzaSyBhS6E7uMfyWdUstf1PXpYiEFay86uUj4A&address='.$prepAddr.'&sensor=false');
			    $output= json_decode($geocode);
			    
			    if(!empty($output))
			    {
			    	if(!empty($output->results))
			    	{
			    		$latitude = $output->results[0]->geometry->location->lat;
					    $longitude = $output->results[0]->geometry->location->lng;
					    $addArr = array(
					    				'user_id'=>$this->session->userdata('user_id'),
					    				'address'=>$this->input->post('location'),
					    				'user_lat'=>$latitude,
					    				'user_long'=>$longitude
					    				);
						$this->common_model->insertData('feu_addresses',$addArr);
			    	}
			    }
			    else
			    {
			    
			    	$addArr = array(
				    				'user_id'=>$this->session->userdata('user_id'),
				    				'address'=>$this->input->post('location'),
				    				'user_lat'=>0,
				    				'user_long'=>0
				    				);
					$this->common_model->insertData('feu_addresses',$addArr);
			    }
			}
			if($update)
			{
				redirect(base_url().'setting');
			}
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$content_data['userAddress'] = $this->common_model->getAll('feu_addresses',array('user_id'=>$this->session->userdata('user_id')));
		$content_data['userAlterEmails'] = $this->common_model->getAll('usr_alter_email',array('user_id'=>$this->session->userdata('user_id'), 'confirmed'=>1));
		$content_data['userPhones'] = $this->common_model->getAll('usr_phones',array('user_id'=>$this->session->userdata('user_id')));
		$content_data['lifestyles'] = $this->common_model->getAll('lifestyles');
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*,feu_userdetails.user_id') ;
		$content_data['userPreferences'] = $this->common_model->getAllMultipleJoin('feu_sexual_preference',array('feu_sexual_preference.user_id'=>$this->session->userdata('user_id'))) ;
		$content_data['userMembershipDetails'] = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		//print_r($content_data['userMembershipDetails']); die;
		$content_data['countries'] = $this->common_model->getAll('feu_countries','','','country_name ASC') ;
		$content_data['languages'] = $this->common_model->getAll('sys_languages') ;
		//$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id'=>4)) ;
		if($content_data['userDetials']['free_member']==1){
			$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id Desc') ;
		} else {
			$content_data['memberships'] = $this->common_model->getAll('shop_articles',array('id'=>4)) ;
		}
		$content_data['memberships_half'] = $this->common_model->getAll('shop_new_articles','','','id Asc') ;

		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		//print_r($data['userDetials']); die;
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Settings')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('edit_profile', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function partyDetails()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$cart_id = $this->input->post('cart_id');
		$eventDetails = $this->common_model->getAllRow('shop_booking_details',array('cart_id'=>$cart_id));
		$partyDetails = $this->common_model->getAllRowMultipleJoin('evt_events',array('evt_events.id'=>$eventDetails['event_id'],'is_banner'=>1,'evt_language_values.lang_id'=>$langId),array(array('evt_language_values','evt_language_values.event_id = evt_events.id'),array('loc_events_locations','loc_events_locations.event_id = evt_events.id'),array('loc_locations','loc_locations.id = loc_events_locations.location_id'),array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('sys_files','sys_files.id = evt_event_files.file_id')),'','*,evt_language_values.party_details');
		$userDetials = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		$orderDetails = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$cart_id));
		$userMembershipDetails = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		//print_r($orderDetails); die;

		$membership = 5;
		if($userMembershipDetails)
		{
			$membership = $userMembershipDetails['id'];
		}
		$days = 10;
		if($membership==4)
		{
			$days = 14;
		}
		if(!empty($orderDetails))
		{
			$UpdateData = $this->common_model->UpdateData('event_guest',array('details_check'=>1),array('order_id'=>$orderDetails['order_id']));
		}
		$html='<div class="printInner" id="printPartyInner" style="height: 300px; overflow-y: auto;">
                                         
                          <a href="'.base_url().'" class="invoicelogo" style="padding-bottom: 20px; text-align: center; display: block;"><img src="'.base_url().'newsletter_image/logo-icon.png" alt="Castleevents.com" width="40" style="width: 45px; height: 45px; min-width: 45px; min-height: 45px; max-width: 100%; max-height: 100%;"></a><br>
                         
                          '.getLang('Dear').' '.$userDetials['username'].',
                           <br/><span class="partyDate" style="padding-top: 10px; display:block; ">Party name :'.$partyDetails['title'].'</span>  
                      		<br/><span class="partyDate">Party date: '.date('d-m-Y',$partyDetails['time_from']).'</span>';

        				if(($partyDetails['time_from']-time())/86400 <= $days )
                        {
        $html.='          <h3 style="top:30px; padding:0 60px; color:#b3975b; text-transform:uppercase; font-weight:600;">'.getLang('Address_of_the_Party').' : '.$partyDetails['address'].'</h3>';                	
                        }  
                        if($partyDetails['party_details']!='')
                        {
        $html.='          <div style="padding: 20px; margin-bottom:15px; ">'.$partyDetails['party_details'].'</div>';
                        }
                        else
                        {
        $html.='          <div style="padding: 20px; margin-bottom:15px; ">'.getLang('You_will_get_party_details_soon').'.....</div>';                	
                        }                 
        $html.='     	<p style="border-top:1px solid #333; padding-top:10px; text-align:center;">'.getLang('Looking_forward_to_welcome_you').' <br>
							'.getLang('Your_Castleeventscom_Team').' </p>
                          </div>
                          </div>';
        echo $html; exit;               
    }
    public function pictures()
	{
		if($_FILES)
		{
			for($i=0;$i<count($_FILES['pics']['name']);$i++)
			{
				if($_FILES['pics']['name'][$i]!='')
				{
					$_FILES['userFile']['name'] = $_FILES['pics']['name'][$i];
		            $_FILES['userFile']['type'] = $_FILES['pics']['type'][$i];
		            $_FILES['userFile']['tmp_name'] = $_FILES['pics']['tmp_name'][$i];
		            $_FILES['userFile']['error'] = $_FILES['pics']['error'][$i];
		            $_FILES['userFile']['size'] = $_FILES['pics']['size'][$i];

					$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().'pictures/');
			        }

			        $uploaddata = $this->upload->data();
			        $this->load->library('Utility');
			        //pr($uploaddata);
			        //$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' 	=> $this->session->userdata('user_id'),
				            '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' 	=> $this->session->userdata('user_id'),
				            'file_id' 	=> $fileId,
				            'is_private'=> 1,
				            'created'	=>time()
				        );
				    $galId = $this->common_model->insertData('ugal_images',$dataset);
					$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>1,'type'=>12,'created'=>time(),'file_id'=>$fileId));        
				}
			}
		}
		if(checkStep()==1)
		{
			redirect('profile');
		}
		if(checkCardUpdated()==2)
		{
			redirect('profile');
		}
		if($this->session->userdata('user_id')){
			if(getOpenBookingInvoices() > 0)
			{
				$this->session->set_userdata('pay_book_first',1);
				redirect('invoice');
			}
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*, sys_files.id') ;
		$content_data['userImages'] = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC','*, sys_files.id, ugal_images.id as gai_id') ;
		//echo $this->db->last_query();die;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		/******************FREE MEMBERSHIP*******************/
		/*if($content_data['userDetials']['free_member']==1)
		{
			$this->session->set_userdata('upgrade',1);
			redirect('profile');
		}*/
		/******************FREE MEMBERSHIP*******************/
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$content_data['userVideos'] = $this->common_model->getAll('sys_videos',array('user_id'=>$this->session->userdata('user_id')),'', 'created_at DESC') ;
		$data['title'] = getLang('Pictures')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('pictures', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function change($encfileId = '')
	{
		/*if($encfileId=='')
		{
			redirect(base_url().'pictures');
		}
		else
		{*/
			$fileId = (base64_decode($encfileId));
			$getFile = $this->common_model->getAllRow('sys_files',array('id'=>$fileId));
			/*if(empty($getFile))
			{
				redirect(base_url().'pictures');
			} 
			else
			{*/
				if($this->input->post())
				{
					$filename = $getFile['filename'].'.'.$getFile['extension'];
					@unlink(FCPATH.'assets/userfiles/'.$getFile['path'].'/'.$filename);
					$time=time();
					$filename=$time.'.jpg';
					$ifp = fopen(FCPATH.'assets/userfiles/avatars/'.$filename, "wb"); 

				    $data = explode(',', $this->input->post('data'));

				    fwrite($ifp, base64_decode($data[1])); 
				    //fclose($ifp);
				    $image_name =$filename;
				    $new_width ='500';
					$new_height  = '500';
					$uploadDir = FCPATH.'assets/userfiles/avatars/';
					$imagefolder = 'avatars';
					//$moveToDir = $_SERVER['DOCUMENT_ROOT'].'/profile_image/thumb/';
					$path = $uploadDir. '/' . $image_name;
				    $mime = getimagesize($path);
				    if($mime['mime']=='image/png') { 
				        $src_img = imagecreatefrompng($path);
				    }
				    if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
				        $src_img = imagecreatefromjpeg($path);
				    }
				    if(empty($getFile))
					{
						$newName = explode('.', $image_name); 
						$file = array(
					            'user_id' 	=> $this->session->userdata('user_id'),
					            'path' 		=> $imagefolder,
					            'filename' 	=> $newName[0],
					            'extension' => $newName[1],
					            'mimetype' 	=> 'image/jpeg',
					            'is_image' 	=> 1,
					            'created'	=> time(),
					            'temp_name'	=> '',
					            //'attr_alt' 	=> 'Bild von ' . $username,
					        );
				        //print_r($file); die;
				        $file['width'] 	= '400';
					    $file['height'] = '400';

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

						$resize = $this->avater($newName[0] .'.'. $newName[1]);
						if(file_exists(FCPATH . 'assets/userfiles/avatars/80/'.$newName[0] .'.'. $newName[1])){
							$im = new Imagick(FCPATH . 'assets/userfiles/avatars/80/'.$newName[0] .'.'. $newName[1]);
					        $im->blurImage(5,3);
					        $blurredImg = FCPATH . 'assets/userfiles/avatars/blur/'.$newName[0] .'.'. $newName[1];
					        $fp = fopen($blurredImg, "x");
					        $im->writeImageFile($fp);
				    	}
					    $this->common_model->UpdateData('feu_userdetails',array('avatar_file_id'=>$newFileId),array('user_id'=>$this->session->userdata('user_id')));
					}
					else
					{
						$newName = explode('.', $image_name);
						$resize = $this->avater($newName[0] .'.'. $newName[1]);
						$this->common_model->UpdateData('sys_files',array('path'=>$imagefolder,'filename'=>$time,'extension'=>'jpg'),array('id'=>$fileId));
					}
					
					redirect(base_url().'pictures');
				}

				$langId = 2;
				if(get_cookie('lang'))
				{
					$langId = get_cookie('lang');
				}

				$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
				$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
				$content_data['userImages'] = $this->common_model->getAllRowMultipleJoin('sys_files',array('sys_files.id'=>$fileId)) ;
				$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
				$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
				if(empty($data['upcomingEvents']))
				{
					$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
				}
				if(empty($data['lastEvents']))
				{
					$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
				}
				$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
				$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
				//echo $this->db->last_query();die;
				/******************FREE MEMBERSHIP*******************/
				/*if($content_data['userDetials']['free_member']==1)
				{
					$this->session->set_userdata('upgrade',1);
					redirect('profile');
				}*/
				/******************FREE MEMBERSHIP*******************/
				$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
				$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
				$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
				$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
				$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
				$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
				$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
				$data['title'] = getLang('Change_Pictures')." | ".$data['userDetials']['username'];
				$data['content'] = $this->load->view('change', $content_data, TRUE);
				$this->load->view('template', $data);
			//}	
		//}	
	}
	public function deleteImage($encfileId ='')
	{
		if($encfileId=='')
		{
			redirect(base_url().'pictures');
		}
		else
		{
			$fileId = base64_decode($encfileId);
			$getFile = $this->common_model->getAllRow('sys_files',array('id'=>$fileId));
			if(empty($getFile))
			{
				redirect(base_url().'pictures');
			} 
			else
			{
				$filename = $getFile['filename'].'.'.$getFile['extension'];
				@unlink(FCPATH.'assets/userfiles/'.$getFile['path'].'/'.$filename);
				$this->common_model->deleteData('sys_files',array('id'=>$fileId));
				$this->common_model->deleteData('ugal_images',array('file_id'=>$fileId));
				$this->common_model->deleteData('notification',array('file_id'=>$fileId));
				redirect(base_url().'pictures');
			}
		}
	}
	public function lock($type='',$encgalId ='')
	{
		if($encgalId=='')
		{
			redirect(base_url().'pictures');
		}
		else
		{
			$galId = base64_decode($encgalId);
			$getFile = $this->common_model->getAllRow('ugal_images',array('id'=>$galId));
			$fileDetails = $this->common_model->getAllRow('sys_files',array('id'=>$getFile['file_id']));
			if(empty($getFile))
			{
				redirect(base_url().'pictures');
			} 
			else
			{
				if($type == 1)
				{
					if(!file_exists(FCPATH . 'assets/userfiles/' .$fileDetails['path'] . '/' . $fileDetails['filename'] .'_blur.'. $fileDetails['extension'])){
			            $im = new Imagick(FCPATH . 'assets/userfiles/' . $fileDetails['path'] . '/' . $fileDetails['filename'] .'.'. $fileDetails['extension']);
			            //print_r(FCPATH . 'assets/userfiles/' . $fileDetails['path'] . '/' . $fileDetails['filename'] .'.'. $fileDetails['extension']); die;
			            $im->blurImage(30,20);
			            $blurredImg = FCPATH . 'assets/userfiles/' .$fileDetails['path'] . '/' . $fileDetails['filename'] .'_blur.'. $fileDetails['extension'];
			            $fp = fopen($blurredImg, "x");
			            $im->writeImageFile($fp);
			            //fclose($fp);
		        	}
					$is_type = 1; 
				}	
				else
				{
					$is_type = 0;
				}
				$this->common_model->UpdateData('ugal_images',array('is_private'=>$is_type),array('id'=>$galId));
				redirect(base_url().'pictures');
			}
		}
	}
	public function privateRequest()
	{
		$from_id = $this->session->userdata('user_id');
		$to_id = $this->input->post('user_id');
		$array = array(
						'from_user_id'=>$from_id,
						'to_user_id'=>$to_id,
						'file_id'=>1,
						'created'=>time(),
						'privacy'=>0
					);
		$id = $this->common_model->insertData('ugal_images_user_privacy',$array);
		$this->common_model->insertData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>5,'created'=>time()));
		echo $id;exit;
	}
	public function rotate($encfileId = '')
	{
		if($encfileId=='')
		{
			redirect(base_url().'pictures');
		}
		else
		{
			$fileId = base64_decode($encfileId);
			$getFile = $this->common_model->getAllRow('sys_files',array('id'=>$fileId));
			if(empty($getFile))
			{
				redirect(base_url().'pictures');
			} 
			else
			{
				$source_path = FCPATH . 'assets/userfiles/' .$getFile['path'] . '/' . $getFile['filename'] .'.'. $getFile['extension'];
				$dest_name = rand(0,100000);
				$dest_path = FCPATH . 'assets/userfiles/' .$getFile['path'] . '/' . $dest_name.'.'. $getFile['extension'];
				$degrees = 90;
				$this->load->library('image_lib');
				$this->image_lib->clear();
                $config=array();
			    $config['image_library'] = 'gd2';
			    $config['source_image']  = $source_path;
			    $config['new_image']  =  $source_path;
				$config['rotation_angle'] = $degrees;
			    $this->image_lib->initialize($config);      
			    $this->image_lib->rotate();

			    if($getFile['path']=='avatars/' || $getFile['path']=='avatars'){
			    	$resize = $this->avater($getFile['filename'].'.'. $getFile['extension']);
			    }

			    if($getFile['path']=='usergalleries/' || $getFile['path']=='usergalleries'){
				    /***************Blur rotation*****************/
				    $source_path = FCPATH . 'assets/userfiles/' .$getFile['path'] . '/' . $getFile['filename'] .'_blur.'. $getFile['extension'];
					$degrees = 90;
					$this->load->library('image_lib');
					$this->image_lib->clear();
	                $config=array();
				    $config['image_library'] = 'gd2';
				    $config['source_image']  = $source_path;
				    $config['new_image']  =  $source_path;
					$config['rotation_angle'] = $degrees;
				    $this->image_lib->initialize($config);      
				    $this->image_lib->rotate();

				    //$resize = $this->avater($getFile['filename'] .'_blur.'. $getFile['extension']);
			   		/***************Blur rotation*****************/
			   	}
			   
			    $this->common_model->UpdateData('sys_files',array('filename'=>$getFile['filename']),array('id'=>$fileId));
			    //@unlink($source_path);
				redirect(base_url().'pictures','refresh');
			}
		}
	}
	public function members($page = '0')
	{
		$steps = getValue('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
		if(count($steps)>0)
		{
			redirect(base_url().'profile');
		}
		if(checkCardUpdated()==2)
		{
			redirect('profile');
		}
		if($this->session->userdata('user_id')){
			if(getOpenBookingInvoices() > 0)
			{
				$this->session->set_userdata('pay_book_first',1);
				redirect('invoice');
			}
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*, sys_files.id') ;
		$content_data['loggedInUserMembershipDetails'] = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		$this->common_model->UpdateData('usr_users',array('last_login'=>time()),array('id'=>$this->session->userdata('user_id')));
		/**************************************/
		if($this->input->post())
		{
			$serach = array('username'=>$this->input->post('serach'));
			$accounttype = $this->input->post('accounttype');
			$type ='';
			if($accounttype)
			{
				foreach ($accounttype  as $value) {
					$type .= '"'.$value.'",';
				}
			}
			$types = rtrim($type,','); 
			$where = 'feu_userdetails.user_id not in (25267, 11330) ';
			if($accounttype)
			{
				$where .= 'and accounttype in ('.$types.')';
			}
			//echo $where; die;
			$latestMember = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','usr_users.id = feu_userdetails.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'usr_users.last_login DESC','*, feu_userdetails.created, feu_userdetails.user_id','',$page,9,$serach);
			//echo $this->db->last_query(); die;
			$latestMembers = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','usr_users.id = feu_userdetails.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'usr_users.last_login DESC','*, feu_userdetails.created, feu_userdetails.user_id','','','',$serach);
			$total_rows = count($latestMembers);
			$this->load->library('Utility');
			$link = $this->utility->pagination(base_url().'members',$total_rows,9,2);	
		    $html="";
		    if(!empty($latestMember)){ 
	            foreach ($latestMember as $key=>$member) { 
	                    $html.='<div class="profileBox">';
	                    if($key < 90){ 
                        	$html.='<img src="'.base_url().'assets/images/online.svg" title="Online" class="closeProfile" widht="10">';
                        }
	                    $html.='<a target="_blank" href="'.base_url().'profil/'.$member['alias'].'">
	                   <div class="contactAvatar" >
								<img src="';
								if(!empty($member) && $member['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$member['path'].'/80/'.$member['filename'].'.'.$member['extension'])){ 
						$html.=		base_url().'assets/userfiles/'.$member['path'].'/80/'.$member['filename'].'.'.$member['extension']; 
								} 
								else
								{ 
						$html.=	    base_url().'assets/images/default-avatar.jpg'; 
								}
						$html.='" alt="" srcset="';
							if(!empty($member['filename']) && file_exists(FCPATH.'assets/userfiles/'.$member['path'].'/80/'.$member['filename'].'.'.$member['extension'])){ 
						$html.=	  base_url().'assets/userfiles/'.$member['path'].'/80/'.$member['filename'].'.'.$member['extension']; 
							} 
							else 
							{ 
						$html.=   base_url().'assets/images/default-avatar.jpg'; 
							}
						$html.=' 1x, ';
							if(!empty($member['filename']) && file_exists(FCPATH.'assets/userfiles/'.$member['path'].'/160/'.$member['filename'].'.'.$member['extension'])){ 
						$html.=  base_url().'assets/userfiles/'.$member['path'].'/160/'.$member['filename'].'.'.$member['extension']; 
							} 
							else 
							{ 
						$html.=	 base_url().'assets/images/default-avatar.jpg'; 
							} 
						$html.=' 2x" >
							
							 </div>
	                    </a>
	                    <h4>'.$member['username'].'</h4>
	                    <p class="noMargin">'.ucfirst($member['accounttype']).'<span>,'.$member['country_name'].'</span></p>';
	                    	$html.='  <p class="text_gold"><strong>'.getLang('Registered_since').'</strong><br>'.date('d.m.Y',$member['created']).'</p>';
	                         
	                    $html.='<p id="message_error" style="color:red"></p>';
	                    if($member['user_id']!=$this->session->userdata('user_id'))
	                    {
		                    $connectCanDo = 1;
		                    $FriendUnfriend = FriendUnfriend($this->session->userdata('user_id'),$member['user_id']);
                            $acctype = $content_data['userDetials']['accounttype'];
                            if($content_data['loggedInUserMembershipDetails']['id']==4)
                            {
                              	$connectCanDo = 0;
                            }
                            elseif ($content_data['loggedInUserMembershipDetails']['id']==5) 
                            {
                              	if($acctype=='lady')
                              	{
                                	$connectCanDo = 0;
                              	}
                              	if($acctype=='gentleman')
                              	{
                                	if($FriendUnfriend==1)
                                	{
                                  		$connectCanDo = 0;
                                	}
                              	}
                            	if($acctype=='couple')
                            	{
                                	if($FriendUnfriend==1)
                                	{
                                  		$connectCanDo = 0;
                                	}
                              	}
                            }
                            elseif ($content_data['userDetials']['free_member']==1) 
                            {
                              	if($FriendUnfriend==1)
                              	{
                                	$connectCanDo = 0;
                              	}
                            }
                            if($connectCanDo==1){
			                    $html.='<a href="javascript:void(0)" data-id="'.$member['user_id'].'" data-type="1" data-status="';
			                    $html.= $connectCanDo; 
			                	$html.='" class="profileBtn addblockUsersFromMembers">'.getLang('Contact').'</a>';
			                }
			                else
			                {
			                	$html.='<a href="'.base_url().'messages/'.base64_encode($member['user_id']).'" class="profileBtn">'.getLang('Contact').'</a>';
			                }
	                	}
	                $html.='  </div>';
	          		}
                }
                else
                {
                    $html.='<div class="norecord">'.getLang('No_record_found').'</div>';
                }
	            
                $html.='<div class="paginationouter">'.$link.'</div>';
                echo $html; die;
		}
		else
		{
			$where = 'feu_userdetails.user_id not in (25267, 11330) and avatar_file_id > 0';
			$content_data['latestMembers'] = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','usr_users.id = feu_userdetails.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'usr_users.last_login DESC','*, feu_userdetails.created, feu_userdetails.user_id','',$page,9);
			$latestMembers = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','usr_users.id = feu_userdetails.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'usr_users.last_login DESC','*, feu_userdetails.created, feu_userdetails.user_id','');
			$total_rows = count($latestMembers);
			$this->load->library('Utility');
			$content_data['link'] = $this->utility->pagination(base_url().'members',$total_rows,9,2);	
		}
		/**************************************/

		$content_data['to_friend'] = $this->common_model->getAllMultipleJoin('feu_relationships',array('user_id_2'=>$this->session->userdata('user_id'),'status'=>'accepted','type'=>'friend'),array(array('feu_userdetails','feu_userdetails.user_id = feu_relationships.user_id_1'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_relationships.created DESC','*,feu_relationships.created,feu_userdetails.user_id','',0,5);
		$content_data['from_friend'] = $this->common_model->getAllMultipleJoin('feu_relationships',array('user_id_1'=>$this->session->userdata('user_id'),'status'=>'accepted','type'=>'friend'),array(array('feu_userdetails','feu_userdetails.user_id = feu_relationships.user_id_2'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_relationships.created DESC','*,feu_relationships.created,feu_userdetails.user_id','',0,5);
		$content_data['todays_pics'] = $this->common_model->getAllMultipleJoin('sys_files',array('sys_files.is_image'=>1),array(array('ugal_images','ugal_images.file_id = sys_files.id')),'sys_files.created DESC','','',0,10,array('path'=>'usergalleries'));
		
		if($content_data['todays_pics'])
		{
			foreach ($content_data['todays_pics'] as $key => $value) {
				$pics_user = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$value['user_id']),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')));
				$content_data['todays_pics'][$key]['pics_user'] = $pics_user;
			}
		}
		
		$newsletterUsers = $this->common_model->getAll('newsletter_couple_lady','','','id DESC','','',0,1);
		//pr($content_data['userDetials']);
		$main_arr = array();
		$lady = array();
		$gent = array();
		$couple = array();
		if(count($newsletterUsers)>0)
		{
			foreach($newsletterUsers as $key=>$val)
			{
				if($content_data['userDetials']['interested_in_ladies']==1)
				{
					$lady = $this->common_model->getAllRowMultipleJoin('newsletter_couple_lady',array('newsletter_couple_lady.id'=>$val['id']),array(array('feu_userdetails','feu_userdetails.user_id = newsletter_couple_lady.lady'),array('feu_countries','feu_userdetails.country = feu_countries.country_code'),array('sys_files','feu_userdetails.avatar_file_id = sys_files.id')));
				}
				if($content_data['userDetials']['interested_in_gentlemen']==1)
				{
					$gent = $this->common_model->getAllRowMultipleJoin('newsletter_couple_lady',array('newsletter_couple_lady.id'=>$val['id']),array(array('feu_userdetails','feu_userdetails.user_id = newsletter_couple_lady.gentleman'),array('feu_countries','feu_userdetails.country = feu_countries.country_code'),array('sys_files','feu_userdetails.avatar_file_id = sys_files.id')));
				}
				if($content_data['userDetials']['interested_in_couples']==1)
				{
					$couple = $this->common_model->getAllRowMultipleJoin('newsletter_couple_lady',array('newsletter_couple_lady.id'=>$val['id']),array(array('feu_userdetails','feu_userdetails.user_id = newsletter_couple_lady.couple'),array('feu_countries','feu_userdetails.country = feu_countries.country_code'),array('sys_files','feu_userdetails.avatar_file_id = sys_files.id')));
				}
				
				
				if(count($lady)>0)
				{
					array_push($main_arr, $lady);
				}
				if(count($gent)>0)
				{
					array_push($main_arr, $gent);
				}
				if(count($couple)>0)
				{
					array_push($main_arr, $couple); 
				}
			}
		}
		/* if($this->session->userdata('user_id')==25267)
		{
			//pr($main_arr);
		} */
		
		$content_data['newsletterUsers'] = $main_arr;
		
		/*********Hot Or Not*****************/
		$given_hotshot = $this->common_model->getAllMultipleJoin('not_liked_users',array('user_id'=>$this->session->userdata('user_id'))) ;
	    $arr = array();
		if(!empty($given_hotshot))
		{
			foreach ($given_hotshot as $g_hotshot) {
				array_push($arr, $g_hotshot['file_id']);
			}
		} 
		//pr($arr);
		
		$mainArr  = array();
		$acctype = array();
		if($content_data['userDetials']['interested_in_ladies']==1)
		{
			array_push($acctype, 'lady');
		}
		if($content_data['userDetials']['interested_in_gentlemen']==1)
		{
			array_push($acctype, 'gentleman');
		}
		if($content_data['userDetials']['interested_in_couples']==1)
		{
			array_push($acctype, 'couple');
		}
		$actype = "'" . implode ( "', '", $acctype ) . "'";
		$where = "1 ";
		if(count($arr)>0)
		{
			$where .= "and sys_files.id not in (".implode(',',$arr).") ";
		}
		$where .= "and accounttype in (".$actype.") and filename != '' and is_image = 1"; 
		$hotnot = $this->common_model->getAllRowMultipleJoin('feu_userdetails',$where,array(array('sys_files','feu_userdetails.user_id = sys_files.user_id')),'sys_files.created ASC','*, sys_files.id as file_id','',0,1);
		//echo $this->db->last_query();die;
		$content_data['hotnot'] = $hotnot;
		$content_data['userImages'] = $this->common_model->getAllMultipleJoin('ugal_images',array('ugal_images.user_id'=>$this->session->userdata('user_id'),'filename !='=>'','is_private'=>0),array(array('sys_files','sys_files.id = ugal_images.file_id')),'sys_files.id DESC') ;
		$content_data['totalLikedData'] = $this->common_model->getAll('not_liked_users',array('user_id'=>$this->session->userdata('user_id')));
		/*********Hot Or Not*****************/
		
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		/******************FREE MEMBERSHIP*******************/
		/*if($content_data['userDetials']['free_member']==1)
		{
			$this->session->set_userdata('upgrade',1);
			redirect('profile');
		}*/
		/******************FREE MEMBERSHIP*******************/
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Members')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('members', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function contacts($page = '0')
	{
		$limit = 20;
		$steps = getValue('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
		if(count($steps)>0)
		{
			redirect(base_url().'profile');
		}
		if($this->session->userdata('user_id')){
			if(getOpenBookingInvoices() > 0)
			{
				$this->session->set_userdata('pay_book_first',1);
				redirect('invoice');
			}
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$update = $this->common_model->UpdateData('notification',array('read_unread'=>1),array('to_id'=>$this->session->userdata('user_id'),'read_unread'=>0,'type'=>8));
		$update = $this->common_model->UpdateData('notification',array('read_unread'=>1),array('to_id'=>$this->session->userdata('user_id'),'read_unread'=>0,'type'=>9));
		$update = $this->common_model->UpdateData('notification',array('read_unread'=>1),array('to_id'=>$this->session->userdata('user_id'),'read_unread'=>0,'type'=>10));
		$update = $this->common_model->UpdateData('notification',array('read_unread'=>1),array('to_id'=>$this->session->userdata('user_id'),'read_unread'=>0,'type'=>1));
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*, sys_files.id') ;
		
		/**************************************/
		if($this->input->post())
		{//pr($this->input->post());
			$accounttype = $this->input->post('accounttype');
			$type ='';
			if($accounttype)
			{
				foreach ($accounttype  as $value) {
					$type .= '"'.$value.'",';
				}
			}
			$types = rtrim($type,','); 
			$where1 = 'status = "accepted" and type = "friend" and user_id_2 = '.$this->session->userdata('user_id');
			$where2 = 'status = "accepted" and type = "friend" and user_id_1 = '.$this->session->userdata('user_id');
			if($accounttype)
			{
				$where1 .= ' and accounttype in ('.$types.')';
				$where2 .= ' and accounttype in ('.$types.')';
			}
			//echo $where1; die;
			$content_data['to_friend'] = $this->users_model->contactlist($page,$limit,$types);
			$total_to_friend = $this->users_model->contactlist('','',$types);
		}
		else
		{
			$content_data['to_friend'] = $this->users_model->contactlist($page,$limit,$types);
			$total_to_friend = $this->users_model->contactlist();
		}
		if($content_data['to_friend']){
			foreach ($content_data['to_friend'] as $key => $value) {
				$notification = $this->common_model->getAllRow('notification',array('type'=>12,'from_id'=>$value['user_id']));
				if($notification){
					$content_data['to_friend'][$key]['notcreated'] = $notification['created'];
				}
			}
		}
		foreach ($content_data['to_friend'] as $key => $row)
		{
		    $vc_array_name[$key] = $row['notcreated'];
		}
		array_multisort($vc_array_name, SORT_DESC, $content_data['to_friend']);
		//pr($content_data['to_friend']);
		$this->load->library('pagination');
		$config['base_url'] = base_url().'contacts/';
		$config['total_rows'] = count($total_to_friend);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$content_data['link'] = $this->pagination->create_links();
		/**************************************/
		$content_data['visitors'] = $this->common_model->getAllMultipleJoin('feu_profilevisits',array('feu_profilevisits.to_user_id'=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = feu_profilevisits.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_profilevisits.created DESC','*, sys_files.id','',0,7) ;
		$content_data['visited'] = $this->common_model->getAllMultipleJoin('feu_profilevisits',array('feu_profilevisits.from_user_id'=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = feu_profilevisits.to_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_profilevisits.created DESC','*, sys_files.id','',0,7) ;
		$content_data['receive_hotshot'] = $this->common_model->getAllMultipleJoin('like_likes',array('like_likes.identifier'=>'profile:'.$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = like_likes.user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'like_likes.created DESC','*, sys_files.id','',0,7) ;
		$given_hotshot = $this->common_model->getAllMultipleJoin('like_likes',array('like_likes.user_id'=>$this->session->userdata('user_id')),'','like_likes.created DESC','','',0,7,array('identifier'=>'profile')) ;
		$arr = array();
		if(!empty($given_hotshot))
		{
			foreach ($given_hotshot as $g_hotshot) {
				$g_user= explode(':',$g_hotshot['identifier']);
				$g_userId = 0;
				if(!empty($g_user) && count($g_user)>1)
				{
					$g_userId = $g_user[1];
				}
				$givenUserdata = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$g_userId),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;	
				if(count($givenUserdata)>0)
				{
					array_push($arr, $givenUserdata);
				}
			}
		}
		$content_data['given_hotshot'] = $arr;
		
		$content_data['privacy_accepted_users'] = $this->common_model->getAllMultipleJoin('ugal_images_user_privacy',array('to_user_id'=>$this->session->userdata('user_id'),'privacy'=>1),array(array('feu_userdetails','feu_userdetails.user_id = ugal_images_user_privacy.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'ugal_images_user_privacy.created DESC','*, sys_files.id','from_user_id') ;

		$content_data['requsts'] = $this->common_model->getAllMultipleJoin('feu_relationships',array('user_id_2'=>$this->session->userdata('user_id'),'status'=>'pending','type'=>'friend'),array(array('feu_userdetails','feu_userdetails.user_id = feu_relationships.user_id_1'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_relationships.created DESC','*,feu_relationships.created,feu_userdetails.user_id');
		//print_r($content_data['requsts']);die;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$content_data['blocked_user_list'] = $this->common_model->getAllMultipleJoin('usr_block',array('from_id'=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = usr_block.to_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['title'] = getLang('Contacts')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('contacts', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function acceptRequest($type='',$from_id='')
	{
		$from_id = $from_id;
		$type = $type;
		$to_id = $this->session->userdata('user_id');
		if($type==1)
		{
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>2,'created'=>time()));
			$this->common_model->UpdateData('feu_relationships',array('status'=>'accepted','type'=>'friend'),array('user_id_1'=>$from_id,'user_id_2'=>$to_id));
		}
		else
		{
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>2,'created'=>time()));
			$this->common_model->deleteData('feu_relationships',array('user_id_1'=>$from_id,'user_id_2'=>$to_id));
			$this->common_model->deleteData('feu_relationships',array('user_id_2'=>$from_id,'user_id_1'=>$to_id));
		}
		redirect('contacts');
	}
	public function upgradePay()
	{
		$memberships = $this->common_model->getAll('shop_articles',array('id >'=>2,'id <'=>6),'','id Desc') ;
		$memberships_half = $this->common_model->getAll('shop_new_articles','','','id Asc') ;

		$origPrice = $this->input->post('price');
		$upgradeFee = $this->input->post('upgradeFee');
		$vatPrice = $this->input->post('vatPrice');
		$user_id = $this->session->userdata('user_id');
		$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));
		$userData = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		
		$shop_order_details =  $shop_order = $this->common_model->getAllRow('shop_orders',array('payed'=>1 , 'is_booking'=>0,'invoiceAddress'=>$userDetails['email'] ),'','created DESC');
		$created_time=time();
		if($shop_order_details){
			$created_time= ($shop_order_details['created']+1);
		}


		$finaltotal = 0;
		if($vatPrice > 0)
		{
			$finaltotal = $vatPrice;
		}
		else
		{
			$finaltotal = $upgradeFee;
		}

		$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);

		$type = 4;
		if($origPrice==($memberships_half[0]['base_price']/100) || $origPrice==($memberships[0]['base_price']/100)){
			$type = 5;
		} elseif($origPrice==($memberships[2]['base_price']/100)) {
			$platinum_order = 1;
			$type = 4;
		} else {
			$type = 4;
		}

		$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*100,
			'shipping_fee' 			=> 0,
			'payment_fee' 			=> ($upgradeFee - $origPrice)*100,
			'vat' 					=> ($vatPrice - $upgradeFee)*100,
			'total_sum' 			=> $finaltotal*100 ,
			'payment_method_id' 	=> 13,
			'invoiceAddress' 		=> $userDetails['email'],
            'discount'              => 0,
            'time'					=> ($origPrice==($memberships_half[0]['base_price']/100) || $origPrice==($memberships_half[1]['base_price']/100))?182:365,
            'created'				=> time(),
            'terms_accept_date'		=> time(),
			'upgrade_date'          => time()
		);
		$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));
		
		/*********TEST*************/
		/*$CustomerId = 246934;	
		$TerminalId = 17951970;	
		$username = 'API_246934_23183450';
		$password = 'JsonApiPwd1_a8EpfvCy';*/	
		/*********TEST*************/

		/*********LIVE*************/
		$CustomerId = 403547;
		$TerminalId = 17799239;	
		$username = 'API_403547_78643204';
		$password = 'JsonApiPwdAnexus1_a8EpfvCy';	
		/*********LIVE*************/
		/***********************Create Card Alias Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "PaymentMeans": {
			    "Card": {
			      "Number": "'.$this->input->post('card_number').'",
			      "ExpYear": '.$this->input->post('exp_year').',
			      "ExpMonth": '.$this->input->post('exp_month').',
			      "HolderName": "'.$this->input->post('card_holder').'",
			      "VerificationCode": "'.$this->input->post('card_cvc').'"
			    }
			  },
			  "RegisterAlias": {
			    "IdGenerator": "RANDOM"
			  }
			}';
			//$url = 'https://test.saferpay.com/api/Payment/v1/Alias/InsertDirect';
			$url = 'https://www.saferpay.com/api/Payment/v1/Alias/InsertDirect';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		    	if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	} else {
		    		$fail_reason = 'Authorization denied';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $aliasresponse = json_decode($jsonResponse, true);
		    //echo "<pre>";
		  	//print_r($aliasresponse);die;
		/***********************Create Card Alias Direct********************/


		/***********************Create Transaction Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TerminalId": "'.$TerminalId.'",
			  "Payment": {
			    "Amount": {
			      "Value": "'.(int)($finaltotal*100).'",
			      "CurrencyCode": "EUR"
			    },
			    "Recurring": {
			      "Initial": true
			    },
			    "Description": "Membership",
			    "PayerNote": "Membership"
			  },
			  "PaymentMeans": {
			    "Alias": {
			      "Id": "'.$aliasresponse['Alias']['Id'].'"
			    }
			  }
			}';

			//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
			$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $transactionresponse = json_decode($jsonResponse, true);
		    $this->common_model->UpdateData('shop_orders',array('real_name'=>$transactionresponse['PaymentMeans']['Card']['HolderName'], 'card_origin'=>$transactionresponse['PaymentMeans']['Card']['CountryCode']),array('order_id'=>$orderId));
		  	//echo "<pre>";
			//print_r($transactionresponse);die;
		/***********************Create Transaction Direct********************/


		/***********************Create Capture Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TransactionReference": {
			    "TransactionId": "'.$transactionresponse['Transaction']['Id'].'"
			  }
			}';
			//echo $JSONObj;die;
			//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Capture';
			$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Capture';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	}
		    	$errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $response = json_decode($jsonResponse, true);
		    
		  	//echo "<pre>";
			//print_r($response);die;
		/***********************Create Capture Direct********************/
		//print_r($cc_ref_id_result);die;

			if($response)
			{
						
				$this->common_model->UpdateData('shop_orders',array('payed'=>1,'trn_id'=>$transactionresponse['Transaction']['Id'],'fail_reason'=>''),array('order_id'=>$orderId));
				$cc_pan = 'xxxx xxxx xxxx '.substr($this->input->post('card_number'), -4);
				$expYr = substr($this->input->post('exp_year'), -2);
				$expMth = str_pad($this->input->post('exp_month'), 2, '0', STR_PAD_LEFT);
				$saferpay_exp = $expMth.$expYr;
				$this->common_model->UpdateData('usr_users',array('card_alias'=>$aliasresponse['Alias']['Id'],'cc_pan'=>$cc_pan,'saferpay_exp'=>$saferpay_exp),array('id'=>$this->session->userdata('user_id')));
				/**************FREE MEMBERSHIP**************/
				$this->common_model->UpdateData('feu_userdetails',array('free_member'=>0),array('user_id'=>$this->session->userdata('user_id')));
				/**************FREE MEMBERSHIP**************/
				$to = $userDetails['email'];
				$sub = getLang('Membership_Invoice_mail_from').' Castleevents';
				//$body= '<p>Dear '.$userData['username'].',</p>';
				$body= '<p>'.getLang('We_have_received_your_payment').'!</p>';
				$body.= '<p>'.getLang('Invoice_Number').': CE-'.$orderId.'</p><p>'.getLang('Generated_On').': '.date('Y-m-d',time()).'</p><p>'.getLang('Paid_Amount').': '.number_format($finaltotal,2, '.', '').' EUR</p>';
				$body.= '<p>'.getLang('Invoice_will_be_located').' www.castleevents.com.</p>';
				$body.= '<p>'.getLang('We_appreciate_very_much').'.</p>';
				$body.= '<p>'.getLang('Please_do_not_hesitate_to_contact').'.</p>';

				$body.= '<p></p>';
				$body.= '<p>This payment is related our <a href="'.base_url('terms').'">terms and conditions</a> confirmed from you on '.date('d-m-Y H:i:s').' </p>';
				//$body.= '<p>Best regards,</p><p>Your Castleevents Team </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>'.getLang('Dear').' <span style="text-transform:capitalize">'.$userData['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;">
                         		'.getLang('Best_regards').' <br>
                         		<p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
                         	</td>
                         </tr>
                      </table>
                   </td>
                </tr>
            </table>';


			$this->utility->sendOrderMail($to,$sub,$bodys);

			/****extra mail****/
				$to = 'alorenc@me.com';
				$sub = 'Payment recieved';
				$body= 'CE-'.$orderId.', EUR '.number_format($finaltotal, 2,',', '.');
				$body.= '<p>Paid Upgrade Membership Fees</p>';
				$body.= '<p>'.$userData['username'].'</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 style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
				                           '.$body.'
				                        </td>
				                     </tr>
				                  </table>
				               </td>
				            </tr>
				        </table>';
				$this->utility->sendOrderMail($to,$sub,$bodys);
			/****extra mail****/
				echo 2;
			}
			else
			{
				$this->common_model->UpdateData('shop_orders',array('fail_reason'=>'Card authorization denied','payment_method_id'=>13),array('order_id'=>$orderId));
				echo 'Card authorization denied';
			}
			exit;
	}
	public function messages($encId = '')
	{
		if(checkStep()==1)
		{
			redirect('profile');
		}
		if(checkCardUpdated()==2)
		{
			redirect('profile');
		}
		if($this->session->userdata('user_id')){
			if(getOpenBookingInvoices() > 0)
			{
				$this->session->set_userdata('pay_book_first',1);
				redirect('invoice');
			}
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		/****************Blacklist*******************/
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		$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 = '.$this->session->userdata('user_id').' order by b.created DESC');
		$content_data['membershipUser'] = $qry->row_array();
		$percent = profile_percent($this->session->userdata('user_id'));
		/*if($percent<100 && $content_data['loginDetails'][0]['blacklist']==1 && $content_data['userDetials']['verified']==0)
		{
			if(!empty($content_data['membershipUser']) && $content_data['membershipUser']['article_id']==5){
				redirect('settings');
			}
		}*/
		/****************Blacklist*******************/
		$update = $this->common_model->UpdateData('notification',array('read_unread'=>1),array('to_id'=>$this->session->userdata('user_id'),'read_unread'=>0,'type'=>4));
		//$update = $this->users_model->updateConversation($this->session->userdata('user_id'));
		$content_data['msg_user_id'] = $encId;
		$guestRow = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>base64_decode($encId)));
		$content_data['msg_username'] = empty($guestRow) ? '' : $guestRow['username'];
		if($encId!='')
		{
			$guest_to = $this->common_model->getAllRow('feu_relationships',array('user_id_1'=>$this->session->userdata('user_id'),'user_id_2'=>base64_decode($encId)));
			$guest_from = $this->common_model->getAllRow('feu_relationships',array('user_id_2'=>$this->session->userdata('user_id'),'user_id_1'=>base64_decode($encId)));
			$usersmessages = $this->users_model->conversation($this->session->userdata('user_id'),base64_decode($encId));
			if(empty($guest_to) && empty($guest_from))
			{
				$this->common_model->insertData('feu_relationships',array('user_id_1'=>$this->session->userdata('user_id'),'user_id_2'=>base64_decode($encId),'created'=>time(),'type'=>'guest','status'=>'guest'));
			}
			if(empty($usersmessages))
			{
				$meg_conv_instId = $this->common_model->insertData('msg_conversations',array('created'=>time()));
				$this->common_model->insertData('msg_conversations_users',array('conversation_id'=>$meg_conv_instId,'user_id'=>base64_decode($encId),'latest_read'=>0));
				$this->common_model->insertData('msg_messages',array('created'=>time(),'conversation_id'=>$meg_conv_instId,'from_user_id'=>$this->session->userdata('user_id'),'text'=>'Hi'));
			}
		}
		$content_data['to_friend'] = $this->users_model->latestConversationLimit(6,0);
		$latestMessagesUser = $this->users_model->groupConversation($this->session->userdata('user_id'));
		//echo $this->db->last_query(); die; 
		$content_data['number_to_restrict'] = $this->users_model->number_to_restrict();
		//echo $this->db->last_query(); die; 
		//pr($latestMessagesUser);
		$to_id= 0;
		if($latestMessagesUser['from_user_id']==$this->session->userdata('user_id'))
		{
			$to_id= $latestMessagesUser['user_id'];
		}
		else
		{
			$to_id= $latestMessagesUser['from_user_id'];
		}
		if(!empty($latestMessagesUser))
		{
			$content_data['latest_userDetails'] = $latestMessagesUser;
			$content_data['latest_userDetails'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$to_id),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*,feu_userdetails.user_id') ;
			//echo $this->session->userdata('user_id').'|'.$to_id;die;
			$content_data['latest_messages'] = $this->users_model->conversationLimit($this->session->userdata('user_id'),$to_id,0,5,0);
			$content_data['latest_messages'] = array_reverse($content_data['latest_messages']);
			$otherUserqry = $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 = '.$to_id.' order by b.created DESC');
			$otherUserMembership = $otherUserqry->row_array();
			$$content_data['otherUserMembershiphistory'] = 0;
			if(count($otherUserMembership)>0)
			{
				$content_data['otherUserMembershiphistory'] = $otherUserMembership['article_id'];
			}
		}

		
		$content_data['userParticipation'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_events.alias','shop_booking_details.cart_id');
    	$content_data['userParticipationOld'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_articles_carts.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','','shop_articles_carts.event_id');
    	
    	$content_data['upcomingLastBookedParty'] = $this->common_model->getAllRowMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','*,evt_events.alias','shop_booking_details.cart_id');
    	//echo $this->db->last_query(); die;
    	if(count($content_data['upcomingLastBookedParty'])==0)
    	{
    		$content_data['upcomingLastBookedParty']['time_from'] = 0;
    	}

		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Messages')." | ".$data['userDetials']['username'];
		
		$data['content'] = $this->load->view('messages', $content_data, TRUE);
		
		$this->load->view('template', $data);
	}
	public function searchfriend()
	{
		$name = $this->utility->info_cleanQuery($this->input->post('name'));
		$to_friend = $this->users_model->latestConversationByUser($name);
		//$to_friend = $this->common_model->getAllMultipleJoin('feu_relationships',array('user_id_2'=>$this->session->userdata('user_id'),'user_id_1 !='=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = feu_relationships.user_id_1'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_relationships.created DESC','*,feu_relationships.created,feu_userdetails.user_id','','','',array('username'=>$name));
		//$from_friend = $this->common_model->getAllMultipleJoin('feu_relationships',array('user_id_1'=>$this->session->userdata('user_id'),'user_id_2 !='=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = feu_relationships.user_id_2'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'feu_relationships.created DESC','*,feu_relationships.created,feu_userdetails.user_id','','','',array('username'=>$name));
		$html = '<div id="mCSB_1" class="mCustomScrollBox mCS-minimal-dark mCSB_vertical mCSB_outside" style="max-height: none;" tabindex="0"><div id="mCSB_1_container" class="mCSB_container" style="position:relative; top:0; left:0;" dir="ltr">';
		if(!empty($to_friend))
		{ 
	        foreach ($to_friend as $t_friend) {
	            //$last_conv = conversation($this->session->userdata('user_id'),$t_friend['user_id']);
	         
	            $html.='<li id="user_';
	            if($t_friend['user_id']!=$this->session->userdata('user_id')){
	            	$html.=$t_friend['user_id']; 
	            } 
            	else {
            	    $html.=$t_friend['from_user_id']; 
            	}
	            $html.='" class="listUser" data-id="';
	            if($t_friend['user_id']!=$this->session->userdata('user_id')){
	            	$html.=$t_friend['user_id']; 
	            } 
            	else {
            	    $html.=$t_friend['from_user_id']; 
            	}
	            
	            $html.='">
	            <a href="javascript:void(0)" class="clearfix">
	            <div class="online_wrapper">
	            <div class="mediumbgAvatar">';
	            $html.='<img src="';
				if(!empty($t_friend) && $t_friend['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension'])){
					$html.=base_url().'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension'];
				} 
				else
				{
					$html.=base_url().'assets/images/default-avatar.jpg';
				}
				$html.='" alt="" srcset="';
				if(!empty($t_friend['filename']) && file_exists(FCPATH.'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension'])){   $html.=base_url().'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension']; 
				} 
				else
					{ 
					$html.=base_url().'assets/images/default-avatar.jpg'; 
				}
				$html.=' 1x,';
				if(!empty($t_friend['filename']) && file_exists(FCPATH.'assets/userfiles/'.$t_friend['path'].'/160/'.$t_friend['filename'].'.'.$t_friend['extension'])){ 
					$html.=base_url().'assets/userfiles/'.$t_friend['path'].'/160/'.$t_friend['filename'].'.'.$t_friend['extension'];
				} 
				else
				{ 
					$html.=base_url().'assets/images/default-avatar.jpg'; 
				}
				$html.=' 2x" >';
	            $html.='</div>'.(($t_friend['online_status']==1)?'<i class="fa fa-circle"></i>':'').'</div>
	             	<div class="conversation_text">                     
	               <h5>'.$t_friend['username'].'</h5>
	               <div class="action-btns">
	                <time class="last_talktime">';
	            $html.=	date('M d',$t_friend['created']);
	            $html.='</time>                          
	                <!--<span><i class="fa  fa-trash"></i></span>-->
	               </div>                      
	               <p class="last_talk">';
	            $html.=strip_tags(substr($t_friend['text'],0,20));
	            $html.='</p>
	             </div>
	            </a>
	          </li>';
	    	}
	    }
	    
	    $html .='</div></div><div id="mCSB_1_scrollbar_vertical" class="mCSB_scrollTools mCSB_1_scrollbar mCS-minimal-dark mCSB_scrollTools_vertical" style="display: block;"><div class="mCSB_draggerContainer"><div id="mCSB_1_dragger_vertical" class="mCSB_dragger" style="position: absolute; min-height: 50px; display: block; height: 384px; max-height: 410px; top: 0px;"><div class="mCSB_dragger_bar" style="line-height: 50px;"></div></div><div class="mCSB_draggerRail"></div></div></div>';
	echo $html; exit;
	}
	public function latestMessage()
	{
		date_default_timezone_set("Europe/Zurich");
		$user_id = $this->input->post('user_id');
		$other_user_id = $this->input->post('other_user_id');
		$html = '';
		$user_chat = '';
		$user_message = '';
		$latest_userDetails = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$other_user_id),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*,feu_userdetails.user_id') ;
		

		$final_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,1,0);
		$latest_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,5,0);
		//echo $this->db->last_query();
		$lasttime = 0;
		if(count($latest_messages)>0)
		{
			$lasttime = $latest_messages[count($latest_messages)-1]['created'];
		}
		$finaltime = 0;
		if(count($final_messages)>0)
		{
			$finaltime = $final_messages[0]['created'];
		}
		$latest_messages = array_reverse($latest_messages);


		$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 = '.$this->session->userdata('user_id').' order by b.created DESC');
		$membershipUser = $qry->row_array();

		$otherUserqry = $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 = '.$other_user_id.' order by b.created DESC');
		$otherUserMembership = $otherUserqry->row_array();
		$otherUserMembershiphistory = 0;
		if(count($otherUserMembership)>0)
		{
			$otherUserMembershiphistory = $otherUserMembership['article_id'];
		}

		$number_to_restrict = $this->users_model->number_to_restrict();
		$userDetials = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		
		$upcomingLastBookedParty = $this->common_model->getAllRowMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','*,evt_events.alias','shop_booking_details.cart_id');
    	//echo $this->db->last_query(); die;
    	if(count($upcomingLastBookedParty)==0)
    	{
    		$upcomingLastBookedParty['time_from'] = 0;
    	}

		if(!empty($latest_userDetails))
		{
			$user_chat .='<a href="'.base_url().'profil/'.$latest_userDetails['alias'].'" class="clearfix" target="_blank">
                  <div class="online_wrapper">
                  <div class="mediumbgAvatar">';
	            $user_chat.='<img src="';
				if(!empty($latest_userDetails) && $latest_userDetails['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$latest_userDetails['path'].'/80/'.$latest_userDetails['filename'].'.'.$latest_userDetails['extension'])){
					$user_chat.=base_url().'assets/userfiles/'.$latest_userDetails['path'].'/80/'.$latest_userDetails['filename'].'.'.$latest_userDetails['extension'];
				} 
				else
				{
					$user_chat.=base_url().'assets/images/default-avatar.jpg';
				}
				$user_chat.='" alt="" srcset="';
				if(!empty($latest_userDetails['filename']) && file_exists(FCPATH.'assets/userfiles/'.$latest_userDetails['path'].'/80/'.$latest_userDetails['filename'].'.'.$latest_userDetails['extension'])){   $user_chat.=base_url().'assets/userfiles/'.$latest_userDetails['path'].'/80/'.$latest_userDetails['filename'].'.'.$latest_userDetails['extension']; 
				} 
				else
					{ 
					$user_chat.=base_url().'assets/images/default-avatar.jpg'; 
				}
				$user_chat.=' 1x,';
				if(!empty($latest_userDetails['filename']) && file_exists(FCPATH.'assets/userfiles/'.$latest_userDetails['path'].'/160/'.$latest_userDetails['filename'].'.'.$latest_userDetails['extension'])){ 
					$user_chat.=base_url().'assets/userfiles/'.$latest_userDetails['path'].'/160/'.$latest_userDetails['filename'].'.'.$latest_userDetails['extension'];
				} 
				else
				{ 
					$user_chat.=base_url().'assets/images/default-avatar.jpg'; 
				}
				$user_chat.=' 2x" >';
	            $user_chat.='</div>'.(($latest_userDetails['online_status']==1)?'<i class="fa fa-circle"></i>':'').'</div>

                  <div class="view_header_content">
                    <h5>';
                    if(!empty($latest_userDetails)){ 
                    	$user_chat .=$latest_userDetails['username']; 
                    }
                    $user_chat .='</h5>
                    <p>';
                    if(!empty($latest_userDetails)){ 
                    	$user_chat .=$latest_userDetails['accounttype'];
                    }
                    $user_chat .='</p>
                  </div>        
                </a><div class="deleteWholeConv"><i class="fa fa-trash deleteCommunityWholeMessage" data-id="'.$latest_userDetails['user_id'].'" title="Delete Conversation"></i></div>';
        }
        $normal = 0;
        if(!empty($latest_messages))
		{        
                $user_message .= '<div id="chatwrapper"  class="chat_wrapper " style="overflow-y:auto;">
                    <!--<div id="chatwrapper"  class="chat_wrapper mCustomScrollbar light" data-mcs-theme="minimal-dark">-->
                        <time>'.date('M d',$latest_messages[count($latest_messages)-1]['created']).'</time>';
        		if($membershipUser['article_id'] == 5 && $userDetials['accounttype']=='gentleman' && $latest_userDetails['accounttype'] == 'lady')
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('Thank_you_for_using_our_community').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              		$normal = 1;
              	} 
              	elseif($membershipUser['article_id'] == 5 && $userDetials['accounttype']=='couple' && $latest_userDetails['accounttype'] == 'lady')
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('To_continue_upgrade_or_book').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              		$normal = 1;
              	}	
              	else
              	{
            		foreach ($latest_messages as $message) {    
                
                    	$user_message .= '<div class="conversation ';
                            if($message['from_user_id']==$this->session->userdata('user_id')){ 
                            	$user_message .= 'mysite';
                            } 
                            else { 
                            	$user_message .= 'othersite'; 
                            }
                            $user_message .='">
                            <div class="avatar">
                              <div class="mediumbgAvatar">';
								$user_message.='<img src="';
								if(!empty($message) && $message['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{
									$user_message.=base_url().'assets/images/default-avatar.jpg';
								}
								$user_message.='" alt="" srcset="';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){   $user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension']; 
								} 
								else
									{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 1x,';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'])){ 
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 2x" >';
								$user_message.='</div>

                            </div>
                            <div class="content">
                              <p>'.$message['text'].'</p>';
		                    if($message['image_path']){
		                    	$user_message .= '<p><a class="fancybox downloadAnchor" href="#inline'.$message['id'].'" data-fancybox-group="gallery" style="background:url('.base_url().$message['image_path'].') no-repeat center center / cover; min-width: 150px; min-height: 150px;" ><span class="dImageWrapper">'.getLang('View').'</span></a></p>';
		                    	$user_message .= '<div id="inline'.$message['id'].'" style="display:none;">
                                  <div class="hotshotWrapper">
                                    <div class="hotshotbody">
                                      <div class="border">
                                            <div style="background: url('.base_url().str_replace('message/', 'message_big/', $message['image_path']).') no-repeat center center / cover; " ></div>
                                        </div>
                                      </div>
                                    </div>
                                </div>';
		                    } 
		                    $user_message .= '</div>
                            <time>';
                            if(date('d',$message['created'])==date('d',time())){ 
                            	$user_message .=date('H:i',$message['created']);
                            }
                            else{ 
                            	$user_message .=date('M d',$message['created']); 
                            }
                            $user_message .=' <i class="fa fa-trash deleteCommunityMessage" data-id="'.$message['id'].'"></i></time>                        
                          </div>';
                        } 
                    }
                    $user_message .= '</div>';
		}
		else 
		{ 
            $user_message .= '<div id="chatwrapper"  class="chat_wrapper " style="overflow-y:auto;">
                    <!--<div id="chatwrapper"  class="chat_wrapper mCustomScrollbar light" data-mcs-theme="minimal-dark">-->
                        <time>'.date('M d',time()).'</time>
                          '.getLang('No_Message').'
                    </div>';
        }
		echo $html= $user_chat.'|'.$user_message.'|'.$lasttime.'|'.$finaltime.'|'.$normal;exit;
	}
	public function loadnextmessage()
	{
		date_default_timezone_set("Europe/Zurich");
		$user_id = $this->input->post('user_id');
		$other_user_id = $this->input->post('other_user_id');
		$uptime = $this->input->post('uptime')?$this->input->post('uptime'):'';
		$html = '';
		$user_chat = '';
		$user_message = '';
		$latest_userDetails = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$other_user_id),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		
		
		$final_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,1,0);
		if($uptime!='')
		{
			$latest_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,$uptime,5,0);
		}
		else
		{
			$latest_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,5,0);
		}
		//echo $this->db->last_query();
		$lasttime = 0;
		if(count($latest_messages)>0)
		{
			$lasttime = $latest_messages[count($latest_messages)-1]['created'];
		}
		$finaltime = 0;
		if(count($final_messages)>0)
		{
			$finaltime = $final_messages[0]['created'];
		}
		$latest_messages = array_reverse($latest_messages);


		$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 = '.$this->session->userdata('user_id').' order by b.created DESC');
		$membershipUser = $qry->row_array();

		$otherUserqry = $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 = '.$other_user_id.' order by b.created DESC');
		$otherUserMembership = $otherUserqry->row_array();
		$otherUserMembershiphistory = 0;
		if(count($otherUserMembership)>0)
		{
			$otherUserMembershiphistory = $otherUserMembership['article_id'];
		}

		$number_to_restrict = $this->users_model->number_to_restrict();
		$userDetials = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		
		$upcomingLastBookedParty = $this->common_model->getAllRowMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','*,evt_events.alias','shop_booking_details.cart_id');
    	//echo $this->db->last_query(); die;
    	if(count($upcomingLastBookedParty)==0)
    	{
    		$upcomingLastBookedParty['time_from'] = 0;
    	}
        if(!empty($latest_messages))
		{        
                $user_message .= '';
        		if($membershipUser['article_id'] == 5 && $userDetials['accounttype']=='gentleman' && count($number_to_restrict)>50 && $otherUserMembershiphistory!=4)
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('Thank_you_for_using_our_community').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              	} 
              	elseif($membershipUser['article_id'] == 5 && $upcomingLastBookedParty['time_from']<time() && count($number_to_restrict)>50 && $userDetials['accounttype']=='couple' && $otherUserMembershiphistory!=4)
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('To_continue_upgrade_or_book').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              	}	
              	else
              	{
            		foreach ($latest_messages as $message) {    
                
                    	$user_message .= '<div class="conversation ';
                            if($message['from_user_id']==$this->session->userdata('user_id')){ 
                            	$user_message .= 'mysite';
                            } 
                            else { 
                            	$user_message .= 'othersite'; 
                            }
                            $user_message .='">
                            <div class="avatar">
                              <div class="mediumbgAvatar">';
								$user_message.='<img src="';
								if(!empty($message) && $message['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{
									$user_message.=base_url().'assets/images/default-avatar.jpg';
								}
								$user_message.='" alt="" srcset="';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){   $user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension']; 
								} 
								else
									{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 1x,';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'])){ 
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 2x" >';
								$user_message.='</div>

                            </div>
                            <div class="content">
                              <p>'.$message['text'].'</p>';
		                    if($message['image_path']){
		                    	$user_message .= '<p><a class="fancybox downloadAnchor" href="#inline'.$message['id'].'" data-fancybox-group="gallery" style="background:url('.base_url().$message['image_path'].') no-repeat center center / cover; min-width: 150px; min-height: 150px;" ><span class="dImageWrapper">'.getLang('View').'</span></a></p>';
		                    	$user_message .= '<div id="inline'.$message['id'].'" style="display:none;">
                                  <div class="hotshotWrapper">
                                    <div class="hotshotbody">
                                      <div class="border">
                                            <div style="background: url('.base_url().str_replace('message/', 'message_big/', $message['image_path']).') no-repeat center center / cover; " ></div>
                                        </div>
                                      </div>
                                    </div>
                                </div>';
		                    } 
		                    $user_message .= '</div>
                            <time>';
                            if(date('d',$message['created'])==date('d',time())){ 
                            	$user_message .=date('H:i',$message['created']);
                            }
                            else{ 
                            	$user_message .=date('M d',$message['created']); 
                            }
                            $user_message .=' <i class="fa fa-trash deleteCommunityMessage" data-id="'.$message['id'].'"></i></time>                        
                          </div>';
                        } 
                    }
                    $user_message .= '</div>';
		}
		echo $html= $user_message.'|'.$lasttime.'|'.$finaltime.'|'.count($latest_messages);exit;
	}
	public function loadcurrentmessage()
	{
		date_default_timezone_set("Europe/Zurich");
		$user_id = $this->input->post('user_id');
		$other_user_id = $this->input->post('other_user_id');
		$finaltime = $this->input->post('finaltime')?$this->input->post('finaltime'):'';
		$html = '';
		$user_chat = '';
		$user_message = '';
		$latest_userDetails = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$other_user_id),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		
		
		$final_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,1,0);
		$latest_messages = $this->users_model->conversationCurrentLimit($this->session->userdata('user_id'),$other_user_id,$finaltime);
		//echo $this->db->last_query();
		$lasttime = 0;
		if(count($latest_messages)>0)
		{
			$lasttime = $latest_messages[count($latest_messages)-1]['created'];
		}
		$finaltime = 0;
		if(count($final_messages)>0)
		{
			$finaltime = $final_messages[0]['created'];
		}
		$latest_messages = array_reverse($latest_messages);


		$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 = '.$this->session->userdata('user_id').' order by b.created DESC');
		$membershipUser = $qry->row_array();

		$otherUserqry = $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 = '.$other_user_id.' order by b.created DESC');
		$otherUserMembership = $otherUserqry->row_array();
		$otherUserMembershiphistory = 0;
		if(count($otherUserMembership)>0)
		{
			$otherUserMembershiphistory = $otherUserMembership['article_id'];
		}

		$number_to_restrict = $this->users_model->number_to_restrict();
		$userDetials = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		
		$upcomingLastBookedParty = $this->common_model->getAllRowMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','*,evt_events.alias','shop_booking_details.cart_id');
    	//echo $this->db->last_query(); die;
    	if(count($upcomingLastBookedParty)==0)
    	{
    		$upcomingLastBookedParty['time_from'] = 0;
    	}
        if(!empty($latest_messages))
		{        
                $user_message .= '';
        		if($membershipUser['article_id'] == 5 && $userDetials['accounttype']=='gentleman' && count($number_to_restrict)>50 && $otherUserMembershiphistory!=4)
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('Thank_you_for_using_our_community').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              	} 
              	elseif($membershipUser['article_id'] == 5 && $upcomingLastBookedParty['time_from']<time() && count($number_to_restrict)>50 && $userDetials['accounttype']=='couple' && $otherUserMembershiphistory!=4)
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('To_continue_upgrade_or_book').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              	}	
              	else
              	{
            		foreach ($latest_messages as $message) {    
                
                    	$user_message .= '<div class="conversation ';
                            if($message['from_user_id']==$this->session->userdata('user_id')){ 
                            	$user_message .= 'mysite';
                            } 
                            else { 
                            	$user_message .= 'othersite'; 
                            }
                            $user_message .='">
                            <div class="avatar">
                              <div class="mediumbgAvatar">';
								$user_message.='<img src="';
								if(!empty($message) && $message['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{
									$user_message.=base_url().'assets/images/default-avatar.jpg';
								}
								$user_message.='" alt="" srcset="';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){   $user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension']; 
								} 
								else
									{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 1x,';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'])){ 
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 2x" >';
								$user_message.='</div>

                            </div>
                            <div class="content">
                              <p>'.$message['text'].'</p>';
		                    if($message['image_path']){
		                    	$user_message .= '<p><a class="fancybox downloadAnchor" href="#inline'.$message['id'].'" data-fancybox-group="gallery" style="background:url('.base_url().$message['image_path'].') no-repeat center center / cover; min-width: 150px; min-height: 150px;" ><span class="dImageWrapper">'.getLang('View').'</span></a></p>';
		                    	$user_message .= '<div id="inline'.$message['id'].'" style="display:none;">
                                  <div class="hotshotWrapper">
                                    <div class="hotshotbody">
                                      <div class="border">
                                            <div style="background: url('.base_url().str_replace('message/', 'message_big/', $message['image_path']).') no-repeat center center / cover; " ></div>
                                        </div>
                                      </div>
                                    </div>
                                </div>';
		                    } 
		                    $user_message .= '</div>
                            <time>';
                            if(date('d',$message['created'])==date('d',time())){ 
                            	$user_message .=date('H:i',$message['created']);
                            }
                            else{ 
                            	$user_message .=date('M d',$message['created']); 
                            }
                            $user_message .=' <i class="fa fa-trash deleteCommunityMessage" data-id="'.$message['id'].'"></i></time>                        
                          </div>';
                        } 
                    }
                    $user_message .= '</div>';
		}
		echo $html= $user_message.'|'.$finaltime.'|'.count($latest_messages);exit;
	}
	public function sendMessage()
	{
		date_default_timezone_set("Europe/Zurich"); 
		$user_id = $this->input->post('user_id');
		$other_user_id = $this->input->post('other_user_id');
		//$text = $this->utility->info_cleanQuery($this->input->post('text'));
		$userDetialData = $this->common_model->getAllRow('usr_users',array('id'=>$user_id));
		$otherUserDetialData = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$other_user_id));
		$banned = 0;
		if(count($userDetialData)>0)
		{
			$banned = 0;
			if($userDetialData['ban_status']==1 && strtotime($userDetialData['ban_date']) >= strtotime(date("Y-m-d", strtotime("-30 days"))))
			{
				$banned = 1;
			}
			else
			{
				$this->common_model->UpdateData('usr_users',array('ban_status'=>0,'ban_date'=>0),array('id'=>$user_id));
			}
		}
		$user_blocked_data = $this->common_model->getAllRowMultipleJoin('usr_block',array('to_id'=>$user_id,'from_id'=>$other_user_id));
		if($banned==0 && !$user_blocked_data)
		{
			$text = $this->utility->info_cleanQuery($this->input->post('text'));
			if($this->session->userdata('user_id') != 11330)
			{
				$text = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i','',$text); // extract email
				//$text = preg_replace('/\d+/u', '', $text); // extract phonenumber
				$text = preg_replace('/(\d{5,})/', '', $text); // extract phonenumber
				$main = explode('@', $text);
				$pos = strpos($text,'@');
				if(count($main)>0 && $pos!==false)
				{
					if(count($main)>0)
						$start = explode(' ', trim($main[0]));
						array_pop($start);
						$text1 = implode(' ', $start);
					if(count($main)>1)
						$end = explode(' ', trim($main[1]));
						array_shift($end);
						$text2 = implode(' ', $end);
					$text = $text1.' '.$text2;	
				}
			}

			if($this->session->userdata('user_id') == 11330 || $this->session->userdata('user_id') == 25267)
			{
				$url_regex = '~(http|ftp)s?://[a-z0-9.-]+\.[a-z]{2,3}(/\S*)?~i';
				$text = preg_replace($url_regex, '<a class="link_anchor_text" href="$0" target="_blank">$0</a>', $text);
			}

			$file = '';
			if($_FILES['file']['name']!='')
			{
				$imagefolder = 'img/' ;
		        $uploadpath = 'assets/userfiles/'. $imagefolder;
				/*if (!file_exists(FCPATH . $uploadpath)) {
				    mkdir(FCPATH . $uploadpath, 0777, true);
				} */ 
				$filename = microtime().$_FILES['file']['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('file')) {

		            echo $this->upload->display_errors(); 
		        }

		        $uploaddata = $this->upload->data();
		        if($uploaddata)
		        {
		        	$file = $uploadpath.'message/'.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
		        	$config['image_library'] = 'gd2';
				    $config['source_image']  = $uploadpath.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
				    $config['new_image']  =  $uploadpath.'message/'.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
					$config['overwrite'] = TRUE;
					$config['width']	 = '100';
					$config['maintain_ratio'] = TRUE;
				    $this->load->library('image_lib');      
				    $this->image_lib->initialize($config);      
				    $this->image_lib->resize();


				    /**************Upload big version*******************************/
				    $config['image_library'] = 'gd2';
				    $config['source_image']  = $uploadpath.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
				    $config['new_image']  =  $uploadpath.'message_big/'.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
					$config['overwrite'] = TRUE;
					$config['width']	 = '500';
					$config['maintain_ratio'] = TRUE;
				    $this->load->library('image_lib');      
				    $this->image_lib->initialize($config);      
				    $this->image_lib->resize();
				    /**************Upload big version*******************************/
		        	
		        	/*$imagesize = getimagesize($uploaddata['full_path']);
			        $width 	= $imagesize[0];
			        if($width>800)
			        {
			        	$config['image_library'] = 'gd2';
					    $config['source_image']  = $uploadpath.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
					    $config['new_image']  =  $uploadpath.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1);
						$config['overwrite'] = TRUE;
						$config['width']	 = '800';
						$config['maintain_ratio'] = TRUE;
					    $this->load->library('image_lib');      
					    $this->image_lib->initialize($config);      
					    $this->image_lib->resize();
			        }*/
			    }
		        
			}
			
			$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'=>$other_user_id,'latest_read'=>0));
			$meg_message_instId = $this->common_model->insertData('msg_messages',array('created'=>time(),'conversation_id'=>$meg_conv_instId,'from_user_id'=>$user_id,'text'=>$text,'image_path'=>$file));


			$lastMailMesageSentTime = 0;
	    	$lastMailMesageSent = $this->common_model->getAllRow('notification',array('from_id'=>$user_id,'to_id'=>$other_user_id,'type'=>4),'','created DESC');
	    	if($lastMailMesageSent){
	    		$lastMailMesageSentTime = $lastMailMesageSent['created'];
	    	}
	    	
			$this->common_model->insertData('notification',array('from_id'=>$user_id,'to_id'=>$other_user_id,'type'=>4,'created'=>time()));
			if($text!='' && $otherUserDetialData['accept_terms']==1)
			{	
				/****************************Send mail***************************/
				include APPPATH.'libraries/Mailins.php';
		    	$mailin = new Mailin('https://api.sendinblue.com/v2.0','bs8yJF0cRaCOGMPt', 5000);

		    	

				$otherUserDetail = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$other_user_id),array(array('usr_users','usr_users.id = feu_userdetails.user_id'))) ;
				$currentUserDetail = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$user_id),array(array('usr_users','usr_users.id = feu_userdetails.user_id'))) ;
				
				$visitorData = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')));
				$visitedData = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$other_user_id),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
				
				$visitorPreference = $this->common_model->getAll('feu_sexual_preference',array('user_id'=>$this->session->userdata('user_id'))); 	

				$sub = 'Castleevents '.getLang('Instant_message');
				$visitorPreference = $this->common_model->getAll('feu_sexual_preference',array('user_id'=>$this->session->userdata('user_id'))); 	
			 	$genteman_age = (time() - $visitorData['dob_gentleman'])/(365*24*60*60);
	            $lady_age = (time() - $visitorData['dob_lady'])/(365*24*60*60);
					//print_r($visitorData); die;	
				$to = $visitedData['email'];
				//$to = $visitedData['email'];
				if($visitorData['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension']))     
	            {
	            	$cidurl = base_url().'/newsletter_image/'.$visitorData['filename'].'.'.$visitorData['extension'];
	  				$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$visitorData['filename'].'.'.$visitorData['extension']);
	            }
	            else
	            {
	            	$cidurl = base_url().'/newsletter_image/default-avatar.jpg';
	            }
	            $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',
		              '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->to($to); 
				$this->email->subject($sub);

				$body='<!DOCTYPE html>
									<html>
									   <head>
										  <meta http-equiv="content-type" content="text/html" 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;
											 }
										  </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%; background: #222222;">
											 <div style="max-width: 600px; margin: 40px auto;">
											   
														 <table cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 600px;">
															<tr>
															   <td style="padding: 20px 0; text-align: center; background:#131218;">
																  <a href="'.base_url().'"><img src="'.base_url().'newsletter_image/new-logo-mail.png" width="250" alt="Castleevents" border="0"></a>
															   </td>
															</tr>
														 </table>
														 <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="color: #e4e4e4;font-family: sans-serif;font-size: 15px;line-height: 20px;padding: 40px;">
			                                   <h5 style="font-size: 17px;padding-bottom: 10px;text-transform: capitalize;">'.getLang('Hello').' '.$visitedData['username'].'</h5>
											   <span><a href="'.base_url().'messages" style="color: #fff; text-decoration:none;">'.getLang('You_got_a_message').'</a> '.date('d.M.Y',time()).' '.getLang('at').' '.date('H:i',time()).'</span>												    
			                                </td>
			                             </tr>


			                             <tr>
			                                <td align="center" style="padding: 0 40px 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
			                                   <div style="background:#131218; padding: 20px; border-radius: 10px; text-align: center; display: inline-block; ">
			                                   <h2 style="text-transform:capitalize; font-size: 23px; padding-bottom: 10px; ">'.$visitorData['username'].'</h2>
												    <span style=" text-transform: capitalize; color: #fff; font-size: 16px; display: block; margin-bottom: 20px;">'.$visitorData['accounttype'].'-'.$visitorData['country_name'].',';
				                                    if($visitorData['dob_lady']>0){ 
				        $body.=							round($lady_age);
				                                    } 
				                                    elseif($visitorData['dob_gentleman']>0){ 
				        $body.=							round($genteman_age);
				                                    }  
				        $body.='                    </span>
				        							<!--<img src="'.$image.'" width="100" >-->
													<img src="'.$cidurl.'" width="100" >

				        							<p style="color: #666; font-size: 14px; ">';
			                            			$usermeetingdata = '';
					                                if($visitorData['experience']==1)
					                                {
					                                  $usermeetingdata .= getLang('New_experience').', ';
					                                }
					                                $usermeetingdata .= getLang(str_replace('-', '_', str_replace(' ', '_', $visitorData['preferences'])));
					                                if($visitorData['preferences']=='full_swap' && ($visitorData['same_room']==1 || $visitorData['separate_room']==1))
					                                {
					                                    $usermeetingdata .= ' (';
					                                    if($visitorData['same_room']==1)
					                                    {
					                                      $usermeetingdata .= getLang('Same_Room');
					                                    } 
					                                    if($visitorData['same_room']==1 && $visitorData['separate_room']==1)
					                                    {
					                                      $usermeetingdata .= ',';
					                                    } 
					                                    if($visitorData['separate_room']==1)
					                                    {
					                                      $usermeetingdata .= getLang('Separate_Room');
					                                    } 
					                                    $usermeetingdata .= ') ';  
					                                }
					                                $usermeetingdata .= ', ';
					                                if($visitorData['escort_interest']==1)
					                                {
					                                    $usermeetingdata .= ' '.getLang('Looking_for_companion').', ';
					                                }
					                                if($visitorData['interested_in_private_meeting']==1)
					                                {
					                                    $usermeetingdata .= ' '.getLang('Ceremony').', ';
					                                }
					            $body.=                 $usermeetingdata;

					            					if(!empty($visitorPreference)){ 
					                                    $i=1;
					                                    foreach ($visitorPreference as $preference) {
					                                      $comma = '';
					                                        if($i!=count($visitorPreference))
					                                        {
					                                          $comma = ',';
					                                        }
					                                    
					            $body.=                     getLang(str_replace('-', '_', str_replace(' ', '_', $preference['sex_preference']))).' '.$comma;
					                                    $i++; } } 

			        $body.='                  </p>

			        							</div>
			                                </td>
			                             </tr>';
			                        

			        $body.='             <tr>
			                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
			                                   <h5 style="color: #ffffff;font-size: 17px;padding-bottom: 10px;">visit the profile:</h5>
											   <span><a style="color: #b3975b;font-size: 18px;" href="https://castleevents.com/messages">https://castleevents.com/messages</a></span>												    
			                                </td>
			                             </tr>

			                             <tr>
			                                <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
			                                   <span style="color: #666">'.getLang('If_you_do_not_wish_any_mail').'.</span>												    
			                                </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;">
			                             		'.getLang('Best_regards').' <br>
			                             		<p style="margin:5px 0 0; color:#b3975b">'.getLang('Your_Castleevents_Team').'</p> 
			                             	</td>
			                             </tr>
			                          </table>
			                       </td>
			                    </tr>
			                </table></div>
											  </center>
										   </body>
										</html>';

		            // echo  $body; die;  	
					if($template){
				  		$cont='<!DOCTYPE html>
												<html>
												   <head>
													  <meta http-equiv="content-type" content="text/html" 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;
														 }
													  </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%" bgcolor="#222222" style="Margin: 0;">
								  <center style="width: 100%; background: #222222;">
									 <div style="max-width: 600px; margin: 40px auto;">
									   
												 <table cellspacing="0" cellpadding="0" border="0" align="center" width="100%" style="max-width: 600px;">
													<tr>
													   <td style="padding: 20px 0; text-align: center; background:#131218;">
														  <a href="'.base_url().'"><img src="'.base_url().'newsletter_image/new-logo-mail.png" width="250" alt="Castleevents" border="0"></a>
													   </td>
													</tr>
												 </table>'.$body.'</div>
									  </center>
								   </body>
								</html>';
				}
				else
				{
				 	$cont=$body;
				}
				$this->email->message($cont);
				//echo time().'|'.$lastMailMesageSentTime.'|'.(time()-$lastMailMesageSentTime);die;
				if($lastMailMesageSentTime==0 || (time()-$lastMailMesageSentTime) >= 600){
					$mail = $this->email->send();
				}
				/****************************Send mail***************************/

			}
		}
		$html = '';
		$lastMessage = '';
		$user_chat = '';
		$user_message = '';
		$latest_userDetails = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$other_user_id),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		
		$latest_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,5,0);
		$final_messages = $this->users_model->conversationLimit($this->session->userdata('user_id'),$other_user_id,0,1,0);
		$lasttime = 0;
		if(count($latest_messages)>0)
		{
			$lasttime = $latest_messages[count($latest_messages)-1]['created'];
		}
		$finaltime = 0;
		if(count($final_messages)>0)
		{
			$finaltime = $final_messages[0]['created'];
		}	

		$latest_messages = array_reverse($latest_messages);

		$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 = '.$this->session->userdata('user_id').' order by b.created DESC');
		$membershipUser = $qry->row_array();
		$number_to_restrict = $this->users_model->number_to_restrict();
		$userDetials = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'))) ;
		
		$upcomingLastBookedParty = $this->common_model->getAllRowMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','*,evt_events.alias','shop_booking_details.cart_id');
    	//echo $this->db->last_query(); die;
    	if(count($upcomingLastBookedParty)==0)
    	{
    		$upcomingLastBookedParty['time_from'] = 0;
    	}

    	$otherUserqry = $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 = '.$other_user_id.' order by b.created DESC');
		$otherUserMembership = $otherUserqry->row_array();
		$otherUserMembershiphistory = 0;
		if(count($otherUserMembership)>0)
		{
			$otherUserMembershiphistory = $otherUserMembership['article_id'];
		}

		
        if(!empty($latest_messages))
		{        
                $user_message .= '<div id="chatwrapper"  class="chat_wrapper " style="overflow-y:auto;">
                    <!--<div id="chatwrapper"  class="chat_wrapper mCustomScrollbar light" data-mcs-theme="minimal-dark">-->
                        <time>'.date('M d',$latest_messages[count($latest_messages)-1]['created']).'</time>';
            	if($membershipUser['article_id'] == 5 && $userDetials['accounttype']=='gentleman' && count($number_to_restrict)>50 && $otherUserMembershiphistory!=4)
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('Thank_you_for_using_our_community').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              	} 
              	elseif($membershipUser['article_id'] == 5 && $upcomingLastBookedParty['time_from']<time() && count($number_to_restrict)>50 && $userDetials['accounttype']=='couple' && $otherUserMembershiphistory!=4)
              	{
                	$user_message .='<div class="conversation seeAllUpgrade"><h3>'.getLang('To_continue_upgrade_or_book').'</h3><a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></div>';
              	}	
              	else
              	{
            		foreach ($latest_messages as $message) {    
	                	$lastMessage = $message['text'];

	                    $user_message .= '<div class="conversation ';
                            if($message['from_user_id']==$this->session->userdata('user_id')){ 
                            	$user_message .= 'mysite';
                            } 
                            else { 
                            	$user_message .= 'othersite'; 
                            }
                            $user_message .='">
                            <div class="avatar">
                              <div class="mediumbgAvatar">';
								$user_message.='<img src="';
								if(!empty($message) && $message['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{
									$user_message.=base_url().'assets/images/default-avatar.jpg';
								}
								$user_message.='" alt="" srcset="';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension'])){   $user_message.=base_url().'assets/userfiles/'.$message['path'].'/80/'.$message['filename'].'.'.$message['extension']; 
								} 
								else
									{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 1x,';
								if(!empty($message['filename']) && file_exists(FCPATH.'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'])){ 
									$user_message.=base_url().'assets/userfiles/'.$message['path'].'/160/'.$message['filename'].'.'.$message['extension'];
								} 
								else
								{ 
									$user_message.=base_url().'assets/images/default-avatar.jpg'; 
								}
								$user_message.=' 2x" >';
								$user_message.='</div>

                            </div>
                            <div class="content">
                              <p>'.$message['text'].'</p>';
	                    if($message['image_path']){
	                    	$user_message .= '<p><a class="fancybox downloadAnchor" href="#inline'.$message['id'].'" data-fancybox-group="gallery" style="background:url('.base_url().$message['image_path'].') no-repeat center center / cover; min-width: 150px; min-height: 150px;" ><span class="dImageWrapper">'.getLang('View').'</span></a></p>';
		                    	$user_message .= '<div id="inline'.$message['id'].'" style="display:none;">
                                  <div class="hotshotWrapper">
                                    <div class="hotshotbody">
                                      <div class="border">
                                            <div style="background: url('.base_url().str_replace('message/', 'message_big/', $message['image_path']).') no-repeat center center / cover; " ></div>
                                        </div>
                                      </div>
                                    </div>
                                </div>';
	                    } 
	                    $user_message .= '</div>
                            <time>';
                            if(date('d',$message['created'])==date('d',time())){ 
                            	$user_message .=date('H:i',$message['created']);
                            }
                            else{ 
                            	$user_message .=date('M d',$message['created']); 
                            }
                            $user_message .=' <i class="fa fa-trash deleteCommunityMessage" data-id="'.$message['id'].'"></i></time>
                          </div>';
                    }
                } 
                    $user_message .= '</div>';
		}
		if($banned==0 && !$user_blocked_data) {
			echo $html= $user_chat.'|'.$user_message.'|'.$lastMessage; exit;
		} else if($user_blocked_data){
			echo $html= 11;die;
		} else {
			echo $html= 10;die;
		}
	}
	public function hotshot_profile()
	{
		$user_id = $this->input->post('user_id');
		$from_id = $this->session->userdata('user_id');
		$getdata = $this->common_model->getAllRow('like_likes',array('user_id'=>$from_id,'identifier'=>'profile:'.$user_id));
		if(empty($getdata))
		{
			$inst_arr = array(
							'created'=>time(),
							'identifier'=>'profile:'.$user_id,
							'user_id'=>$from_id,
						);
			$inst = $this->common_model->insertData('like_likes',$inst_arr);
			$this->common_model->insertData('notification',array('from_id'=>$from_id,'to_id'=>$user_id,'type'=>8,'created'=>time()));
			echo getLang('Added_to_Hotshot');
		}
		else
		{
			echo getLang('Already_added_to_Hotshot');
		}
		exit;
	}
	public function hotshot_picture()
	{
		$file_id = $this->input->post('file_id');
		$from_id = $this->session->userdata('user_id');
		$getdata = $this->common_model->getAllRow('like_likes',array('user_id'=>$from_id,'identifier'=>'picture:'.$file_id));
		$html = '';
		if(empty($getdata))
		{
			$inst_arr = array(
							'created'=>time(),
							'identifier'=>'picture:'.$file_id,
							'user_id'=>$from_id,
						);
			$inst = $this->common_model->insertData('like_likes',$inst_arr);
			$likeUsers = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$from_id),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')));
			$toUserDetails = $this->common_model->getAllRowMultipleJoin('ugal_images',array('file_id'=>$file_id),array(array('feu_userdetails','feu_userdetails.user_id = ugal_images.user_id')),'','feu_userdetails.user_id');
			$this->common_model->insertData('notification',array('from_id'=>$from_id,'to_id'=>$toUserDetails['user_id'],'file_id'=>$file_id,'type'=>9,'created'=>time()));
			$html.='<li>
	                    <div class="mediumbgAvatar" style="background: url(';
	                	if(!empty($likeUsers['filename']) && file_exists(FCPATH.'assets/userfiles/'.$likeUsers['path'].'/'.$likeUsers['filename'].'.'.$likeUsers['extension'])){ 
	                		$html.=base_url().'assets/userfiles/'.$likeUsers['path'].'/'.$likeUsers['filename'].'.'.$likeUsers['extension']; 
	                	}
	                	else 
	                	{ 
	                		$html.='images/default-avatar.jpg';
	                	}
	                $html.=') no-repeat center center / cover; "></div>
	                </li>';
		}
		echo $html;exit;
	}
	public function hotshot_party()
	{
		$party_id = $this->input->post('party_id');
		$from_id = $this->session->userdata('user_id');
		$getdata = $this->common_model->getAllRow('like_likes',array('user_id'=>$from_id,'identifier'=>'party:'.$party_id));
		if(empty($getdata))
		{
			$inst_arr = array(
							'created'=>time(),
							'identifier'=>'party:'.$party_id,
							'user_id'=>$from_id,
						);
			$inst = $this->common_model->insertData('like_likes',$inst_arr);
			$this->common_model->insertData('notification',array('from_id'=>$from_id,'to_id'=>1,'type'=>13,'request_id'=>$party_id,'created'=>time()));
			echo getLang('Added_to_Hotshot');
		}
		else
		{
			echo getLang('Already_added_to_Hotshot');
		}
		exit;
	}
	function currentMessage()
	{
		$to_id = $this->session->userdata('user_id');
		$messages = $this->common_model->getAllMultipleJoin('msg_conversations',array('user_id'=>$to_id,'msg_conversations.created >'=>time()-5*60*60),array(array('msg_conversations_users','msg_conversations_users.conversation_id = msg_conversations.id')),'msg_conversations.created DESC','count(*)');
	}
	public function deleteAddress($id= '')
	{
		$this->common_model->deleteData('feu_addresses',array('id'=>$id));
		redirect(base_url().'setting');
	}	
	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('60','80','120','160','240','320');
	$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 updateCardInfo(){
		if($this->input->post('order_id'))
		{
			$order_id = $this->input->post('order_id');
			if($order_id > 0)
			{
				$userdetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$this->session->userdata('user_id'),'order_id'=>$order_id),array(array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created DESC');
			}
			else
			{
				$userdetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$this->session->userdata('user_id'),'payed'=>1,'is_booking'=>0,'cancelled'=>0,'refund_trn_id'=>''),array(array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created DESC');
			}
		}
		else
		{
			$userdetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('usr_users.id'=>$this->session->userdata('user_id'),'payed'=>1,'is_booking'=>0,'cancelled'=>0,'refund_trn_id'=>''),array(array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created DESC');
		}
		
		//pr($userdetails);
		if($userdetails)
		{
			if($this->input->post('order_id'))
			{
				$orderId = $this->input->post('order_id');
				if($orderId > 0)
				{
					//new code
				}
				else
				{

					
					$user_subscrip_details = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		
					 $shop_order = $this->common_model->getAllRow('shop_orders',array('is_renewed'=>1 , 'is_booking'=>0 ,'payed'=>0, 'invoiceAddress'=>$user_subscrip_details[0]['email'] ),'','created DESC'); 
					 
					 $orderId=$shop_order['order_id'];
				}
			}
			else
			{
				
				
				$user_subscrip_details = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		
				$shop_order = $this->common_model->getAllRow('shop_orders',array('is_renewed'=>1 , 'is_booking'=>0 ,'payed'=>0, 'invoiceAddress'=>$user_subscrip_details[0]['email'] ),'','created DESC'); 
					 
				$orderId=$shop_order['order_id'];
			}
			/*********TEST*************/
			/*$CustomerId = 246934;	
			$TerminalId = 17951970;	
			$username = 'API_246934_23183450';
			$password = 'JsonApiPwd1_a8EpfvCy';*/	
			/*********TEST*************/
//echo $orderId; die();
			/*********LIVE*************/
			$CustomerId = 403547;
			$TerminalId = 17799239;	
			$username = 'API_403547_78643204';
			$password = 'JsonApiPwdAnexus1_a8EpfvCy';	
			/*********LIVE*************/
			/***********************Create Card Alias Direct********************/
				$JSONObj  = '{
				  "RequestHeader": {
				    "SpecVersion": "1.10",
				    "CustomerId": "'.$CustomerId.'",
				    "RequestId": "aScdFewDSRFrfas2wsad3",
				    "RetryIndicator": 0
				  },
				  "PaymentMeans": {
				    "Card": {
				      "Number": "'.$this->input->post('card_number').'",
				      "ExpYear": '.$this->input->post('exp_year').',
				      "ExpMonth": '.$this->input->post('exp_month').',
				      "HolderName": "'.$this->input->post('card_holder').'",
				      "VerificationCode": "'.$this->input->post('card_cvc').'"
				    }
				  },
				  "RegisterAlias": {
				    "IdGenerator": "RANDOM"
				  }
				}';
				//$url = 'https://test.saferpay.com/api/Payment/v1/Alias/InsertDirect';
				$url = 'https://www.saferpay.com/api/Payment/v1/Alias/InsertDirect';
			    
			    $JSONObj = json_decode($JSONObj);
			    $curl = curl_init($url);
			    curl_setopt($curl, CURLOPT_HEADER, false);
			    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
			    curl_setopt($curl, CURLOPT_POST, true);
			    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
			    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
			    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
			    $jsonResponse = curl_exec($curl);
			    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			    if ( $status != 200 ) {
			        if($status == 400) {
			    		$fail_reason = 'Validation error';
			    	} elseif($status == 401) {
			    		$fail_reason = 'Authentication of the request failed';
			    	} elseif($status == 402) {
			    		$fail_reason = 'Requested action failed';
			    	} elseif($status == 403) {
			    		$fail_reason = 'Access denied';
			    	} elseif($status == 406) {
			    		$fail_reason = 'Not acceptable (wrong accept header)';
			    	} elseif($status == 415) {
			    		$fail_reason = 'Unsupported media type (wrong content-type header)';
			    	} elseif($status == 500) {
			    		$fail_reason = 'Internal error';
			    	} else {
			    		$fail_reason = 'Authorization denied';
			    	}
			        $errorresponse = json_decode($jsonResponse, true);
			    	if($errorresponse)
			    	{
			    		if($errorresponse['ProcessorMessage'])
			    		{
			    			$fail_reason = $errorresponse['ProcessorMessage'];
			    		}
			    	}
			    	$this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
			        die("Error: ".$fail_reason);
			    }
			    curl_close($curl);
			    $aliasresponse = json_decode($jsonResponse, true);


			    /***********************Create Transaction Direct********************/
				$JSONObj  = '{
				  "RequestHeader": {
				    "SpecVersion": "1.10",
				    "CustomerId": "'.$CustomerId.'",
				    "RequestId": "aScdFewDSRFrfas2wsad3",
				    "RetryIndicator": 0
				  },
				  "TerminalId": "'.$TerminalId.'",
				  "Payment": {
				    "Amount": {
				      "Value": "'.(int)$userdetails['total_sum'].'",
				      "CurrencyCode": "EUR"
				    },
				    "Description": "Membership",
				    "PayerNote": "Membership"
				  },
				  "PaymentMeans": {
				    "Alias": {
				      "Id": "'.$aliasresponse['Alias']['Id'].'"
				    }
				  }
				}';

				//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
				$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
			    
			    $JSONObj = json_decode($JSONObj);
			    $curl = curl_init($url);
			    curl_setopt($curl, CURLOPT_HEADER, false);
			    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
			    curl_setopt($curl, CURLOPT_POST, true);
			    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
			    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
			    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
			    $jsonResponse = curl_exec($curl);
			    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			    if ( $status != 200 ) {
			        if($status == 400) {
			    		$fail_reason = 'Validation error';
			    	} elseif($status == 401) {
			    		$fail_reason = 'Authentication of the request failed';
			    	} elseif($status == 402) {
			    		$fail_reason = 'Requested action failed';
			    	} elseif($status == 403) {
			    		$fail_reason = 'Access denied';
			    	} elseif($status == 406) {
			    		$fail_reason = 'Not acceptable (wrong accept header)';
			    	} elseif($status == 415) {
			    		$fail_reason = 'Unsupported media type (wrong content-type header)';
			    	} elseif($status == 500) {
			    		$fail_reason = 'Internal error';
			    	}
			    	$errorresponse = json_decode($jsonResponse, true);
			    	if($errorresponse)
			    	{
			    		if($errorresponse['ProcessorMessage'])
			    		{
			    			$fail_reason = $errorresponse['ProcessorMessage'];
			    		}
			    	}
			        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
			        die("Error: ".$fail_reason);
			    }
			    curl_close($curl);
			    $transactionresponse = json_decode($jsonResponse, true);
			    $this->common_model->UpdateData('shop_orders',array('real_name'=>$transactionresponse['PaymentMeans']['Card']['HolderName'], 'card_origin'=>$transactionresponse['PaymentMeans']['Card']['CountryCode']),array('order_id'=>$orderId));
			  	//echo "<pre>";
				//print_r($transactionresponse);die;
			/***********************Create Transaction Direct********************/


			/***********************Create Capture Direct********************/
				$JSONObj  = '{
				  "RequestHeader": {
				    "SpecVersion": "1.10",
				    "CustomerId": "'.$CustomerId.'",
				    "RequestId": "aScdFewDSRFrfas2wsad3",
				    "RetryIndicator": 0
				  },
				  "TransactionReference": {
				    "TransactionId": "'.$transactionresponse['Transaction']['Id'].'"
				  }
				}';
				//echo $JSONObj;die;
				//$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Capture';
				$url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Capture';
			    
			    $JSONObj = json_decode($JSONObj);
			    $curl = curl_init($url);
			    curl_setopt($curl, CURLOPT_HEADER, false);
			    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
			    curl_setopt($curl, CURLOPT_POST, true);
			    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
			    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
			    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
			    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
			    $jsonResponse = curl_exec($curl);
			    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			    if ( $status != 200 ) {
			        if($status == 400) {
			    		$fail_reason = 'Validation error';
			    	} elseif($status == 401) {
			    		$fail_reason = 'Authentication of the request failed';
			    	} elseif($status == 402) {
			    		$fail_reason = 'Requested action failed';
			    	} elseif($status == 403) {
			    		$fail_reason = 'Access denied';
			    	} elseif($status == 406) {
			    		$fail_reason = 'Not acceptable (wrong accept header)';
			    	} elseif($status == 415) {
			    		$fail_reason = 'Unsupported media type (wrong content-type header)';
			    	} elseif($status == 500) {
			    		$fail_reason = 'Internal error';
			    	}
			    	$errorresponse = json_decode($jsonResponse, true);
			    	if($errorresponse)
			    	{
			    		if($errorresponse['ProcessorMessage'])
			    		{
			    			$fail_reason = $errorresponse['ProcessorMessage'];
			    		}
			    	}
			        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('order_id'=>$orderId));
			        die("Error: ".$fail_reason);
			    }
			    curl_close($curl);
			    $response = json_decode($jsonResponse, true);
			    
			  	//echo "<pre>";
				//print_r($response);die;
			/***********************Create Capture Direct********************/
			//print_r($cc_ref_id_result);die;

			if($response)
			{
				$this->common_model->deleteData('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
				$this->common_model->UpdateData('shop_orders',array('payed'=>1,'trn_id'=>$transactionresponse['Transaction']['Id'],'payment_method_id'=>13,'payment_date'=>date('Y-m-d'),'fail_reason'=>''),array('order_id'=>$orderId));
				$cc_pan = 'xxxx xxxx xxxx '.substr($this->input->post('card_number'), -4);
				$expYr = substr($this->input->post('exp_year'), -2);
				$expMth = str_pad($this->input->post('exp_month'), 2, '0', STR_PAD_LEFT);
				$saferpay_exp = $expMth.$expYr;
				$this->common_model->UpdateData('usr_users',array('card_alias'=>$aliasresponse['Alias']['Id'],'cc_pan'=>$cc_pan,'saferpay_exp'=>$saferpay_exp),array('id'=>$this->session->userdata('user_id')));
				
				/**************FREE MEMBERSHIP**************/
				$namedetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
				$to = $userdetails['email'];
				$sub = getLang('Membership_Invoice_mail_from').' Castleevents';
				//$body= '<p>Dear '.$userData['username'].',</p>';
				$body= '<p>'.getLang('We_have_received_your_payment').'!</p>';
				$body.= '<p>'.getLang('Invoice_Number').': CE-'.$orderId.'</p><p>'.getLang('Generated_On').': '.date('Y-m-d',time()).'</p><p>'.getLang('Paid_Amount').': '.number_format(($userdetails['total_sum']/100),2, '.', '').' EUR</p>';
				$body.= '<p>'.getLang('Invoice_will_be_located').' www.castleevents.com.</p>';
				$body.= '<p>'.getLang('We_appreciate_very_much').'.</p>';
				$body.= '<p>'.getLang('Please_do_not_hesitate_to_contact').'.</p>';
				$body.= '<p></p>';
				$body.= '<p>This payment is related our <a href="'.base_url('terms').'">terms and conditions</a> confirmed from you on '.date('d-m-Y H:i:s').' </p>';
				//$body.= '<p>Best regards,</p><p>Your Castleevents Team </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>'.getLang('Dear').' <span style="text-transform:capitalize">'.$namedetails['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;">
                         		'.getLang('Best_regards').' <br>
                         		<p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
                         	</td>
                         </tr>
                      </table>
                   </td>
                </tr>
            </table>';


			$this->utility->sendOrderMail($to,$sub,$bodys);
				/****extra mail****/
					$to = 'alorenc@me.com';
					$sub = 'Payment recieved';
					$body= 'CE-'.$orderId.', EUR '.number_format(($userdetails['total_sum']/100), 2,',', '.');
					$body.= '<p>Paid Renewal Membership Fees</p>';
					$body.= '<p>'.$namedetails['username'].'</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 style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
					                           '.$body.'
					                        </td>
					                     </tr>
					                  </table>
					               </td>
					            </tr>
					        </table>';
					$this->utility->sendOrderMail($to,$sub,$bodys);
				/****extra mail****/
				echo 2;
			}
		}
		exit;
	}
	function putContent($source='',$dest='')
	{
		//$source = $_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/avatars//80/d8638342de86a99346c1cb8eaa67f8ed.png';
		//$dest = $_SERVER['DOCUMENT_ROOT'].'/newsletter_image/d8638342de86a99346c1cb8eaa67f8ed.png';
		$size = getimagesize($source);
		$this->load->library('Utility');
		$this->utility->pic_resize($source,$dest,$size[0],$size[1]);
		//print_r($size);
		//die;
	}
	function deleteMobile($enc_id ='')
	{
		if($enc_id)
		{
			$id = base64_decode($enc_id);
			$this->common_model->deleteData('usr_phones',array('id'=>$id));
		}
		redirect(base_url().'setting');
	}
	function setDefaultMobile($enc_id ='')
	{
		if($enc_id)
		{
			$id = base64_decode($enc_id);
			$mobileDetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
			$newMobileDetails = $this->common_model->getAllRow('usr_phones',array('id'=>$id));
			$this->common_model->updateData('feu_userdetails',array('mobile_number'=>$newMobileDetails['mobile_number']),array('user_id'=>$this->session->userdata('user_id')));
			$this->common_model->updateData('usr_phones',array('mobile_number'=>$mobileDetails['mobile_number']),array('id'=>$id));
		}
		redirect(base_url().'setting');
	}
	function before_settings()
	{
		$this->session->set_userdata('upgradeSet',1);
		redirect(base_url().'setting');
	}
	public function success()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		//print_r($content_data['orders']);die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Successful_payment')." | Castleevents";
		$data['content'] = $this->load->view('success', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	function getmorefriend()
	{
		$limit = $this->input->post('data');
		$to_friend = $this->users_model->latestConversationLimit(6,$limit);
		//pr($to_friend);
		$i = 0; 
		$html = '';
        if(!empty($to_friend))
		{ 
	        foreach ($to_friend as $t_friend) {
	            $html.='<li id="user_';
	            if($t_friend['user_id']!=$this->session->userdata('user_id')){
	            	$html.=$t_friend['user_id']; 
	            } 
            	else {
            	    $html.=$t_friend['from_user_id']; 
            	}
	            $html.='" class="listUser" data-id="';
	            if($t_friend['user_id']!=$this->session->userdata('user_id')){
	            	$html.=$t_friend['user_id']; 
	            } 
            	else {
            	    $html.=$t_friend['from_user_id']; 
            	}
	            
	            $html.='">
	            <a href="javascript:void(0)" class="clearfix">
	            <div class="mediumbgAvatar">';
	            $html.='<img src="';
				if(!empty($t_friend) && $t_friend['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension'])){
					$html.=base_url().'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension'];
				} 
				else
				{
					$html.=base_url().'assets/images/default-avatar.jpg';
				}
				$html.='" alt="" srcset="';
				if(!empty($t_friend['filename']) && file_exists(FCPATH.'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension'])){   
					$html.=base_url().'assets/userfiles/'.$t_friend['path'].'/80/'.$t_friend['filename'].'.'.$t_friend['extension']; 
				} 
				else
				{ 
					$html.=base_url().'assets/images/default-avatar.jpg'; 
				}
				$html.=' 1x,';
				if(!empty($t_friend['filename']) && file_exists(FCPATH.'assets/userfiles/'.$t_friend['path'].'/160/'.$t_friend['filename'].'.'.$t_friend['extension']))
				{ 
					$html.=base_url().'assets/userfiles/'.$t_friend['path'].'/160/'.$t_friend['filename'].'.'.$t_friend['extension'];
				} 
				else
				{ 
					$html.=base_url().'assets/images/default-avatar.jpg'; 
				}
				$html.=' 2x" >';
	            $html.='</div>
	             	<div class="conversation_text">                     
	               <h5>'.$t_friend['username'].'</h5>
	               <div class="action-btns">
	                <time class="last_talktime">';
	            $html.=	date('M d',$t_friend['created']);
	            $html.='</time>                          
	                <!--<span><i class="fa  fa-trash"></i></span>-->
	               </div>                      
	               <p class="last_talk">';
	            $html.=strip_tags(substr($t_friend['text'],0,20));
	            $html.='</p>
	             </div>
	            </a>
	          </li>';
	    	}
	    }
    	$html.='<li class=""><div class="ajax-loader_msg"  style="display:none;">
        <img src="images/Rolling.svg" class="img-responsive" />
      	</div><div class="more_user" data-id="'.($limit+6).'" style="cursor:pointer;text-align: center;"></div></li>';
    	$html.='';
    	echo $html;exit;
	}
	public function participation()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		if(checkStep()==1)
		{
			redirect('profile');
		}
		if($this->session->userdata('user_id')){
			if(getOpenBookingInvoices() > 0)
			{
				$this->session->set_userdata('pay_book_first',1);
				redirect('invoice');
			}
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'','*,feu_userdetails.user_id') ;
		$content_data['invoices'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'payed'=>1,'shop_orders.is_booking'=>1,'shop_booking_details.event_id >'=>0),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_booking_details.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_language_values.title,evt_events.alias','evt_events.id,shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		
		$ids = '';
		if(!empty($content_data['invoices']))
		{
			foreach ($content_data['invoices'] as $key => $value) {
				if($value['event_id']>0)
				{
					$ids = $ids.$value['event_id'].',';
				}
			}
			//echo $ids;die;
		}
		$where="";
		if($ids != '')
		{
			$where = " `shop_carts`.`user_id` = ".$this->session->userdata('user_id')." AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0 and evt_events.id not in (".trim($ids,',').")";
		}
		else
		{
			$where = " `shop_carts`.`user_id` = ".$this->session->userdata('user_id')." AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0";
		}
		//echo $where;die;
		//$content_data['userParticipation_old'] = array();
		$content_data['old_invoices'] = $this->common_model->getAllMultipleJoin('shop_orders',$where,array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'shop_carts.created DESC','*,evt_events.title,evt_events.alias','evt_events.id,shop_articles_carts.event_id');
		//$content_data['old_invoices'] = $this->common_model->getAllMultipleJoin('shop_articles',array('shop_articles_carts.event_id !='=>'','shop_carts.user_id'=>$this->session->userdata('user_id'),'evt_language_values.lang_id'=>$langId),array(array('shop_articles_carts','shop_articles_carts.article_id = shop_articles.id'),array('shop_carts','shop_carts.id = shop_articles_carts.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('evt_events','evt_events.id = shop_articles_carts.event_id'),array('evt_language_values','evt_language_values.event_id = evt_events.id'),array('loc_events_locations','loc_events_locations.event_id = evt_events.id'),array('loc_locations','loc_locations.id = loc_events_locations.location_id')),'shop_orders.created DESC','*,evt_events.alias,shop_orders.created as created','shop_articles_carts.event_id');
		//echo $this->db->last_query();die;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		//print_r($content_data['orders']);die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Participation')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('participartion', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function show_participation($event_id,$status)
	{
		$event_id = base64_decode($event_id);
		if($status==2)
		{
			$status = 0;
		}
		$getValue = $this->common_model->getAllRow('user_to_event',array('user_id'=>$this->session->userdata('user_id'),'event_id'=>$event_id));
		if($getValue)
		{
			$this->common_model->UpdateData('user_to_event',array('status'=>$status),array('user_id'=>$this->session->userdata('user_id'),'event_id'=>$event_id));
		}
		else
		{
			$this->common_model->insertData('user_to_event',array('user_id'=>$this->session->userdata('user_id'),'event_id'=>$event_id,'status'=>$status));
		}
		redirect(base_url().'participation');
	}
	public function deleteCommunityMessage()
	{
		$id = $this->input->post('id');
		$getdata = $this->common_model->getAllRow('msg_conversations',array('id'=>$id));
		if(count($getdata)>0)
		{
			$this->common_model->deleteData('msg_conversations',array('id'=>$id));
			$this->common_model->deleteData('msg_conversations_users',array('conversation_id'=>$id));
			$this->common_model->deleteData('msg_messages',array('conversation_id'=>$id));
		}
		exit;
	}
	public function deleteCommunityWholeMessage()
	{
		$user_id = $this->input->post('id');
		$from_id = $this->session->userdata('user_id');
		$getdata = $this->users_model->conversation($from_id,$user_id);
		//pr($getdata);
		if(count($getdata)>0)
		{
			foreach ($getdata as $key => $value) {
				$this->common_model->deleteData('msg_conversations',array('id'=>$value['id']));
				$this->common_model->deleteData('msg_conversations_users',array('conversation_id'=>$value['id']));
				$this->common_model->deleteData('msg_messages',array('conversation_id'=>$value['id']));
			}
		}
		exit;
	}
	public function download_invoice($order_id){
		$order_id = base64_decode($order_id);
		$orderDetails = $this->common_model->getAllRow('shop_orders',array('order_id'=>$order_id));
		if($orderDetails && $orderDetails['order_id'] > 0) {
			$userDetails = $this->common_model->getAllRow('usr_users',array('email'=>$orderDetails['invoiceAddress']),array('feu_userdetails','feu_userdetails.user_id = usr_users.id'));
			$site_address_name = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
			$site_address_city = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
			$site_address_country_zip = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));
			$payment_method = '';
	        if($orderDetails['payment_method_id']==13){ 
	        	$payment_method = 'Saferpay'; 
	        } elseif($orderDetails['payment_method_id']==14){ 
	        	$payment_method = 'Credit Card'; 
	        } elseif($orderDetails['payment_method_id']==12){ 
	        	$payment_method = 'Bank Transfer'; 
	        } else{ 
	        	$payment_method = 'Pay By Bank'; 
	        }
	        $title = ucfirst($orderDetails[0]['alias']).' Membership fee'; 
			if($orderDetails['upgrade_date'] > 0 ){ $cdate = $orderDetails['upgrade_date'];}else{$cdate = $orderDetails['created'];} 
			
	    	$date = date('d-m-Y',$cdate);
	        if($orderDetails['time']==365)
	    	{
	    		$title .= ' 12 Months from '.$date;
	    	}
	    	else
	    	{
	    		$title .= ' 6 Months from '.$date;
	    	}
	    	$book='Order';
			$html='<!DOCTYPE html>
						<html>
						   <head>
						      <title>invoice</title>
						   </head>
						   <body>
						      <div style="max-width:960px; width:100%; margin:0 auto 0; font-family: sans-serif; padding: 0 50px;">
						         <div style="padding: 50px 0 70px; ">
						          <p style="margin:0;">'.$site_address_name['value'].'</p>
						          <p style="margin:0;">'.$site_address_city['value'].',</p>
						          <p style="margin:0;">'.$site_address_country_zip['value'].'</p>
						          <p style="padding-top: 10px;">UID: CHE-362.535.263</p>
						         </div>
						         <h2 style="padding: 10px;border-bottom:1px solid #ccc; display: block;">INVOICE</h2>
						         <table style="padding:0px 10px 0 0px; width: 100%; margin-bottom: 36px;">
						            <tr>
						               <td style="padding:10px ; font-weight: bold;">Order No</td>
						               <td style="padding:10px ;">'.$orderDetails['order_id_masked'].'</td>
						            </tr>';
						            
						            
						    $html.='<tr>
						               <td style="padding:10px ; font-weight: bold;">Username</td>
						               <td style="padding:10px ;">'.$userDetails['username'].'</td>
						            </tr><tr>
						               <td style="padding:10px ; font-weight: bold;">Email</td>
						               <td style="padding:10px ;">'.$orderDetails['invoiceAddress'].'</td>
						            </tr>';
						           $html.=' <tr>
						               <td style="padding:10px ; font-weight: bold;"> Payment Method </td>
						               <td style="padding:10px ;">'.$payment_method.'</td>
						            </tr>
						         </table>
						         <div style="width:700px; float: left;">

						         	<div style="width: 100%; float: left; padding-left:10px;">         	
						 			   <div style="padding:10px ; font-weight: bold; width: 30%; height: 19px; line-height: 19px; float: left;">Description</div>
						               <div style="padding:10px ; font-weight: bold; width: 30%; float: left; height: 19px; line-height: 19px;">Number</div>
						               <div style=" font-weight: bold; padding:10px ; width: 30%; float: left; height: 19px; line-height: 19px;">Price</div>
						         	</div>';
						            if(!empty($orderDetails)){ 
				                        $html .= '<div style="padding:10px ;     font-weight: bold;  width: 30%; float: left; height: 21px; line-height: 21px;">';
								            $html .= $title; 
								            $html .= '</div>
								                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 21px;">1</div>
								                <div style="padding:10px ; width: 30%; float: left; height: 21px; line-height: 21px;">'.number_format($orderDetails['total_base']/100, 2,',', '.').' &euro;</div>
								            ';
									}
									if($orderDetails['vat']>0)
	         						{		
							            $html .='<div style="width: 100%; float: left; padding-left:10px;">         	
								 			   <div style="padding:10px ;     font-weight: bold; width: 30%; float: left; height: 21px; line-height: 21px;">&nbsp;</div>
								               <div style="padding:10px ;      width: 30%; float: left; height: 21px; line-height: 21px; font-weight: bold;">Vat:</div>
								               <div style="     border-top: 0;   padding:10px ; width: 30%; float: left; height: 21px; line-height: 21px;">'.number_format($orderDetails['vat']/100, 2,',', '.').' &euro;</div>
		         								</div>';
	         						}		
	         						$html .='<div style="width: 100%; float: left; padding-left:10px;">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 30%; float: left; height: 21px; line-height: 21px;">&nbsp;</div>
							               <div style="padding:10px ;    width: 30%; float: left; height: 21px; line-height: 21px; font-weight: bold;">Payment Fee:</div>
							               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 21px;">'.number_format($orderDetails['payment_fee']/100, 2,',', '.').' &euro;</div>
	         								</div>
	         								<div style="width: 100%; float: left; padding-left:10px;">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 30%; float: left; height: 21px; line-height: 21px;">&nbsp;</div>
							               <div style="padding:10px ;    width: 30%; float: left; height: 21px; line-height: 21px; font-weight: bold;">Grand Total:</div>
							               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 21px;">'.number_format($orderDetails['total_sum']/100, 2,',', '.').' &euro;</div>
	         								</div></div>

	         								<div style="width: 100%; float: left; padding-left:10px;">         	
							 			   <div style="padding:10px ;     font-weight: bold; width: 30%; float: left; height: 21px; line-height: 21px;">&nbsp;</div>
							               <div style="padding:10px ;    width: 30%; float: left; height: 21px; line-height: 21px; font-weight: bold;">&nbsp;</div>
							               <div style="     border-top: 0; padding:10px ; width: 30%; float: left; height: 21px; line-height: 21px;">&nbsp;</div>
	         								</div></div>										
						      </div>
						   </body>
						</html>';
					
			$pdfFilePath = $orderDetails['order_id_masked'].".pdf";
	        $this->load->library('m_pdf');
	        $this->m_pdf->pdf->WriteHTML($html);
	        $this->m_pdf->pdf->Output($pdfFilePath, "D");   
	        die;
		} else {
			redirect(base_url());
		}
		
	}
	public function private_picture_viewers()
	{
		$steps = getValue('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
		if(count($steps)>0)
		{
			redirect(base_url().'profile');
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$content_data['privacy_accepted_users'] = $this->common_model->getAllMultipleJoin('ugal_images_user_privacy',array('to_user_id'=>$this->session->userdata('user_id'),'alias !='=>''),array(array('feu_userdetails','feu_userdetails.user_id = ugal_images_user_privacy.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'ugal_images_user_privacy.created DESC','*, sys_files.id','from_user_id') ;

		
		//print_r($content_data['requsts']);die;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Members_access_your_private_pictures')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('private_picture_viewers', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function accept_privacy_users()
	{
		$from_id = $this->input->post('user_id');
		$type = $this->input->post('type');
		$to_id = $this->session->userdata('user_id');
		if($type==1)
		{
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>5));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>6,'created'=>time()));
			$this->common_model->UpdateData('ugal_images_user_privacy',array('privacy'=>1),array('from_user_id'=>$from_id,'to_user_id'=>$to_id));
		} else if($type==2) {
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>5));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>6,'created'=>time()));
			$this->common_model->UpdateData('ugal_images_user_privacy',array('privacy'=>0),array('from_user_id'=>$from_id,'to_user_id'=>$to_id));
		} else {
			$this->common_model->deleteData('notification',array('from_id'=>$from_id,'to_id'=>$to_id,'type'=>5));
			$this->common_model->insertData('notification',array('from_id'=>$to_id,'to_id'=>$from_id,'type'=>7,'created'=>time()));
			$this->common_model->deleteData('ugal_images_user_privacy',array('from_user_id'=>$from_id,'to_user_id'=>$to_id));
		}
		exit;
	}

	public function newCardAdd(){
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		if(checkStep()==1)
		{
			redirect('profile');
		}
		if(checkCardUpdated()==2)
		{
			redirect('profile');
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['card_infos'] = $this->common_model->getAll('usr_card_infos',array('user_id'=>$this->session->userdata('user_id')),'','id DESC') ;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,6) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		
		//print_r($content_data['orders']);die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$content_data['userDetials'] = $data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		/******************FREE MEMBERSHIP*******************/
		/*if($content_data['userDetials']['free_member']==1)
		{
			$this->session->set_userdata('upgrade',1);
			redirect('profile');
		}*/
		/******************FREE MEMBERSHIP*******************/
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('Add_new_card')." | ".$data['userDetials']['username'];
		$data['content'] = $this->load->view('new_card_add', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function newCardAddInfo(){
		
		/*********TEST*************/
		/*$CustomerId = 246934;	
		$TerminalId = 17951970;	
		$username = 'API_246934_23183450';
		$password = 'JsonApiPwd1_a8EpfvCy';*/	
		/*********TEST*************/
		//echo $orderId; die();
		/*********LIVE*************/
		$CustomerId = 403547;
		$TerminalId = 17799239;	
		$username = 'API_403547_78643204';
		$password = 'JsonApiPwdAnexus1_a8EpfvCy';	
		/*********LIVE*************/
		/***********************Create Card Alias Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "PaymentMeans": {
			    "Card": {
			      "Number": "'.$this->input->post('card_number').'",
			      "ExpYear": '.$this->input->post('exp_year').',
			      "ExpMonth": '.$this->input->post('exp_month').',
			      "HolderName": "'.$this->input->post('card_holder').'",
			      "VerificationCode": "'.$this->input->post('card_cvc').'"
			    }
			  },
			  "RegisterAlias": {
			    "IdGenerator": "RANDOM"
			  }
			}';
			//$url = 'https://test.saferpay.com/api/Payment/v1/Alias/InsertDirect';
			$url = 'https://www.saferpay.com/api/Payment/v1/Alias/InsertDirect';
		    
		    $JSONObj = json_decode($JSONObj);
		    $curl = curl_init($url);
		    curl_setopt($curl, CURLOPT_HEADER, false);
		    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		    curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
		    curl_setopt($curl, CURLOPT_POST, true);
		    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
		    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
		    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
		    $jsonResponse = curl_exec($curl);
		    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		    if ( $status != 200 ) {
		        if($status == 400) {
		    		$fail_reason = 'Validation error';
		    	} elseif($status == 401) {
		    		$fail_reason = 'Authentication of the request failed';
		    	} elseif($status == 402) {
		    		$fail_reason = 'Requested action failed';
		    	} elseif($status == 403) {
		    		$fail_reason = 'Access denied';
		    	} elseif($status == 406) {
		    		$fail_reason = 'Not acceptable (wrong accept header)';
		    	} elseif($status == 415) {
		    		$fail_reason = 'Unsupported media type (wrong content-type header)';
		    	} elseif($status == 500) {
		    		$fail_reason = 'Internal error';
		    	} else {
		    		$fail_reason = 'Authorization denied';
		    	}
		        $errorresponse = json_decode($jsonResponse, true);
		    	if($errorresponse)
		    	{
		    		if($errorresponse['ProcessorMessage'])
		    		{
		    			$fail_reason = $errorresponse['ProcessorMessage'];
		    		}
		    	}
		    	die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $aliasresponse = json_decode($jsonResponse, true);

		    //pr($aliasresponse);
		    
		if($aliasresponse)
		{
			$data_exist = $this->common_model->getAllRow('usr_card_infos',array('user_id'=>$this->session->userdata('user_id')));
			$default = 0;
			if(count($data_exist)==0){
				$default = 1;
			}

			$cc_pan = 'xxxx xxxx xxxx '.substr($this->input->post('card_number'), -4);
			$expYr = substr($this->input->post('exp_year'), -2);
			$expMth = str_pad($this->input->post('exp_month'), 2, '0', STR_PAD_LEFT);
			$saferpay_exp = $expMth.$expYr;
			$instArr = array(
							'user_id'=>$this->session->userdata('user_id'),
							'cc_pan'=>$cc_pan,
							'saferpay_exp'=>$saferpay_exp,
							'card_alias'=>$aliasresponse['Alias']['Id'],
							'is_default'=>$default,
							'created_at'=>time()
						);
			$this->common_model->insertData('usr_card_infos',$instArr);

			if($cc_pan!='' && $saferpay_exp!='' && $aliasresponse['Alias']['Id']!='' && $default == 1){
				$instArr = array(
								'cc_pan'=>$cc_pan,
								'saferpay_exp'=>$saferpay_exp,
								'card_alias'=>$aliasresponse['Alias']['Id'],
							);
				$this->common_model->UpdateData('usr_users',$instArr,array('id'=>$this->session->userdata('user_id')));
			}
			
			echo 2;
		} else {
			echo 1;
		}
		exit;
	}

	public function make_default_card($id){
		$card_info_details = $this->common_model->getAllRow('usr_card_infos',array('id'=>$id));
		if($card_info_details){
			$instArr = array(
							'is_default'=>0
						);
			$this->common_model->UpdateData('usr_card_infos',$instArr,array('user_id'=>$this->session->userdata('user_id')));

			$instArr = array(
							'is_default'=>1
						);
			$this->common_model->UpdateData('usr_card_infos',$instArr,array('id'=>$id));
			if($card_info_details['cc_pan']!='' && $card_info_details['saferpay_exp']!='' && $card_info_details['card_alias']!=''){
				$instArr = array(
								'cc_pan'=>$card_info_details['cc_pan'],
								'saferpay_exp'=>$card_info_details['saferpay_exp'],
								'card_alias'=>$card_info_details['card_alias'],
							);
				$this->common_model->UpdateData('usr_users',$instArr,array('id'=>$this->session->userdata('user_id')));
			}
			
		}
		redirect(base_url('new-card-add'));
	}
	public function block_this_user()
	{
		$user_id = $this->input->post('user_id');
		$from_id = $this->session->userdata('user_id');
		$getRecord = $this->common_model->getAllRow('usr_block',array('from_id'=>$from_id,'to_id'=>$user_id));
		$insert = 0;
		if(empty($getRecord))
		{
			$insert = $this->common_model->insertData('usr_block',array('from_id'=>$from_id,'to_id'=>$user_id,'created'=>time()));
		}
		echo $insert; exit;
	}
	public function unblock_this_user($to_id)
	{
		$to_id = base64_decode($to_id);
		$from_id = $this->session->userdata('user_id');
		$getRecord = $this->common_model->getAllRow('usr_block',array('from_id'=>$from_id,'to_id'=>$to_id));
		if(!empty($getRecord))
		{
			$delete = $this->common_model->deleteData('usr_block',array('from_id'=>$from_id,'to_id'=>$to_id));
		}
		redirect('blocked-user-list');
	}
	public function blocked_user_list()
	{
		$steps = getValue('feu_user_steps',array('user_id'=>$this->session->userdata('user_id')));
		if(count($steps)>0)
		{
			redirect(base_url().'profile');
		}
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$content_data['blocked_user_list'] = $this->common_model->getAllMultipleJoin('usr_block',array('from_id'=>$this->session->userdata('user_id')),array(array('feu_userdetails','feu_userdetails.user_id = usr_block.to_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'usr_block.created DESC') ;

		
		//print_r($content_data['requsts']);die;
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		if(empty($data['upcomingEvents']))
		{
			$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from ASC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		}
		if(empty($data['lastEvents']))
		{
			$data['lastEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from < '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1,'lang_id'=>$langId),array(array('evt_event_files','evt_event_files.event_id = evt_events.id'),array('evt_language_values','evt_events.id = evt_language_values.event_id')),'time_from DESC','evt_events.*,evt_event_files.*,evt_language_values.title as title','id',0,4) ;
		}
		$data['checkinEvents'] = $this->common_model->getAllMultipleJoin('shop_orders',array('shop_orders.payed'=>1,'shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.checkin_payed'=>NULL,'evt_language_values.lang_id'=>$langId),array(array('shop_carts','shop_carts.id = shop_orders.cart_id'),array('shop_booking_details','shop_booking_details.cart_id = shop_carts.id'),array('evt_language_values','evt_language_values.event_id = shop_booking_details.event_id'),array('evt_events','evt_language_values.event_id = evt_events.id')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_events.alias','shop_booking_details.cart_id') ;
		$data['unfinishedPayment'] = $this->common_model->getAllMultipleJoin('shop_booking_details',array('is_booking'=>1,'payed'=>0,'shop_carts.user_id'=>$this->session->userdata('user_id')),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created','','shop_booking_details.cart_id');
		//echo $this->db->last_query();die;
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id')),array(array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'))) ;
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>$langId),array(array('sys_files','sys_files.id = cms_page.image_id')),'cms_page.id ASC','*','');
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['title'] = getLang('blocked_user_list');
		$data['content'] = $this->load->view('blocked_user_list', $content_data, TRUE);
		$this->load->view('template', $data);
	}

	public function put_new_email()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$new_email = $this->utility->info_cleanQuery($this->input->post('new_email'));
		$existEmail = $this->common_model->getAllRow('usr_users',array('email'=>$new_email));
		$userDetials = $this->common_model->getAllRow('usr_users',array('user_id'=>$this->session->userdata('user_id')),array('feu_userdetails', 'feu_userdetails.user_id = usr_users.id'));
		//print_r($userDetials); die;
		if(!empty($existEmail))
		{
			echo 1;exit;
		}
		else
		{
			$con = array(
					'new_email'=>$new_email,
					'new_email_confirmed'=>0
				);
			$this->common_model->UpdateData('usr_users',$con, array('id'=>$this->session->userdata('user_id')));
			$to = $new_email;
			$sub = 'Confirm your new email at Castleevents';
			$body=' <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>'.getLang('Hello').' <span style="text-transform:capitalize">'.$userDetials['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   <p>
	                                      '.getLang('Thank_you_for_your_registration').'.
	                                   </p>
	                                   <br>
	                                   <p>'.getLang('Your_confirmation_URL').': <a href="'.base_url().'profile/validate_new_email/'.base64_encode($userDetials['user_id']).'" style="color:#b3975b">'.getLang('Click_here_to_verify').'</a></p>
	                                   <p>'.base_url().'profile/validate_new_email/'.base64_encode($userDetials['user_id']).'</p>
	                                </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;">
	                             		'.getLang('Best_regards').' <br>
	                             		<p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';

			//$this->utility->sendCIMail($to,$sub,$body);
			$this->utility->sendMandrillCIMail($to,$sub,$body);
			echo 3;exit;
		}
	}
	public function validate_new_email($encId = '')
	{
		$userId= base64_decode($encId);
		$userData = $this->common_model->getAllRow('usr_users',array('user_id'=>$userId),array('feu_userdetails', 'feu_userdetails.user_id = usr_users.id'));
		if($userData['new_email_confirmed']==0){
			$this->common_model->UpdateData('usr_users',array('new_email_confirmed'=>1, 'email'=>$userData['new_email'], 'old_email'=>$userData['email']),array('id'=>$userId));
			$this->common_model->UpdateData('shop_orders',array('invoiceAddress'=>$userData['new_email']),array('invoiceAddress'=>$userData['email']));
			/*if(!empty($userData))
			{
				$this->session->set_userdata('success_pop',$userData['username']);
			}*/
			$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
			$listId = "4b705bab4e";
			if($userData['userlanguage']==1){
				$listId = "4b705bab4e";
			} elseif($userData['userlanguage']==2){
				$listId = "a8efb2baef";
			} else{
				$listId = "8be54dca74";
			}
			/***********subscribe new email**************/
			try{
				$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower($userData['new_email']));
				$operation = array(
			            'email_address'=>$userData['new_email'],
			            'status'=>'subscribed'
			            );//print_r($operation);die;
				$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);
				//var_dump($result);
			} catch(Exception $e){
				//var_dump($e);
			}
			
			/***********subscribe new email**************/

			/***********subscribe old email**************/
			try{
				$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower($userData['email']));
				$operation = array(
			            'email_address'=>$userData['email'],
			            'status'=>'unsubscribed'
			            );
				$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); 
				$result1 = curl_exec($curl);
				//var_dump($result1);
			} catch(Exception $e){
				//var_dump($e);
			}
			/***********subscribe old email**************/
		}
		redirect('setting');
	}

	public function put_alter_email()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$alter_email = $this->utility->info_cleanQuery($this->input->post('alter_email'));
		$existEmail = $this->common_model->getAllRow('usr_users',array('email'=>$alter_email));
		$existAlterEmail = $this->common_model->getAllRow('usr_alter_email',array('user_id'=>$this->session->userdata('user_id')));
		$userDetials = $this->common_model->getAllRow('usr_users',array('user_id'=>$this->session->userdata('user_id')),array('feu_userdetails', 'feu_userdetails.user_id = usr_users.id'));
		if(!empty($existEmail) || !empty($existAlterEmail))
		{
			echo 1;exit;
		}
		else
		{
			$this->common_model->deleteData('usr_alter_email', array('user_id'=>$this->session->userdata('user_id')));
			$con = array(
					'user_id' => $this->session->userdata('user_id'),
					'alter_email'=>$alter_email,
					'confirmed'=>0,
					'created_at' => time()
				);
			$this->common_model->insertData('usr_alter_email',$con);
			$to = $alter_email;
			$sub = 'Confirm your alternative email at Castleevents';
			$body=' <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>'.getLang('Hello').' <span style="text-transform:capitalize">'.$userDetials['username'].'</span> </h2>
	                                </td>
	                             </tr>
	                             <tr>
	                                <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
	                                   <p>
	                                      '.getLang('Thank_you_for_your_registration').'.
	                                   </p>
	                                   <br>
	                                   <p>'.getLang('Your_confirmation_URL').': <a href="'.base_url().'profile/validate_alter_email/'.base64_encode($userDetials['user_id']).'" style="color:#b3975b">'.getLang('Click_here_to_verify').'</a></p>
	                                   <p>'.base_url().'profile/validate_alter_email/'.base64_encode($userDetials['user_id']).'</p>
	                                </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;">
	                             		'.getLang('Best_regards').' <br>
	                             		<p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
	                             	</td>
	                             </tr>
	                          </table>
	                       </td>
	                    </tr>
	                </table>';

			//$this->utility->sendCIMail($to,$sub,$body);
			$this->utility->sendMandrillCIMail($to,$sub,$body);
			echo 3;exit;
		}
	}
	public function validate_alter_email($encId = '')
	{
		$userId= base64_decode($encId);
		$userData = $this->common_model->getAllRow('usr_users',array('user_id'=>$userId),array('feu_userdetails', 'feu_userdetails.user_id = usr_users.id'));
		$useralterData = $this->common_model->getAllRow('usr_alter_email',array('user_id'=>$userId));
		
		$this->common_model->UpdateData('usr_alter_email',array('confirmed'=>1),array('user_id'=>$userId));
		/*if(!empty($userData))
		{
			$this->session->set_userdata('success_pop',$userData['username']);
		}*/
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$listId = "4b705bab4e";
		if($userData['userlanguage']==1){
			$listId = "4b705bab4e";
		} elseif($userData['userlanguage']==2){
			$listId = "a8efb2baef";
		} else{
			$listId = "8be54dca74";
		}
		/***********subscribe new email**************/
		try{
			$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower($useralterData['alter_email']));
			$operation = array(
		            'email_address'=>$useralterData['alter_email'],
		            'status'=>'subscribed'
		            );//print_r($operation);die;
			$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);
			//var_dump($result);
		} catch(Exception $e){
			//var_dump($e);
		}
		
		/***********subscribe new email**************/
		
		redirect('setting');
	}

	public function put_new_username()
	{
		$langId = 2;
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		$new_username = $this->utility->info_cleanQuery($this->input->post('new_username'));
		$existUsername = $this->common_model->getAllRow('feu_userdetails',array('username'=>$new_username, 'user_id !='=>$this->session->userdata('user_id')));
		if(!empty($existUsername))
		{
			echo 1;exit;
		}
		else
		{
			$con = array(
					'username'=>$new_username
				);
			$this->common_model->UpdateData('feu_userdetails',$con, array('user_id'=>$this->session->userdata('user_id')));
			echo 2;exit;
		}
	}
}
