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

class Checkin 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(base_url());
		}
		$this->load->library('Mobile_detect');
		if(checkStep()==1)
		{
			redirect('profile');
		}
		if(checkCardUpdated()==2)
		{
			redirect('profile');
		}
		if($this->session->userdata('user_id')){
			//if($this->session->userdata('user_id')==25267){
				if(getOpenBookingInvoices() > 0)
				{
					$this->session->set_userdata('pay_book_first',1);
					redirect('invoice');
				}
			//}
		}
	}
	public function details($slug='',$enc_cartId='')
	{
		$langId = 2;
		$orderDetail = array();
		if(get_cookie('lang'))
		{
			$langId = get_cookie('lang');
		}
		if($enc_cartId=='')
		{
			redirect(base_url());
		}
		else
		{
			$cartId = base64_decode($enc_cartId);
			$where = 'cart_id = '.$cartId.' AND (checkin_payed IS NULL OR checkin_payed=0) AND payed = 1';
			$orderDetail = $this->common_model->getAllRow('shop_orders',$where);
			
			//echo $this->db->last_query(); die;
			if(empty($orderDetail))
			{
				redirect(base_url());
			}
		}
		$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$this->session->userdata('user_id'))) ;
		$content_data['userMembershipDetails'] = $this->users_model->getMembershipDetails($this->session->userdata('user_id'));
		//$content_data['userMembershipDetails'] = $this->common_model->getAllRowMultipleJoin('shop_orders',array('shop_carts.user_id'=>$this->session->userdata('user_id'),'shop_orders.payed'=>1,'shop_orders.is_booking'=>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('shop_articles','shop_articles.id = shop_articles_carts.article_id')),'shop_orders.created','shop_articles.id');
		//print_r($content_data['userMembershipDetails']); die;
		$content_data['steps'] = $this->common_model->getAllRow('feu_user_steps',array('user_id'=>$this->session->userdata('user_id'))) ;
		$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') ;
		$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) ;
		}
		$content_data['partyDetails'] = $this->common_model->getAllRowMultipleJoin('evt_events',array('evt_event_files.is_banner'=>1,'evt_language_values.lang_id'=>$langId,'evt_events.alias'=>$slug,'evt_language_values.lang_id'=>$langId),array(array('evt_language_values','evt_language_values.event_id = evt_events.id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_id'),array('loc_locations','loc_events_locations.location_id = loc_locations.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_events.created DESC','evt_events.id as id, evt_events.*,sys_files.path,sys_files.filename,sys_files.extension,loc_locations.name,loc_locations.country,loc_locations.city,loc_locations.zipcode,evt_event_files.is_banner,evt_language_values.title,evt_language_values.description,evt_language_values.teasertext, evt_language_values.add_checkin_title, evt_language_values.add_checkin_info','loc_events_locations.event_id, evt_language_values.title, evt_language_values.description');
		//echo $this->db->last_query(); die;
		//print_r($content_data['partyDetails']); die;
		if(empty($content_data['partyDetails']))
		{
			redirect(base_url());
		}
		$data['checkinEvents'] = array();
		if($this->session->userdata('user_id'))
		{
			$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['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['userData'] = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_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');
		}
		$content_data['partyPrice'] = $this->common_model->getAllRowMultipleJoin('evt_events',array('evt_events.alias'=>$slug,'event_features.type'=>1),array(array('event_features','event_features.event_id = evt_events.id')),'event_features.base_price ASC');
		$content_data['entries'] = $this->common_model->getAllMultipleJoin('evt_events',array('evt_events.alias'=>$slug,'event_features.type'=>1,'event_features_lang_values.lang_id'=>$langId),array(array('event_features','event_features.event_id = evt_events.id'),array('event_features_lang_values','event_features_lang_values.event_feature_id = event_features.id'),array('sys_files','sys_files.id = event_features.image_id')),'event_features.base_price ASC','event_features_lang_values.*,sys_files.*,event_features.*');
		$data['languages'] = $this->common_model->getAll('sys_languages',array('visible'=>1)) ;
		$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'] = "Castleevents | ".getLang('Party_Checkin');

		$content_data['site_address_name'] = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_name'));
		$content_data['site_address_city'] = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_city'));
		$content_data['site_address_country_zip'] = $this->common_model->getAllRow('site_settings',array('code'=>'site_address_country_zip'));
		$content_data['orderDetail'] = $orderDetail;
		if(!empty($content_data['partyDetails']))
		{
			$data['meta_title'] = $content_data['partyDetails']['title'];
			$data['meta_description'] = strip_tags(html_entity_decode($content_data['partyDetails']['description']));
		}
		$data['content'] = $this->load->view('checkin', $content_data, TRUE);
		$this->load->view('template', $data);
	}
	public function pay()
	{
		$userData = $this->common_model->getAllRow('feu_userdetails',array('user_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*************/
		
		if($this->input->post('price'))
		{
			$userDetail = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));
			$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$this->input->post('cartId')));

		/***********************Create Transaction Direct********************/
			$JSONObj  = '{
			  "RequestHeader": {
			    "SpecVersion": "1.10",
			    "CustomerId": "'.$CustomerId.'",
			    "RequestId": "aScdFewDSRFrfas2wsad3",
			    "RetryIndicator": 0
			  },
			  "TerminalId": "'.$TerminalId.'",
			  "Payment": {
			    "Amount": {
			      "Value": "'.(int)($this->input->post('price')*100).'",
			      "CurrencyCode": "EUR"
			    },
			    "Description": "Party Checkin",
			    "PayerNote": "Party Checkin"
			  },
			  "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'];
		    		}
		    	}
		        die("Error: ".$fail_reason);
		    }
		    curl_close($curl);
		    $transactionresponse = json_decode($jsonResponse, true);
		    
		  	//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'];
		    		}
		    	}
		        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('checkin_payed'=>1,'checkin_amount'=>$this->input->post('price')),array('cart_id'=>$this->input->post('cartId')));
					$this->common_model->UpdateData('shop_orders',array('checkin_payment_method_id'=>1),array('cart_id'=>$this->input->post('cartId')));
					$arr = array(
								'event_id'=>$this->input->post('event_id'),
								'username'=>$userData['username'],
								'drinking_package'=>$this->input->post('package_id'),
								'cape'=>$this->input->post('cape_no'),
								'ceremonial'=>$this->input->post('seduction'),
								'additional'=>$this->input->post('additional'),
								//'ceremonial'=>$this->input->post('ceremony').'#'.$this->input->post('seduction'),
								'summury'=>$this->input->post('price'),
								'payment'=>1,
								'confirmed'=>date('Y-m-d'),
								'drink_price'=>$this->input->post('package_price'),
								'cape_price'=>$this->input->post('cape_price'),
								'trasaction_id'=>$transactionresponse['Transaction']['Id'],
								'order_id'=>$orderDetail['order_id'],
								'extra_wish'=>$this->utility->info_cleanQuery($this->input->post('extra_wish')),
							);
					$this->common_model->insertData('event_guest',$arr);

					$to = $userDetail['email'];
					$sub = getLang('Confirmation').': '.getLang('Successful_Check_in');
					//$body= '<p>Dear '.$userData['username'].',</p>';
					$body= '<p>'.getLang('We_have_received_your_check_in').'!</p>';
					$body.= '<p>'.getLang('Partydetails_will_be_located').' at 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****/
					$event_details_data = $this->common_model->getAllRow('evt_events', array('id'=>$this->input->post('event_id')));
					$evet_title = '';
					if($event_details_data){
						$evet_title = $event_details_data['title'];
					}
					$to = 'alorenc@me.com';
					$sub = 'Payment recieved';
					$body= 'CE-'.$orderDetail['order_id'].', EUR '.number_format($this->input->post('price'), 2,',', '.');
					$body.= '<p>Paid Party Checkin Fees for '.$evet_title.'</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
			{
				echo 'Card authorization denied';
			}
		}
		exit;
	}
	public function payPremuium()
	{
		$userData = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$this->session->userdata('user_id')));
		$userDetail = $this->common_model->getAllRow('usr_users',array('id'=>$this->session->userdata('user_id')));
		$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$this->input->post('cartId')));
		$this->common_model->UpdateData('shop_orders',array('checkin_payment_method_id'=>3),array('cart_id'=>$this->input->post('cartId')));
		$this->common_model->UpdateData('shop_orders',array('checkin_payed'=>1,'checkin_amount'=>$this->input->post('price')),array('cart_id'=>$this->input->post('cartId')));
		$drink_price = 0;
		if($this->input->post('userMembership')==5)
		{
			$drink_price = $this->input->post('package_price');
		}				
		$arr = array(
					'event_id'=>$this->input->post('event_id'),
					'username'=>$userData['username'],
					'drinking_package'=>$this->input->post('package_id'),
					'cape'=>$this->input->post('cape_no'),
					'ceremonial'=>$this->input->post('seduction'),
					'additional'=>$this->input->post('additional'),
					//'ceremonial'=>$this->input->post('ceremony').'#'.$this->input->post('seduction'),
					'summury'=>$this->input->post('price'),
					'payment'=>1,
					'confirmed'=>date('Y-m-d'),
					'drink_price'=>$drink_price,
					'cape_price'=>$this->input->post('cape_price'),
					'trasaction_id'=>0,
					'order_id'=>$orderDetail['order_id'],
					'extra_wish'=>$this->utility->info_cleanQuery($this->input->post('extra_wish')),
				);
		$this->common_model->insertData('event_guest',$arr);

		$to = $userDetail['email'];
		$sub = getLang('Confirmation').': '.getLang('Successful_Check_in');
		//$body= '<p>Dear '.$userData['username'].',</p>';
		$body= '<p>'.getLang('We_have_received_your_check_in').'!</p>';
		$body.= '<p>'.getLang('Partydetails_will_be_located').' at castleevents.com.</p>';
		$body.= '<p>'.getLang('We_appreciate_very_much').'.</p>';
		$body.= '<p>'.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" 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);

		//$this->utility->sendMail($to,$sub,$body);
		echo 2;exit;
	}
	public function updatehotornot()
	{
		$user_id = $this->input->post('id');
		$file_id = $this->input->post('file_id');
		$status = $this->input->post('status');
		$from_id = $this->session->userdata('user_id');
		if($status==1)
		{
			$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'=>'picture:'.$file_id,
								'user_id'=>$from_id,
							);
				$inst = $this->common_model->insertData('like_likes',$inst_arr);
			}
			$inst_arr = array(
								'liked_user'=>$user_id,
								'user_id'=>$from_id,
								'created'=>time(),
								'status'=>1,
								'file_id'=>$file_id
							);
			$inst = $this->common_model->insertData('not_liked_users',$inst_arr);
			$this->common_model->insertData('notification',array('from_id'=>$from_id,'to_id'=>$user_id,'file_id'=>$file_id,'type'=>9,'created'=>time()));
		}
		if($status==2)
		{
			$inst_arr = array(
								'liked_user'=>$user_id,
								'user_id'=>$from_id,
								'created'=>time(),
								'status'=>2,
								'file_id'=>$file_id
							);
			$inst = $this->common_model->insertData('not_liked_users',$inst_arr);
		}
		$loggedInUserMembershipDetails = $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') ;
		$totalLikedData = $this->common_model->getAll('not_liked_users',array('user_id'=>$from_id));
		$html = '';
		if(count($totalLikedData)>10 && $loggedInUserMembershipDetails['id']==5 && count($userImages)<3)
		{
			$html .= '<div class="imgbox"><p>'.getLang('Please_upload_minimum').' 3 '.getLang('Pictures').' '.getLang('Or').' <a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></p></div>';
		}
		elseif(count($totalLikedData)>500 && $loggedInUserMembershipDetails['id']==5 && count($userImages)<4)
		{
			$html .= '<div class="imgbox"><p>'.getLang('Please_upload_minimum').' 4 '.getLang('Pictures').' '.getLang('Or').' <a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></p></div>';
		}
		elseif(count($totalLikedData)>1000 && $loggedInUserMembershipDetails['id']==5 && count($userImages)<5)
		{
			$html .= '<div class="imgbox"><p>'.getLang('Please_upload_minimum').' 5 '.getLang('Pictures').' '.getLang('Or').' <a class="upgardeButt" style="text-decoration: underline;" href="'.base_url().'profile/before_settings">'.getLang('upgrade').'</a></p></div>';
		}
		else
		{
			$content_data['userDetials'] = $this->common_model->getAllRowMultipleJoin('feu_userdetails',array('feu_userdetails.user_id'=>$this->session->userdata('user_id'))) ;
			$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')),'RAND()','*, sys_files.id as file_id','',0,1);
			//echo $this->db->last_query();die;
			$this->common_model->insertData('notification',array('from_id'=>$this->session->userdata('user_id'),'to_id'=>$hotnot['user_id'],'type'=>10,'created'=>time()));
			$visitEntry = $this->common_model->getAllRow('feu_profilevisits',array('from_user_id'=>$this->session->userdata('user_id'),'to_user_id'=>$hotnot['user_id']));
			if(empty($visitEntry)){
				$this->common_model->insertData('feu_profilevisits',array('from_user_id'=>$this->session->userdata('user_id'),'to_user_id'=>$hotnot['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'=>$hotnot['user_id']));
			}
			if (count($hotnot)>0) { 
				$html.='<div class="imgbox">
				<img src="';
				if(!empty($hotnot) && $hotnot['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$hotnot['path'].'/'.$hotnot['filename'].'.'.$hotnot['extension']))
				{ 
					$html.= base_url().'assets/userfiles/'.$hotnot['path'].'/'.$hotnot['filename'].'.'.$hotnot['extension']; 
				} 
				else 
				{ 
					$html.= base_url().'assets/images/default-avatar.jpg'; 
				}
				$html.='" alt="">
				</div>
				<div class="hotnotFooter">
				  <button class="btn_grey hotmember" data-file="'.$hotnot['file_id'].'" data-status="1" data-id="'.$hotnot['user_id'].'">'.getLang('Hot').' <img src="'.base_url() . 'assets/images/hotspot-icon.png'.'" alt=""></button>
				  <button class="btn_grey notmember" data-file="'.$hotnot['file_id'].'" data-status="2" data-id="'.$hotnot['user_id'].'">'.getLang('Hot').'</button>
				</div>';
			} 
			else
			{
				$html.='<div class="imgbox">'.getLang('Contest_has_been_completed').'</div>';
			}
		}
		echo $html; exit;
	}
	public function updatePaymentMethod()
	{
		$cart_id = $this->input->post('cartId');
		$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$this->input->post('cartId')));
		$userDetail = $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')));

		$this->common_model->UpdateData('shop_orders',array('checkin_payment_method_id'=>2),array('cart_id'=>$cart_id));
		$this->common_model->UpdateData('shop_orders',array('checkin_payed'=>0,'checkin_amount'=>$this->input->post('price')),array('cart_id'=>$this->input->post('cartId')));
		$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$this->input->post('cartId')));			
		$arr = array(
					'event_id'=>$this->input->post('event_id'),
					'username'=>$userData['username'],
					'drinking_package'=>$this->input->post('package_id'),
					'cape'=>$this->input->post('cape_no'),
					'ceremonial'=>$this->input->post('seduction'),
					'additional'=>$this->input->post('additional'),
					//'ceremonial'=>$this->input->post('ceremony').'#'.$this->input->post('seduction'),
					'summury'=>$this->input->post('price'),
					'payment'=>1,
					'confirmed'=>date('Y-m-d'),
					'drink_price'=>$this->input->post('package_price'),
					'cape_price'=>$this->input->post('cape_price'),
					'trasaction_id'=>0,
					'order_id'=>$orderDetail['order_id'],
					'extra_wish'=>$this->utility->info_cleanQuery($this->input->post('extra_wish')),
				);
		$this->common_model->insertData('event_guest',$arr);
		$to = $userDetail['email'];
		$sub = getLang('Confirmation').': '.getLang('Successful_Check_in');
		/********************New mail***************************/
		
        $total = number_format($orderDetail['checkin_amount'],2,',','.');

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

        $body= '<p>'.getLang('We_have_received_your_check_in').'!</p>';
        if(!empty($orderDetail))
		{
			$body.= '<p>'.getLang('Partydetails_will_be_located').' at castleevents.com.</p>';
			$body.='<p>'.getLang('Please_transfer_the_full_amount_of').' <span class="total">EUR '.$total.'</span> </p><br><p><strong>'.getLang('Outstanding_Amount').': </strong><span class="total">'.$total.' EUR</span></p>';
            $body.=' <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> Checkin '.$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> ';
        }
        $body.= '<p>'.getLang('We_appreciate_very_much').'.</p><br/>';
		$body.= '<p>'.getLang('Please_do_not_hesitate_to_contact').'.</p><br/><br/>';
		//$body.= '<p>Best regards,</p><p>Your Castleevents Team </p>';

		//pr($body);
		$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>';
	    //echo $bodys;die;           

		$this->utility->sendOrderMail($to,$sub,$bodys);
		echo 2;exit;
	}

	function downloadInvoicePDF($cart_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'));
		/********************New mail***************************/
		$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$cart_id));
		$userDetail = $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')));

		$orderDetail = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$cart_id));			
		
		if($userDetail['email'] == $orderDetail['invoiceAddress']){

	        $total = number_format($orderDetail['checkin_amount'],2,',','.');

	        $body='<!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: 15px 0 20px; ">
							          
							         </div>
						      <br>';
	        $body.= '<p>'.getLang('We_have_received_your_check_in').'!</p>';
	        if(!empty($orderDetail))
			{
				$body.= '<p>'.getLang('Partydetails_will_be_located').' at castleevents.com.</p>';
				$body.='<p>'.getLang('Please_transfer_the_full_amount_of').' <span class="total">EUR '.$total.'</span> </p><br><p><strong>'.getLang('Outstanding_Amount').': </strong><span class="total">'.$total.' EUR</span></p>';
	            $body.=' <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> Checkin '.$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> ';
	        }

			$body.='</div>
						   </body>
						</html>';

			//echo $body;die;
			//print_r($orderDetails);
			$pdfFilePath = "Checkin-".$orderDetail['order_id_masked'].".pdf";
	        $this->load->library('m_pdf');

	        $this->m_pdf->pdf->useOnlyCoreFonts = true;    // false is default
			$this->m_pdf->pdf->SetTitle("Castleevents Title");
			$this->m_pdf->pdf->SetAuthor("Author");
			$this->m_pdf->pdf->SetDisplayMode('fullpage'); 
			$this->m_pdf->pdf->WriteHTML($body);
			$this->m_pdf->pdf->Output($pdfFilePath, "D");    
	        die;
			/********************New mail***************************/
		}
	}
}
