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

class Test_1 extends CI_Controller {
	public function __construct()
	{echo date('d-m-Y H:i:s'); die;
		parent::__construct();
		$this->load->model('common_model');
		/*if($this->session->userdata('user_id'))
		{
			redirect('profile');
		}*/
		$this->load->library('Mobile_detect');
		//$this->load->library('Excel');
	}
	/*public function index()
	{
		echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
die;
		$langId = 2;
		
		$content_data['latestUsers'] = $this->common_model->getAll('feu_userdetails',array('avatar_file_id >'=>0,'id >'=>1,'filename !='=>''),array('sys_files','feu_userdetails.avatar_file_id = sys_files.id'),'feu_userdetails.created DESC','','',0,5);
		$content_data['mediaLogos'] = $this->common_model->getAll('blog_articles',array('blog_articles.visible'=>1),array('sys_files','blog_articles.logo_id = sys_files.id'),'blog_articles.sort ASC','','',0,5) ;
		$content_data['mediaPreview'] = $this->common_model->getAll('blog_articles',array('blog_articles.visible'=>1),array('sys_files','blog_articles.image_id = sys_files.id'),'blog_articles.sort ASC','','',0,5) ;
		$data['nextParty'] = $this->common_model->getAllRowMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1),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_events.title as title','id') ;
		//echo date('M d,Y',$data['nextParty']['time_from']); die;
		$content_data['nextParty'] = $data['nextParty'];
		$data['upcomingEvents'] = $this->common_model->getAllMultipleJoin('evt_events',array('time_from > '=>time(),'sorting'=>1,'is_banner'=>1,'visible'=>1),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_events.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),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_events.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),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_events.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),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_events.title as title','id',0,4) ;
		}
		//echo $this->db->last_query();die;
		//print_r($data['lastEvents']); die;
		$data['checkinEvents'] = array();
		if($this->session->userdata('user_id'))
		{
			$content_data['loginDetails'] = $this->common_model->getAll('usr_users',array('id'=>$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'=>2),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')),'','shop_orders.created,shop_orders.cart_id,evt_language_values.title,evt_language_values.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'))) ;
			$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') ;
		$data['title'] = "Start - CASTLEEVENTS.COM - The World's Leading Eyes Wide Shut Parties and Erotic Social Network";
		$data['cms_pages_1'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>1,'language_id'=>2),array(array('sys_files','sys_files.id = cms_page.thumb_id')),'cms_page.id ASC','*','');
		$data['cms_pages_2'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>2,'language_id'=>2),array(array('sys_files','sys_files.id = cms_page.thumb_id')),'cms_page.id ASC','*','');
		$data['cms_pages_3'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>3,'language_id'=>2),array(array('sys_files','sys_files.id = cms_page.thumb_id')),'cms_page.id ASC','*','');
		$data['cms_pages_4'] = $this->common_model->getAllMultipleJoin('cms_page',array('section_id'=>4,'language_id'=>2),array(array('sys_files','sys_files.id = cms_page.thumb_id')),'cms_page.id ASC','*','');
		//print_r($data['cms_pages_1']);die;
		$data['device'] = ($this->mobile_detect->isMobile() ? ($this->mobile_detect->isTablet() ? 'tablet' : 'phone') : 'computer');
		$data['content'] = $this->load->view('index_test', $content_data, TRUE);
		$this->load->view('template', $data);
	}*/
	function export(){
		echo date('Y-m-d H:i:s');die;
		//$qry = $this->db->query('select * from usr_users where cc_ref_id !=""');
        //$getUserListData = $qry->result_array();
        $qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `usr_users`.`cc_pan`, `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 GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 365 then b.created <('.(time()+(30*86400)).' - (365 * 86400)) when time = 182 then b.created <('.(time()+(30*86400)).' - (182 * 86400)) end AND article_id in (5,4) order by b.created DESC limit 0,23');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'User ID';
			$csv_fields[] = 'Email';
			$csv_fields[] = 'CC Ref ID';
			$csv_fields[] = 'CC PAN No.';
			$csv_fields[] = 'Register Date';

			$output_filename = 'last 10 day users.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['User ID']=$Result['user_id'];
				$leadArray['Email']=$Result['email'];
				$leadArray['CC Ref ID']=$Result['cc_ref_id'];
				$leadArray['CC PAN No.']=$Result['cc_pan'];
				$leadArray['Register Date']=date('d.M.Y',$Result['created']);
				// Add row to file
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
	}
	function no_export(){
		$qry = $this->db->query('select * from (select * from (SELECT shop_orders.created,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE `shop_orders`.`payment_method_id` = 13 AND `shop_articles`.`reoccuring` IS NOT NULL AND `shop_articles`.`reoccuring` >0 AND ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where b.cc_ref_id is NULL order by b.user_id');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Email';
			$csv_fields[] = 'CC Ref ID';
			$csv_fields[] = 'CC PAN No.';

			$output_filename = 'no_cc_ref_id.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Email']=$Result['email'];
				$leadArray['CC Ref ID']=$Result['cc_ref_id'];
				$leadArray['CC PAN No.']=$Result['cc_pan'];
				// Add row to file
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
	}
	
	function get()
	{
		$arr=array();
		$qry = $this->db->query('select * from shop_carts join shop_orders on shop_carts.id = shop_orders.cart_id');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			foreach($getUserListData as $row)
			{
				if(date('d-m-Y',$row['created'])>'01-07-2016' && date('d-m-Y',$row['created'])>'31-07-2016')
				{
					array_push($arr,$row['cart_id']);
				}
			}
		}
		print_r($arr);
	}

	function englishUsers(){
		$qry = $this->db->query('select feu_userdetails.username,usr_users.email from feu_userdetails join usr_users on usr_users.id = feu_userdetails.user_id where userlanguage  = 2');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Language';

			$output_filename = 'EnglishSpeakingUsers.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Email']=$Result['email'];
				$leadArray['Username']=$Result['username'];
				$leadArray['Language']='EN';
				// Add row to file
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}die;
	}

	function spanishUsers(){
		$qry = $this->db->query('select feu_userdetails.username,usr_users.email from feu_userdetails join usr_users on usr_users.id = feu_userdetails.user_id where userlanguage  = 3');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Language';

			$output_filename = 'SpanishSpeakingUsers.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Email']=$Result['email'];
				$leadArray['Username']=$Result['username'];
				$leadArray['Language']='ES';
				// Add row to file
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}die;
	}

	function germanUsers(){
		$qry = $this->db->query('select feu_userdetails.username,usr_users.email from feu_userdetails join usr_users on usr_users.id = feu_userdetails.user_id where userlanguage = 1');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Language';

			$output_filename = 'GermanSpeakingUsers.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Email']=$Result['email'];
				$leadArray['Username']=$Result['username'];
				$leadArray['Language']='DE';
				// Add row to file
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}die;
	}
	function chargeExport(){
		$qry = $this->db->query('select * from charge_card');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'CC PAN No.';
			$csv_fields[] = 'CC Ref ID';
			$csv_fields[] = 'Date & Time';
			$csv_fields[] = 'Amount';
			$csv_fields[] = 'Payment Sattus';
			$csv_fields[] = 'Error Response Saferpay';

			$output_filename = 'charge.xls';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/xls' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['CC PAN No.']=$Result['card'];
				$leadArray['CC Ref ID']=$Result['cc_ref_id'];
				$leadArray['Date & Time']=$Result['date'];
				$leadArray['Amount']=$Result['amount'];
				$leadArray['Payment Sattus']=$Result['payment_status'];
				$leadArray['Error Response Saferpay']=$Result['error'];
				
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
	}
	function current_cron()
	{
		$qry = $this->db->query('select * from (select * from (SELECT shop_orders.created,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE `shop_articles`.`reoccuring` IS NOT NULL AND `shop_articles`.`reoccuring` >0 AND ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where b.created <('.time().' - (365 * 86400)) order by b.created DESC limit 0,10');
		
        $getUserListData = $qry->result();
		echo '<pre>';
		print_r($getUserListData); die;
	}
	function new_cron()
	{
		$qry = $this->db->query('select * from (select * from (SELECT shop_orders.time,shop_articles_carts.article_id,shop_orders.created,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus` FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) AND `shop_orders`.`payed` = 1 ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 365 then b.created <('.time().' - (365 * 86400)) when time = 182 then b.created <('.time().' - (182 * 86400)) end AND article_id in (5,4) order by b.created DESC limit 0,10');
        $getUserListData = $qry->result();
        echo '<pre>';
		print_r($getUserListData); die;
	}
	function mail($alias)
	{
		$this->load->model('common_model');
		$user = $this->common_model->getAllRow('feu_userdetails',array('alias'=>$alias));
		
		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****************/
			$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)
			{
						

				$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;	
				//echo $to = $visitedData['email'];
				//$to = $visitedData['email'];
				$sub = 'New visitor: '.$visitorData['username'];
				if($visitorData['filename']!='' && file_exists(FCPATH.'assets/userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension']))     
                {
                	$image = base_url().'assets/userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension'];
					$image_name = 'userfiles/'.$visitorData['path'].'/80/'.$visitorData['filename'].'.'.$visitorData['extension'];
					$name1 = $visitorData['filename'].'.'.$visitorData['extension'];
                }
                else
                {
                	$image =  base_url().'assets/images/default-avatar.jpg';
					$image_name = 'images/default-avatar.jpg';
					$name1 = 'default-avatar.jpg';
                }
				
						$from='noreply@castleevents.com';
						//$email_config=array('newline'   => "\r\n");
						$email_config = Array(
							'protocol'  => 'smtp',
							'mailtype'  => 'html',
							'charset' => 'iso-8859-1',
							'crlf'   => "\r\n",
							'newline'   => "\r\n",
							'wordwrap' => TRUE
						);
						$email_config['smtp_host'] = 'smtp.mandrillapp.com';
						$email_config['smtp_user'] = 'castleevents';
						$email_config['smtp_pass'] = 'UL-_zRNcxPNZq-smuWkaZQ';
						$email_config['smtp_port'] = '587';

						$this->load->library('email');
						$this->email->initialize($email_config);

						$to='testdevloper007@gmail.com';
						//$this->email->set_mailtype("html");
						$this->email->from($from, 'Castleevents');
						$this->email->to($to); 
						//echo $_SERVER['DOCUMENT_ROOT'].'/assets/'.$image_name; die;
						$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/'.$image_name, 'inline');
						//$cid='';
						$cid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/'.$image_name);

						$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/images/new-logo-mail.png', 'inline');
						//$cid='';
						$cid1 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/images/new-logo-mail.png');
				


				$body='<!DOCTYPE html>
								<html>
								   <head>
									  <meta charset="utf-8">
									  <meta name="viewport" content="width=device-width">
									  <meta http-equiv="X-UA-Compatible" content="IE=edge">
									  <title>Varification</title>
									  <style type="text/css">
										 html,
										 body {
										 margin: 0 auto !important;
										 padding: 0 !important;         
										 width: 100% !important;
										 }
										 
										 * {
										 -ms-text-size-adjust: 100%;
										 -webkit-text-size-adjust: 100%;
										 }
										 
										 div[style*="margin: 16px 0"] {
										 margin:0 !important;
										 }
										 
										 table,
										 td {
										 mso-table-lspace: 0pt !important;
										 mso-table-rspace: 0pt !important;
										 }
									  
										 table {
										 border-spacing: 0 !important;
										 border-collapse: collapse !important;
										 table-layout: fixed !important;
										 Margin: 0 auto !important;
										 }
										 table table table {
										 table-layout: auto; 
										 }
									   
										 img {
										 -ms-interpolation-mode:bicubic;
										 }
										
										 .mobile-link--footer a,
										 a[x-apple-data-detectors] {
										 color:inherit !important;
										 text-decoration: underline !important;
										 }
									  </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="cid:'.$cid1.'" 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;">Hello '.$visitedData['username'].'</h5>
										   <span>Your profile got visited on '.date('d.M.Y',time()).' 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="cid:'.$cid.'" width="100" >

			        							<p style="color: #666; font-size: 14px; ">';
		                            $usermeetingdata = '';
	                                if($visitorData['experience']==1)
	                                {
	                                  $usermeetingdata .= 'New experience, ';
	                                }
	                                $usermeetingdata .= str_replace('_', ' ', $visitorData['preferences']);
	                                if($visitorData['preferences']=='full_swap' && ($visitorData['same_room']==1 || $visitorData['separate_room']==1))
	                                {
	                                    $usermeetingdata .= '(';
	                                    if($visitorData['same_room']==1)
	                                    {
	                                      $usermeetingdata .= 'Same room';
	                                    } 
	                                    if($visitorData['same_room']==1 && $visitorData['separate_room']==1)
	                                    {
	                                      $usermeetingdata .= ',';
	                                    } 
	                                    if($visitorData['separate_room']==1)
	                                    {
	                                      $usermeetingdata .= 'Separate room';
	                                    } 
	                                    $usermeetingdata .= ')';  
	                                }
	                                if($visitorData['interested_financial_interests']==1)
	                                {
	                                    $usermeetingdata .= ', Looking for companion';
	                                }
	                                if($visitorData['interested_in_private_meeting']==1)
	                                {
	                                    $usermeetingdata .= ', Ceremony, ';
	                                }
	            $body.=                 $usermeetingdata;

	            					if(!empty($visitorPreference)){ 
	                                    $i=1;
	                                    foreach ($visitorPreference as $preference) {
	                                      $comma = '';
	                                        if($i!=count($visitorPreference))
	                                        {
	                                          $comma = ',';
	                                        }
	                                    
	            $body.=                     $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/profil/'.$visitorData['alias'].'">https://castleevents.com/profil/'.$visitorData['alias'].'</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">If you do not wish any mail notification, please check your credentials in your settings where you can chose between Daily, Weekly or No E-Mails.</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;">
		                             		Best regards <br>
		                             		<p style="margin:5px 0 0; color:#b3975b">Your Castleevents Team</p> 
		                             	</td>
		                             </tr>
		                          </table>
		                       </td>
		                    </tr>
		                </table></div>
										  </center>
									   </body>
									</html>';
		        //echo  $body.'='.$to; die; 
		        if(!empty($visitEntry)) 
		        {
		        	if(date('Ymd') == date('Ymd', $visitEntry['created']))
		        	{
						//$this->utility->sendCIMail($to,$sub,$body);
					
		        	}
		        	else
		        	{
		        		//$this->utility->sendCIMail($to,$sub,$body);
								
		        	} 
		        }
		        else
		        {
		        	//$this->utility->sendCIMail($to,$sub,$body);

		        }    
				//$this->utility->sendCIMail($to,$sub,$body);
							  //$this->CI->email->cc('info@castleevents.com');
							  $this->email->subject($sub);
							  if($template){
							  $cont='<!DOCTYPE html>
										<html>
										   <head>
											  <meta charset="utf-8">
											  <meta name="viewport" content="width=device-width">
											  <meta http-equiv="X-UA-Compatible" content="IE=edge">
											  <title>Varification</title>
											  <style type="text/css">
												 html,
												 body {
												 margin: 0 auto !important;
												 padding: 0 !important;         
												 width: 100% !important;
												 }
												 
												 * {
												 -ms-text-size-adjust: 100%;
												 -webkit-text-size-adjust: 100%;
												 }
												 
												 div[style*="margin: 16px 0"] {
												 margin:0 !important;
												 }
												 
												 table,
												 td {
												 mso-table-lspace: 0pt !important;
												 mso-table-rspace: 0pt !important;
												 }
											  
												 table {
												 border-spacing: 0 !important;
												 border-collapse: collapse !important;
												 table-layout: fixed !important;
												 Margin: 0 auto !important;
												 }
												 table table table {
												 table-layout: auto; 
												 }
											   
												 img {
												 -ms-interpolation-mode:bicubic;
												 }
												
												 .mobile-link--footer a,
												 a[x-apple-data-detectors] {
												 color:inherit !important;
												 text-decoration: underline !important;
												 }
											  </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().'assets/images/new-logo-mail.png" width="250" alt="Castleevents" border="0"></a>
																   </td>
																</tr>
															 </table>'.$body.'</div>
												  </center>
											   </body>
											</html>';
							 }
							 else{
							 $cont=$body;
							 }
							// echo $cont; 
							 $this->email->message($cont);
							 $mail = $this->email->send();	
							 print_r( $this->email->print_debugger());
							 
							 
			}
		}
		die;
	}
	function curl()
	{	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://castleevents.com/bdaily.sh");
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$result = curl_exec($ch);
		curl_close($ch);
		print_r($result); die;
	}
	public function upcoming()
    {
        $this->load->model('common_model');
        $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 GROUP BY a.user_id 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 created > ('.time().' - (365 * 86400)) order by b.created DESC');
        $getUserListData = $qry->result();
        $i = 0;
        foreach ($getUserListData as $data) {
            print"<pre>";print_r($data);
            echo date('d-m-Y',$data->created);
		}
	}
	public function mandrill()
	{
		$this->load->config('mandrill');

		$this->load->library('mandrill');

		$mandrill_ready = NULL;
		
		$this->mandrill->init('TveFwCTbtHjorrsBDKwJ8Q');
		print_r($this->mandrill->webhooks_add(base_url().'webhook',array('hard_bounce','click','open','spam','send')));
		
		$this->load->library('email');
		$this->email->initialize(array(
		              'protocol' => 'smtp',
		              'smtp_host' => 'smtp.mandrillapp.com',
		              'smtp_user' => 'castleevents',
		              'smtp_pass' => 'TveFwCTbtHjorrsBDKwJ8Q',
		              'smtp_port' => 587,
		              'mailtype' => 'html',
		              'crlf' => "rn",
		              'newline' => "rn"
		           ));

		$this->email->from('info@castleevents.com', 'Castleevents');
		$this->email->to('testdevloper007@gmail.com');
		$this->email->subject('Mandrill mail Subject');
		$this->email->message('Hi this is a Mandrill mail');//Load a view into email body
		$send = $this->email->send();
		//echo $this->email->print_debugger();
		var_dump($result);
		die;
	}
	public function mandrill_response()
	{
		$this->load->config('mandrill');

		$this->load->library('mandrill');

		$mandrill_ready = NULL;
		
		$this->mandrill->init('TveFwCTbtHjorrsBDKwJ8Q');
		
		print_r($this->mandrill->webhooks_info(6));
		print_r($this->mandrill->webhooks_list());
		die;
	}
	function mandrill_mail_send()
	{
		require_once $_SERVER['DOCUMENT_ROOT'].'/Mandrill.php';
		$mandrill = new Mandrill('TveFwCTbtHjorrsBDKwJ8Q');
		//print_r($mandrill); 
	    $message = array(
	        'html' => '<p>Example HTML content</p>',
	        'subject' => 'example subject',
	        'from_email' => 'testdevloper007@gmail.com',
	        'from_name' => 'test',
	        'to' => array(
	            array(
	                'email' => 'falbuq@ig.com.br',
	                'name' => 'Recipient Name',
	                'type' => 'to'
	            )
	        ),
	        'headers' => array('Reply-To' => 'info@castleevents.com'),
	        'important' => false,
	        'track_opens' => 1,
	        'track_clicks' => 1,
	        'auto_text' => null,
	        'auto_html' => null,
	        'inline_css' => null,
	        'url_strip_qs' => null,
	        'preserve_recipients' => null,
	        'view_content_link' => null,
	        'bcc_address' => 'sayan@digitalaptech.com',
	        'tracking_domain' => null,
	        'signing_domain' => null,
	        'return_path_domain' => null,
	        'merge' => true,
	        'merge_language' => 'mailchimp',
	        'global_merge_vars' => array(
	            array(
	                'name' => 'merge1',
	                'content' => 'merge1 content'
	            )
	        ),
	        'images' => array(
	            array(
	                'type' => 'image/png',
	                'name' => 'IMAGECID',
	                'content' => 'ZXhhbXBsZSBmaWxl'
	            )
	        )
	    );
	    $async = false;
	    $ip_pool = 'Main Pool';
	    $send_at = '2017-12-05 22:00:00';
	    $result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
    	print_r($result);
    	die;
	    
	}
	public function info()
	{
		require_once $_SERVER['DOCUMENT_ROOT'].'/Mandrill.php';
		$mandrill = new Mandrill('TveFwCTbtHjorrsBDKwJ8Q');
	    $id = '938dd6f19f924062ac040777f27f4e0e';
	    $result = $mandrill->messages->info($id);
	    print_r($result);
	    die;
	}
	function getdata()
	{
		$filename = $_SERVER['DOCUMENT_ROOT'].'/assets/cleaned_segment_export_70d4ba2307.csv';
		$file = fopen($filename, "r");
          //$sql_data = "SELECT * FROM prod_list_1 ";
          //echo '<pre>';
          $i=0;
          while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
          {
              print_r($emapData);
              $total_details[]=$emapData;
              //if($i==2)
              //{
              	$this->load->model('common_model');
              	$userdata = $this->common_model->getAllRow('usr_users',array('email'=>$emapData[0]));
              	if(!empty($userdata))
              	{
              		$this->common_model->UpdateData('feu_userdetails',array('email_status'=>'bounced'),array('user_id'=>$userdata['id']));
              	}
              //}
              
              //echo $i;
              $i++;             
          }
          //echo '</pre>';

          fclose($file); die;
	}
	function news_user()
	{
		$this->load->model('common_model');
		$days = $this->common_model->getAllRow('sys_settings',array('key'=>'newsletter_days'));
		$newsletter_days = $days['value'];
		if($newsletter_days < 8)
		{
			$where = "subscribe = 1 and email_confirmed = 1 and (email_status = 'sent' or email_status = '') and subscription_mail_send = 0";
			$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC','','',0,1000);
		}
		else
		{
			$where = "subscribe = 1 and email_confirmed = 1 and (email_status = 'sent' or email_status = '') and subscription_mail_send = ".($newsletter_days - 7)."";
			$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC','','',0,1000);
		}
		print_r($userlist);die;
	}
	function StripeCustomerInfo()
	{
		require $_SERVER['DOCUMENT_ROOT'].'/stripe/Stripe.php';
		$params = array(
				"testmode"   => "on",
				//"private_live_key" => "sk_live_7yHhLLeHGtSdGfc0rJNbLXZl",
				//"public_live_key"  => "pk_live_TyYHG0MtVuby9Ja5c8gkddCx",
				"private_test_key" => "sk_test_S1Eg863dRzyX5S6deJ39KLIh",
				"public_test_key"  => "pk_test_J4rdzwRQrf2RsXG6xafA4y4q",
				//"private_test_key" => "sk_test_OFGHKhrV3K6yzNg1RtxDaakA",
				//"public_test_key"  => "pk_test_8TMqaTrtjzh44TBsV9uzi0J6",
			);
		/*$params = array(
				"testmode"   => "off",
				"private_live_key" => "sk_live_7yHhLLeHGtSdGfc0rJNbLXZl",
				"public_live_key"  => "pk_live_TyYHG0MtVuby9Ja5c8gkddCx",
				//"private_test_key" => "sk_test_S1Eg863dRzyX5S6deJ39KLIh",
				//"public_test_key"  => "pk_test_J4rdzwRQrf2RsXG6xafA4y4q",
				//"private_test_key"  => "sk_test_OFGHKhrV3K6yzNg1RtxDaakA",
				//"public_test_key"  => "pk_test_8TMqaTrtjzh44TBsV9uzi0J6",
			);*/
			
			if ($params['testmode'] == "on") {
				Stripe::setApiKey($params['private_test_key']);
				$pubkey = $params['public_test_key'];
			} else {
				Stripe::setApiKey($params['private_live_key']);
				$pubkey = $params['public_live_key'];
			}
			
				try {
					
					$charge = Stripe_Customer::retrieve('cus_BKxBks2I3Q37tB');
			 		print_r($charge);
			 		//print_r($charge['sources']['data'][0]['exp_year']);
				$result = "success";
		 
					} catch(Stripe_CardError $e) {			
				 
					$error = $e->getMessage();
						$result = "declined";
				 
					} catch (Stripe_InvalidRequestError $e) {
						$result = "declined";		  
					} catch (Stripe_AuthenticationError $e) {
						$result = "declined";
					} catch (Stripe_ApiConnectionError $e) {
						$result = "declined";
					} catch (Stripe_Error $e) {
						$result = "declined";
					} catch (Exception $e) {
				 
						if ($e->getMessage() == "zip_check_invalid") {
							$result = "declined";
						} else if ($e->getMessage() == "address_check_invalid") {
							$result = "declined";
						} else if ($e->getMessage() == "cvc_check_invalid") {
							$result = "declined";
						} else {
							$result = "declined";
						}		  
					}
					print_r($e->getMessage());die;
	}
	function testDaferpay()
	{

        $amount         = 200;
        $description    = 'Bestellung 20000 auf Castleevents';

        $initURL           = 'https://www.saferpay.com/hosting/Execute.asp';

        //For testing
        $initURL         = 'https://test.saferpay.com/hosting/Execute.asp';
        $accountId = '401860-17795278';
        $accountPassword = '8e7Yn5yk';

        $initParams      = 'ACCOUNTID=' .     urlencode($accountId);
        $initParams     .= '&spPassword=' .   urlencode($accountPassword);
        $initParams     .= '&AMOUNT=' .       urlencode(200);
        $initParams     .= '&CURRENCY=' .     urlencode('EUR');
        $initParams     .= '&ORDERID=' .      urlencode(20000);
        $initParams     .= '&DESCRIPTION=' .  urlencode('test');
        $initParams     .= '&CARDREFID=' .    'WS_00000000K1578379_071120161031';
        //End for testing

        //Original Parameters
//        $initParams        = 'ACCOUNTID=' .     urlencode($paymentmethod->saferpay_account_id);
//        $initParams       .= '&spPassword=' .   urlencode($paymentmethod->saferpay_password);
//      $initParams       .= '&EXP=' .          $expirydate;
//      $initParams       .= '&CVC=' .          $this->input->post('card_pin');
//        $initParams       .= '&AMOUNT=' .       urlencode($order->total_sum);
//      $initParams       .= '&PAN=' .          urlencode($this->input->post('card_number'));
//        $initParams       .= '&CURRENCY=' .     urlencode('EUR');
//       $initParams       .= '&ORDERID=' .      urlencode($order->cart_id);
//        $initParams       .= '&DESCRIPTION=' .  urlencode($description);
//        $initParams       .= '&CARDREFID=' .    $user->cc_ref_id;
        //End Original Parameters

        $cartId = '20000';
        
        $expYear = date('Y', strtotime('+1 year', '1504505072'));
        $expMonth = date('m', strtotime('+1 year', '1504505072'));
        $expDay = date('d', strtotime('+1 year', '1504505072'));
        $initParams .= '&RECURRING=' . 'yes';
        $initParams .= '&RECEXP='. $expYear . $expMonth . $expDay;
        $initParams .= '&RECFREQ=' . 365;



        $curl_createpayinit = curl_init($initURL);
        curl_setopt($curl_createpayinit, CURLOPT_PORT, 443);
        curl_setopt($curl_createpayinit, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl_createpayinit, CURLOPT_POST, 1);
        curl_setopt($curl_createpayinit, CURLOPT_POSTFIELDS, $initParams);
        curl_setopt($curl_createpayinit, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl_createpayinit, CURLOPT_HEADER, 0);
        curl_setopt($curl_createpayinit, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($curl_createpayinit);
        $response = explode('K:', $response);

        // Kommt "Error" in der Antwort vor? => Dann Abbruch mit Fehlermeldung
        if(strpos($response[0], 'ERROR') !== false && strpos($response[0], 'ERROR') != -1) {

            return array('error' => 'unknown_error');
        }

        // XML aufdröseln
        $respXml = simplexml_load_string($response[1]);
        print_r($respXml); die;
        // BEGIN wenn das RESULT in der XML = 0 ist, dann war die Transaktion erfolgreich - ansonsten passende Fehlermeldung zurückgeben
        if($respXml['RESULT'] == 0) {
        	$this->common_model->UpdateData('shop_orders',array('trn_id'=>$respXml['ID']),array('cart_id'=>$order->cart_id));
            //mail('testdevloper007@gmail.com','new cron success','today saferpay');
            return array('success' => 'transaction_complete');
        } else {
            //mail('testdevloper007@gmail.com','new cron fail',json_encode($respXml['RESULT']));
            switch ($respXml['RESULT']) {
                case '7004': return array('error' => 'Card reference not found');
                case '61': return array('error' => 'Invali Card');
                case '62': return array('error' => 'Invalid Date');
                case '63': return array('error' => 'Card Expired');
                case '64': return array('error' => 'Unknown Card');
                case '65': return array('error' => 'Authorization Denied');
                case '67': return array('error' => 'No Contract Available');
                case '84': return array('error' => 'Invalid Amount');
                case '113': return array('error' => 'Invalid CVC');
                case '114': return array('error' => 'CVC Mandatory');
            }
        }
        // END wenn das RESULT in der XML = 0 ist, dann war die Transaktion erfolgreich - ansonsten passende Fehlermeldung zurückgeben

	}
	function mailchimp()
	{
		$apikey = '9a1d414f170b904492f76c4b4aaad59c-us14';
 		
		$to_emails = array('sayan@digitalaptech.com');
		$to_names = array('sayan');
		 
		$message = array(
		    'html'=>'test',
		    'text'=>'test',
		    'subject'=>'This is the subject',
		    'from_name'=>'CASTLEEVENTS',
		    'from_email'=>'testdevloper007@gmail.com',
		    'to_email'=>$to_emails,
		    'to_name'=>$to_names
		);
		
        $tags = array('Newsletter mail-'.date('d-m-y'));

        $params = array(
            'apikey'=>$apikey,
            'message'=>$message,
            'track_opens'=>true,
            'track_clicks'=>false,
            'tags'=>$tags
        );

        $url = "https://us5.sts.mailchimp.com/1.0/SendEmail";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        curl_close ($ch);
        $data = json_decode($result); 
        print_r($data);
		die;
	}
	function url_get_contents ($Url='https://castleevents.com/assets/images/new-logo-mail.png') {
	    
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $Url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    $output = curl_exec($ch);
	    curl_close($ch);
	    return $output;
	    echo $str =  base64_encode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/assets/images/new-logo-mail.png'));
	    die;
	}
	function create_template()
	{
		$lib = $this->load->library('Mailchimp');
		$lists = $this->mailchimp->call('POST','lists/list');
		print_r($lists);
		die;
	}
	function sendMail()
	{
		$this->load->library('email');
		$this->email->initialize(array(
		             // 'protocol' => 'smtp',
		              'smtp_host' => 'smtp-relay.sendinblue.com',
		              'smtp_user' => 'info@castleevents.com',
		              'smtp_pass' => 'bs8yJF0cRaCOGMPt',
		              'smtp_port' => 587,
		              'mailtype' => 'html',
		              'crlf' => "rn",
		              'newline' => "rn"
		           ));

		//$this->email->from('alorenc@me.com', 'Castleevents');
		$this->email->from('info@castleevents.com', 'Castleevents');
		$this->email->to('testdevloper007@gmail.com');
		$this->email->subject('Sendinblue mail Subject');
		$this->email->message('Hi this is a Sendinblue mail');//Load a view into email body
		$send = $this->email->send();
		echo $this->email->print_debugger();
		var_dump($send);
		die;
	}
	function sendMail11()
	{
		$this->load->library('email');
		$this->email->initialize(array(
		              'protocol' => 'smtp',
		              'smtp_host' => 'smtp.gmail.com',
		              'smtp_user' => 'testdevloper007@gmail.com',
		              'smtp_pass' => 'Password@321',
		              'smtp_port' => 465,
		              'mailtype' => 'html',
		              'crlf' => "rn",
		              'newline' => "rn"
		           ));

		$this->email->from('info@castleevents.com', 'Castleevents');
		$this->email->to('testdevloper007@gmail.com');
		$this->email->subject('Gmail mail Subject');
		$this->email->message('Hi this is a Gmail mail');//Load a view into email body
		$send = $this->email->send();
		echo $this->email->print_debugger();
		//var_dump($result);
		die;
	}
	function sendMail12()
	{
		include 'path/to/mailin-api/Mailin.php';
		$mailin = new Mailin('info@castleevents.com', 'bs8yJF0cRaCOGMPt');
		$mailin->
		addTo('info@castleevents.com', 'Andrej Lorenc')->
		setFrom('info@castleevents.com', 'Andrej Lorenc')->
		setReplyTo('info@castleevents.com','Andrej Lorenc')->
		setSubject('Geben Sie hier den Betreff ein.')->
		setText('Guten Tag')->
		setHtml('<strong>Guten Tag</strong>');
		$res = $mailin->send();
		//echo $this->email->print_debugger();
		var_dump($res);
		die;
	}
	function sendMail13()
	{
		include APPPATH.'libraries/Mailins.php';
		$mailin = new Mailin('https://api.sendinblue.com/v2.0','bs8yJF0cRaCOGMPt', 5000);
		$data = array( "to" => array("testdevloper007@gmail.com"=>""),
			//"cc" => array("cc@example.net"=>"cc whom!"),
			//"bcc" =>array("bcc@example.net"=>"bcc whom!"),
			"from" => array("noreply@castleevents.com","Castleevents"),
			"replyto" => array("info@castleevents.com","Castleevents"),
			"subject" => "My subject nmew",
			//"text" => "This is the text",
			"html" => 'This is the <h1>HTML</h1><br/>
					   This is inline image 1.<br/>
					   <img src="{myinlineimage2.jpg}" alt="image2" border="0">
					   Some text<br/>',
			"attachment" => array(),
			//"headers" => array("Content-Type"=> "text/html; charset=iso-8859-1","X-param1"=> "value1", "X-param2"=> "value2",...,"X-Mailin-custom"=>"my custom value", "X-Mailin-IP"=> "102.102.1.2", "X-Mailin-Tag" => "My tag"),
			"inline_image" => array('myinlineimage2.jpg' => " ")
			);

			var_dump($mailin->send_email($data));
					//var_dump($res);
					die;
	}
	function maillib()
	{
		include APPPATH.'libraries/mail.php';
		$your_api_key = '9a1d414f170b904492f76c4b4aaad59c-us14';
		$MailChimp = new MailChimp($your_api_key);
		// Create or Post new Campaign
		/*$result = $MailChimp->post("campaigns", [
		    'type' => 'regular',
		    'recipients' => ['list_id' => '6d68e79437'],
		    'settings' => ['subject_line' => '🔥'.' Heisse Neuigkeiten   ',
		           'reply_to' => 'noreply@castleevents.com',
		           'from_name' => 'CASTLEEVENTS'
		          ]
		    ]);
		  
		$response = $MailChimp->getLastResponse();
		$responseObj = json_decode($response['body']);  */
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$url = "https://us14.api.mailchimp.com/3.0/campaigns/";
		//$html = file_get_contents('https://castleevents.com/test_1/content');
		$operation = array(
	            'type'=> 'regular',
	            'recipients'=>array('list_id' => '6d68e79437'),
	            'settings'=>array('subject_line' => '🔥'.' Heisse Neuigkeiten   ',
		           'reply_to' => 'noreply@castleevents.com',
		           'from_name' => 'CASTLEEVENTS')
	            );
	        
	    $request_encoded = json_encode($operation);
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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, 'POST');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		
		$campaigns = json_decode($result,true);

		//print_r($campaigns); die;
		$template = $this->content();
		$template_details = json_decode($template,true);
		//echo $template_details['id']; die;
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$url = "https://us14.api.mailchimp.com/3.0/campaigns/".$campaigns['id']."/content";
		//$html = file_get_contents('https://castleevents.com/test_1/content');
		$operation = array(
	            'template'=> array('id' => $template_details['id'])
	            );
	        
	    $request_encoded = json_encode($operation);
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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);
		

		$sendresult = $MailChimp->post('campaigns/' . $campaigns['id'] . '/actions/send');
		var_dump($sendresult);

		$url = "https://us14.api.mailchimp.com/3.0/campaigns/".$campaigns['id']."/send-checklist";
		$operation = array();
		//$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, 'GET');
	    //curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$checkresult = curl_exec($curl);
		$output = json_decode($checkresult,true);
		var_dump($output);
		$this->common_model->insertData('bouncing_system',array('date'=>date('Y-m-d'),'type'=>'English Newsletter','details'=>$output['items'][0]['details'],'campaign_id'=>$campaigns['id']));
		die;
	}
	function create_list()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$this->load->model('common_model');
		/*$where = "subscribe = 1 and userlanguage = 2 and (email_status = 'sent' or email_status = '')";
		$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC');
		//print_r($userlist); 
		//die;
		$arr = array();
		$arr_final = array();
		if(!empty($userlist))
		{
			foreach ($userlist as $key => $value) {
				//echo $value['email'].$value['username'].$value['alias'];
				$arr['email_address'] = $value['email'];
				$arr['status'] = 'subscribed';
				$arr['email_address'] = $value['email'];
				$arr['merge_fields']['FNAME'] = $value['username'];
				$arr['merge_fields']['LNAME'] = $value['alias'];
				
				array_push($arr_final, $arr);
			}
		}*/
		$where = "id in (25846)";
		$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC');
		//print_r($userlist); 
		//die;
		$arr = array();
		$arr_final = array();
		if(!empty($userlist))
		{
			foreach ($userlist as $key => $value) {
				//echo $value['email'].$value['username'].$value['alias'];
				$arr['email_address'] = $value['email'];
				$arr['status'] = 'subscribed';
				$arr['email_address'] = $value['email'];
				$arr['merge_fields']['FNAME'] = $value['username'];
				$arr['merge_fields']['LNAME'] = $value['alias'];
				
				array_push($arr_final, $arr);
			}
		}
		$subscribers = $arr_final;
		//print_r($subscribers); die;
		$listId = "6d68e79437";
		$batch_operations = array();
		$url = "https://us14.api.mailchimp.com/3.0/batches";
		$id = 1;
	    foreach ($subscribers as $subscriber) {
	        #echo $subscriber['email_address'];
	        $operation = array(
	            'method'=>'PUT',
	            'path'=>'lists/'.$listId.'/members/'.md5(strtolower($subscriber['email_address'])),
	            'body'=>json_encode($subscriber));
	        $id++;
	        array_push($batch_operations, $operation);
	    }

	    $request_encoded = json_encode(array('operations'=>$batch_operations));
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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, 'POST');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		var_dump($result);
		die;
	}
	function create_list_german()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$this->load->model('common_model');
		$where = "subscribe = 1 and userlanguage = 1 and (email_status = 'sent' or email_status = '')";
		$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC');
		//print_r($userlist); 
		//die;
		$arr = array();
		$arr_final = array();
		if(!empty($userlist))
		{
			foreach ($userlist as $key => $value) {
				//echo $value['email'].$value['username'].$value['alias'];
				$arr['email_address'] = $value['email'];
				$arr['status'] = 'subscribed';
				$arr['email_address'] = $value['email'];
				$arr['merge_fields']['FNAME'] = $value['username'];
				$arr['merge_fields']['LNAME'] = $value['alias'];
				
				array_push($arr_final, $arr);
			}
		}
		//$where = "id in (25931,25267)";
		//$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC');
		//print_r($userlist); 
		//die;
		$arr = array();
		$arr_final = array();
		if(!empty($userlist))
		{
			foreach ($userlist as $key => $value) {
				//echo $value['email'].$value['username'].$value['alias'];
				$arr['email_address'] = $value['email'];
				$arr['status'] = 'subscribed';
				$arr['email_address'] = $value['email'];
				$arr['merge_fields']['FNAME'] = $value['username'];
				$arr['merge_fields']['LNAME'] = $value['alias'];
				
				array_push($arr_final, $arr);
			}
		}
		$subscribers = $arr_final;
		//print_r($subscribers); die;
		$listId = "4b705bab4e";
		$batch_operations = array();
		$url = "https://us14.api.mailchimp.com/3.0/batches";
		$id = 1;
	    foreach ($subscribers as $subscriber) {
	        #echo $subscriber['email_address'];
	        $operation = array(
	            'method'=>'PUT',
	            'path'=>'lists/'.$listId.'/members/'.md5(strtolower($subscriber['email_address'])),
	            'body'=>json_encode($subscriber));
	        $id++;
	        array_push($batch_operations, $operation);
	    }

	    $request_encoded = json_encode(array('operations'=>$batch_operations));
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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, 'POST');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		var_dump($result);
		die;
	}
	function create_list_english()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$this->load->model('common_model');
		$where = "id = 21023 and subscribe = 1 and userlanguage in(2,3) and (email_status = 'sent' or email_status = '')";
		$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC');
		echo $this->db->last_query(); die;
		//print_r($userlist); 
		//die;
		$arr = array();
		$arr_final = array();
		if(!empty($userlist))
		{
			foreach ($userlist as $key => $value) {
				//echo $value['email'].$value['username'].$value['alias'];
				$arr['email_address'] = $value['email'];
				$arr['status'] = 'subscribed';
				$arr['email_address'] = $value['email'];
				$arr['merge_fields']['FNAME'] = $value['username'];
				$arr['merge_fields']['LNAME'] = $value['alias'];
				
				array_push($arr_final, $arr);
			}
		}
		//print_r($userlist); 
		//die;
		
		$subscribers = $arr_final;
		//print_r($subscribers); die;
		$listId = "a8efb2baef";
		$batch_operations = array();
		$url = "https://us14.api.mailchimp.com/3.0/batches";
		$id = 1;
	    foreach ($subscribers as $subscriber) {
	        #echo $subscriber['email_address'];
	        $operation = array(
	            'method'=>'PUT',
	            'path'=>'lists/'.$listId.'/members/'.md5(strtolower($subscriber['email_address'])),
	            'body'=>json_encode($subscriber));
	        $id++;
	        array_push($batch_operations, $operation);
	    }

	    $request_encoded = json_encode(array('operations'=>$batch_operations));
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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, 'POST');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		var_dump($result);
		die;
	}

	/*function template()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$url = "https://us14.api.mailchimp.com/3.0/templates";
		$html = file_get_contents('https://castleevents.com/test_1/content');
		$operation = array(
	            //'method'=>'POST',
	            //'path'=>'templates/',
	            'name'=>'test template today',
	            //'html'=>'<p>test</p>'
	            'html'=>$html
	            );
	        
	    $request_encoded = json_encode($operation);
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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, 'POST');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		return $result;
		//var_dump($result);
		//die;
	}*/
	public function content()
	{//echo date('d-m-y H:i:s'); die;
		$this->load->model('common_model');
		$this->load->library('Utility');
		$this->load->library('email');
		$langId = 1;
		
				
				$adverts = $this->common_model->getAllRowMultipleJoin('adverts',array('visible'=>1,'adverts_lang_values.lang_id'=>$langId),array(array('adverts_lang_values','adverts_lang_values.adverts_id = adverts.id')),'display_order ASC');
				$latestUsers = $this->common_model->getAllMultipleJoin('feu_userdetails',array('avatar_file_id >'=>0,'filename !='=>''),array(array('sys_files','feu_userdetails.avatar_file_id = sys_files.id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'feu_userdetails.created DESC','','',0,5);
				$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('sys_files','sys_files.id = evt_event_files.file_id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_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,evt_language_values.teasertext as teasertext,sys_files.filename,sys_files.path,sys_files.extension','id',0,4) ;
				//echo $this->db->last_query(); die;
				$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('sys_files','sys_files.id = evt_event_files.file_id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_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,evt_language_values.teasertext as teasertext,sys_files.filename,sys_files.path,sys_files.extension','id',0,5) ;
				//print_r($upcomingEvents); die;
				if(empty($upcomingEvents))
				{
					$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('sys_files','sys_files.id = evt_event_files.file_id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_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,sys_files.filename,sys_files.path,sys_files.extension','id',0,4) ;
				}
				if(empty($lastEvents))
				{
					$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('sys_files','sys_files.id = evt_event_files.file_id'),array('loc_events_locations','evt_events.id = loc_events_locations.event_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,sys_files.filename,sys_files.path,sys_files.extension','id',0,5) ;
				}
				
				$ladyOfTheMonth = $this->common_model->getAllRowMultipleJoin('usr_users',array('filename!='=>'','accounttype'=>'lady','shop_articles.id >'=>0,'about !='=>''),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'shop_carts.created DESC','*,feu_userdetails.alias');
				//print_r($ladyOfTheMonth); die;
				$coupleOfTheWeek = $this->common_model->getAllRowMultipleJoin('usr_users',array('filename!='=>'','accounttype'=>'couple','shop_articles.id >'=>0,'about !='=>'','LENGTH(about) >'=>50),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country'),array('ugal_images','ugal_images.user_id = feu_userdetails.user_id')),'RAND()','*,feu_userdetails.alias');
				//echo $this->db->last_query(); die;
				$visitorOfTheWeek = $this->common_model->getAllRowMultipleJoin('feu_profilevisits',array('filename!='=>'','about !='=>'','LENGTH(about) >'=>10,'from_user_id'=>$users['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'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'','*,feu_userdetails.alias');
				if(empty($visitorOfTheWeek))
				{
					$visitorOfTheWeek = $this->common_model->getAllRowMultipleJoin('usr_users',array('filename!='=>'','accounttype'=>'gentleman','shop_articles.id'=>4,'about !='=>'','LENGTH(about) >'=>10),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id'),array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_articles_carts','shop_articles_carts.cart_id = shop_carts.id'),array('shop_articles','shop_articles.id = shop_articles_carts.article_id'),array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'usr_users.last_login DESC,shop_carts.created DESC','*,feu_userdetails.alias');
				}

				$testimonial = $this->common_model->getAllRowMultipleJoin('testimonials',array('status'=>1,'lang_id'=>$langId),array(array('sys_files','sys_files.id = testimonials.image_id'),array('testimonial_values','testimonial_values.testimonial_id = testimonials.id')),'testimonials.id DESC');
				
				$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/images/logocastle_news.svg', 'inline');
		  		$cid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/images/logocastle_news.svg');
		  		$cidurl = base_url().'/assets/images/logocastle_news.svg';

		  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/images/new-logo-mail.png', 'inline');
		  		$cid1 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/images/new-logo-mail.png');
		  		$cid1url = base_url().'/newsletter_image/new-logo-mail.png';
		  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/images/new-logo-mail.png',$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/new-logo-mail.png');
		  		$advertcid = '';
		  		if(!empty($adverts))
				{
			  		$str = explode('/',$adverts['image']);
			  		$advimage = end($str);
			  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/adverts/160/'.$advimage, 'inline');
			  		$advertcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/adverts/160/'.$advimage);
			  		$advertcidurl = base_url().'/newsletter_image/'.$advimage;
			  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/adverts/160/'.$advimage,$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$advimage);
			  	}

			  	$testimonialcid = '';
		  		if(!empty($testimonial))
				{
			  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$testimonial['path'].'/'.$testimonial['filename'].'.'.$testimonial['extension'], 'inline');
			  		$testimonialcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$testimonial['path'].'/'.$testimonial['filename'].'.'.$testimonial['extension']);
			  		$testimonialcidurl = base_url().'/newsletter_image/'.$testimonial['filename'].'.'.$testimonial['extension'];
			  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$testimonial['path'].'/'.$testimonial['filename'].'.'.$testimonial['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$testimonial['filename'].'.'.$testimonial['extension']);
			  	}
			  	if(!empty($upcomingEvents)){ 
			  		foreach ($upcomingEvents as $keys => $upcoming) {
			  			if($keys==0)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/500/'.$upcoming['filename'].'.'.$upcoming['extension'], 'inline');
				  			$upcomingcid0 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/500/'.$upcoming['filename'].'.'.$upcoming['extension']);
				  			$upcomingcid0url = base_url().'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/500/'.$upcoming['filename'].'.'.$upcoming['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension']);
			    		}
			    		if($keys==1)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/750/'.$upcoming['filename'].'.'.$upcoming['extension'], 'inline');
				  			$upcomingcid1 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/750/'.$upcoming['filename'].'.'.$upcoming['extension']);
				  			$upcomingcid1url = base_url().'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/750/'.$upcoming['filename'].'.'.$upcoming['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension']);
			    		}
			    		if($keys==2)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension'], 'inline');
				  			$upcomingcid2 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension']);
				  			$upcomingcid2url = base_url().'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension']);
			    		}
			    		if($keys==3)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension'], 'inline');
				  			$upcomingcid3 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension']);
				  			$upcomingcid3url = base_url().'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension']);
			    		}
			    		if($keys==4)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension'], 'inline');
				  			$upcomingcid4 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension']);
				  			$upcomingcid4url = base_url().'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$upcoming['path'].'/250/'.$upcoming['filename'].'.'.$upcoming['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$upcoming['filename'].'.'.$upcoming['extension']);
			    		}
				  		
			  		}
			  	}

			  	if(!empty($lastEvents)){ 
                    for($i=0;$i<=(count($lastEvents)-count($upcomingEvents));$i++) {           
				  		if($i==0)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'], 'inline');
				  			$lastEventscid0 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
				  			$lastEventscid0url = base_url().'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'];
			    			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
			    		}
			    		if($i==1)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'], 'inline');
				  			$lastEventscid1 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
				  			$lastEventscid1url = base_url().'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
			    		}
			    		if($i==2)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'], 'inline');
				  			$lastEventscid2 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
				  			$lastEventscid2url = base_url().'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
			    		}
			    		if($i==3)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'], 'inline');
				  			$lastEventscid3 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
				  			$lastEventscid3url = base_url().'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
			    		}
			    		if($i==4)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'], 'inline');
				  			$lastEventscid4 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
				  			$lastEventscid4url = base_url().'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'];
				  			$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$lastEvents[$i]['path'].'/250/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$lastEvents[$i]['filename'].'.'.$lastEvents[$i]['extension']);
			    		}
				  		
			  		}
			  	}
			  	
			  	$ladyOfTheMonthcid = '';
		  		if(!empty($ladyOfTheMonth))
				{
			  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$ladyOfTheMonth['path'].'/320/'.$ladyOfTheMonth['filename'].'.'.$ladyOfTheMonth['extension'], 'inline');
			  		$ladyOfTheMonthcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$ladyOfTheMonth['path'].'/320/'.$ladyOfTheMonth['filename'].'.'.$ladyOfTheMonth['extension']);
			  		$ladyOfTheMonthcidurl = base_url().'/newsletter_image/'.$ladyOfTheMonth['filename'].'.'.$ladyOfTheMonth['extension'];
			  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$ladyOfTheMonth['path'].'/320/'.$ladyOfTheMonth['filename'].'.'.$ladyOfTheMonth['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$ladyOfTheMonth['filename'].'.'.$ladyOfTheMonth['extension']);
			  	}

			  	$coupleOfTheWeekcid = '';
		  		if(!empty($coupleOfTheWeek))
				{
			  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$coupleOfTheWeek['path'].'/320/'.$coupleOfTheWeek['filename'].'.'.$coupleOfTheWeek['extension'], 'inline');
			  		$coupleOfTheWeekcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$coupleOfTheWeek['path'].'/320/'.$coupleOfTheWeek['filename'].'.'.$coupleOfTheWeek['extension']);
			  		$coupleOfTheWeekcidurl = base_url().'/newsletter_image/'.$coupleOfTheWeek['filename'].'.'.$coupleOfTheWeek['extension'];
			  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$coupleOfTheWeek['path'].'/320/'.$coupleOfTheWeek['filename'].'.'.$coupleOfTheWeek['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$coupleOfTheWeek['filename'].'.'.$coupleOfTheWeek['extension']);
			  	}
			  	$visitorOfTheWeekcid = '';
		  		if(!empty($visitorOfTheWeek))
				{
			  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$visitorOfTheWeek['path'].'/320/'.$visitorOfTheWeek['filename'].'.'.$visitorOfTheWeek['extension'], 'inline');
			  		$visitorOfTheWeekcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$visitorOfTheWeek['path'].'/320/'.$visitorOfTheWeek['filename'].'.'.$visitorOfTheWeek['extension']);
			  		$visitorOfTheWeekcidurl = base_url().'/newsletter_image/'.$visitorOfTheWeek['filename'].'.'.$visitorOfTheWeek['extension'];
			  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$visitorOfTheWeek['path'].'/320/'.$visitorOfTheWeek['filename'].'.'.$visitorOfTheWeek['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$visitorOfTheWeek['filename'].'.'.$visitorOfTheWeek['extension']);
			  	}

			  	$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/images/link.png', 'inline');
		  		$linkcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/images/link.png');
		  		$linkcidurl = base_url().'/newsletter_image/link.png';

		  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/images/link.png',$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/link.png');

		  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/images/internet.png', 'inline');
		  		$internetcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/images/internet.png');
		  		$internetcidurl = base_url().'/newsletter_image/internet.png';

		  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/images/internet.png',$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/internet.png');

		  		$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/images/support-box-ico.png', 'inline');
		  		$supportcid = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/images/support-box-ico.png');
		  		$supportcidurl = base_url().'/newsletter_image/support-box-ico.png';
		  		$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/images/support-box-ico.png',$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/support-box-ico.png');
			  	
			  	if(!empty($latestUsers))
			    {
			    	foreach ($latestUsers as $key => $latest) {
			    		if($key==0)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'], 'inline');
			  				$usercid0 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension']);
			  				$usercid0url = base_url().'/newsletter_image/'.$latest['filename'].'.'.$latest['extension'];
			  				$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$latest['filename'].'.'.$latest['extension']);
			    		}
			    		if($key==1)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'], 'inline');
			  				$usercid1 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension']);
			  				$usercid1url = base_url().'/newsletter_image/'.$latest['filename'].'.'.$latest['extension'];
			  				$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$latest['filename'].'.'.$latest['extension']);
			    		}
			    		if($key==2)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'], 'inline');
			  				$usercid2 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension']);
			  				$usercid2url = base_url().'/newsletter_image/'.$latest['filename'].'.'.$latest['extension'];
			  				$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$latest['filename'].'.'.$latest['extension']);
			    		}
			    		if($key==3)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'], 'inline');
			  				$usercid3 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension']);
			  				$usercid3url = base_url().'/newsletter_image/'.$latest['filename'].'.'.$latest['extension'];
			  				$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$latest['filename'].'.'.$latest['extension']);
			    		}
			    		if($key==4)
			    		{
			    			$this->email->attach($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'], 'inline');
			  				$usercid4 = $this->email->attachment_cid($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension']);
			  				$usercid4url = base_url().'/newsletter_image/'.$latest['filename'].'.'.$latest['extension'];
			  				$this->putContent($_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/'.$latest['path'].'/320/'.$latest['filename'].'.'.$latest['extension'],$_SERVER['DOCUMENT_ROOT'].'/newsletter_image/'.$latest['filename'].'.'.$latest['extension']);
			    		}
			    	
			    	}
			    }
	$html='<!DOCTYPE html>
				<html lang="en">
				<head>
					<meta charset="utf-8"> 
					<meta name="viewport" content="width=device-width">
					<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
				    <meta name="x-apple-disable-message-reformatting">  
					<title></title>

					<style type="text/css">
					  
						#button001 {text-align: center;}
						#button001 > a {
							display: inline-block;
							background: #b3975b;
							color: #fff;
							padding: 10px 30px;
							-webkit-border-radius: 8px;
							-moz-border-radius: 8px;
							border-radius: 8px;
							text-decoration:none;
						} 
						@media screen and (max-width: 761px) {
					        #button001 {
					          text-align: center;
					        }
				      	}
				      	center + center {
						    display: none;
						}
					</style>
				</head>
				<body id="body" width="100%" bgcolor="#ffffff" style="margin: 0; mso-line-height-rule: exactly; font-family:Arial;">
				    <center style="width: 100%; background: #ffffff; text-align: left;">';

				        			if($langId==1)
				                    {
			$html.='                    <div style="display:none;font-size:1px;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;mso-hide:all;font-family: sans-serif;">
									        '.$adverts['sub_title'].'</span> '.$adverts['intro_text'].'
									    </div>';	                    		
				                    }
									else
									{
			$html.='	                <div style="display:none;font-size:1px;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;mso-hide:all;font-family: sans-serif;">
									        '.$adverts['sub_title'].'</span> '.$adverts['intro_text'].'
									    </div>';
									}
				        
			$html.='	<table role="presentation" aria-hidden="true" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" align="center" width="700" style="margin: auto;" class="email-container">
							<tr>
								<td style="padding: 20px 0; text-align: center">
									<div style="width: 90%; padding: 0 15px; text-align: center;" class="logosvg">
										<a href="'.base_url().'"><img src="'.$cid1url.'" alt="CASTLEEVENTS.COM"></a>
										
				                    </div>';
				                    if($langId==1)
				                    {
			$html.='	                    <p style="color:#b3974b; margin-top:10px; margin-bottom:0;">"Eines der Dinge, die man tun muss, bevor man stirbt.."</p>
				                      		<span style="color:#b3974b;"> - DT Magazin, Spanien - </span>';	                    		
				                    }
									else
									{
			$html.='	                    <p style="color:#b3974b; margin-top:10px; margin-bottom:0;">"One of the things you have to do before you die.."</p>
				                      		<span style="color:#b3974b;"> - DT Magazin, Spanien - </span>';							
									}

			$html.='			</td>
							</tr>
				        </table>
				        

				        
				        <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" align="center" width="700" style="margin: auto;" class="email-container">';
				        		if($langId==1)
				        		{
			$html.='	                    <tr>
				                  <td style="text-align:center;  padding-bottom: 15px;">
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'all-parties">Parties</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/castleevents">Einblicke</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/einfuhrung">Community</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/venezianischen-masken">Shop</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/geschichte">Uber uns</a>
				                  </td>                  
				               </tr> ';	                    		
				                    }
									else
									{
			$html.='	                    <tr>
				                  <td style="text-align:center;  padding-bottom: 15px;">
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'all-parties">Parties</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/castleevents">Insights</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/introduction">Community</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/venetian-masks">Shop</a>
				                    <a style="padding: 8px 10px; display: inline-block; margin: 0 18px; text-decoration: none; color: #000000;
				    text-transform: uppercase; font-size: 12px;" href="'.base_url().'events/team">About Us</a>
				                  </td>                  
				               </tr> ';							
									}
				           
				               
				           
			if(!empty($adverts))
			{
				$link = explode('https://', $adverts['link']);
				$links = '';
				if(count($link)>0)
				{
					if(count($link)>1)
					{
						$links = 'https://'.$link[1];
					}
					else
					{
						$links = $link[0];
					}
				}
				$html.='	        <tr>
				                <td bgcolor="#131218" dir="ltr" align="center" valign="top" width="100%" style="padding: 10px;">
				                    <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                        <tbody><tr>
				                            

				                            <td width="33.33%" class="stack-column-center">
				                                <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                    <tbody><tr>
				                                        <td align="center" valign="top" style="padding: 0 10px;">
				                                          <div style="width:120px; display: inline-block; vertical-align: top; height:120px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                                               <img width="100%" height="120px" src="'.$advertcidurl.'" alt="userpic">
				                                           </div>
				                                        </td>
				                                    </tr>
				                                </tbody></table>
				                            </td>
				                            
				                            
				                            <td width="66.66%" class="stack-column-center">
				                                
				                                <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                     
				                                    <tbody><tr>
				                                        <td dir="ltr" valign="top" style="font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555; padding: 10px; text-align: left;" class="center-on-narrow">
				                                                    <h2 style="margin: 0 0 10px 0; font-family: sans-serif; font-size: 18px; line-height: 21px; color: #ffffff; font-weight: normal; text-transform:uppercase;">'.$adverts['title'].'</h2>
				                                                    <p style="margin: 0 0 10px 0; color:#e2e2e2;"><span style="color:#b3975b; font-weight:bold;">'.$adverts['sub_title'].'</span> '.$adverts['intro_text'].'</p>
				                                                    <p id="button001"><a href="'.$links.'">'.(($langId==1)?'Mehr Infos':'Read More').'</a></p>
				                                            
				                                            
				                                            
				                                        </td>
				                                    </tr>
				                                </tbody></table>
				                            </td>
				                            
				                        </tr>
				                    </tbody></table>
				                </td>
				            </tr>';
			}	            
				$html.='            <tr>
				                <td bgcolor="#131218" style="padding: 20px; text-align: center;">
				                    
				                    ';

				    if(!empty($latestUsers))
				    {
				    	foreach($latestUsers as $key => $latest) {
				    		$html.= '<div  class="community" href="'.base_url().'" style="margin:0 10px; display:inline-block; vertical-align:top; color:#e2e2e2; text-decoration:none;">
				                        <h5 style="margin: 0 0 5px; color:#b3975b; text-transform: uppercase;">'.$latest['username'].'</h5>';
				            if($key==0)
				            {
				            	$html.= '<div style="width:80px; position: relative; display: inline-block; vertical-align: top; height:80px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                          <img height="80" width="80"  width="80px" height="80px" style="height: 80px; width: 80px; min-width: 80px; position: absolute; min-height: 80px; width: auto; display: block;" src="'.$usercid0url.'" alt="userpic">
				                          
				                        </div>';
				            }
				            if($key==1)
				            {
				            	$html.= '<div style="width:80px; position: relative; display: inline-block; vertical-align: top; height:80px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                          <img height="80" width="80"  width="80px" height="80px" style="height: 80px; width: 80px; min-width: 80px; position: absolute; min-height: 80px; width: auto; display: block;" src="'.$usercid1url.'" alt="userpic">
				                          
				                        </div>';
				            }
				            if($key==2)
				            {
				            	$html.= '<div style="width:80px; position: relative; display: inline-block; vertical-align: top; height:80px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                          <img height="80" width="80"  width="80px" height="80px" style="height: 80px; width: 80px; min-width: 80px; position: absolute; min-height: 80px; width: auto; display: block;" src="'.$usercid2url.'" alt="userpic">
				                          
				                        </div>';
				            }
				            if($key==3)
				            {
				            	$html.= '<div style="width:80px; position: relative; display: inline-block; vertical-align: top; height:80px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                          <img height="80" width="80"  width="80px" height="80px" style="height: 80px; width: 80px; min-width: 80px; position: absolute; min-height: 80px; width: auto; display: block;" src="'.$usercid3url.'" alt="userpic">
				                          
				                        </div>';
				            }
				            if($key==4)
				            {
				            	$html.= '<div style="width:80px; position: relative; display: inline-block; vertical-align: top; height:80px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                          <img height="80" width="80"  width="80px" height="80px" style="height: 80px; width: 80px; min-width: 80px; position: absolute; min-height: 80px; width: auto; display: block;" src="'.$usercid4url.'" alt="userpic">
				                          
				                        </div>';
				            }
				            
				                        
				            $html.= '<p style="margin: 5px 0 5px; font-size:11px; text-transform: capitalize;" >'.$latest['accounttype'].'</p>
				                     </div>';
				    	}
				    }                


				$html.='                </td>
				            </tr>

				            <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>';
				        if(!empty($upcomingEvents))
				        {
			$html.='    <tr>
				                <td bgcolor="#eeeeee" style="">
				                    <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" align="center" style="margin: auto">
				                        <tr>
				                            <td class="stack-column-center" align="center" width="50%" style="padding:20px;">
				                                <h3 style="font-size:20px; font-weight: normal; text-transform:uppercase; margin:0; text-align:center; color: #333333;">'.$upcomingEvents[0]['title'].'</h3>
				                                <h5 style="font-size:15px; text-transform:uppercase; margin:0 0 10px; text-align:center; color: #b3975b; font-weight: normal;">'.$upcomingEvents[0]['city'].' '.date('d.m.Y',$upcomingEvents[0]['time_from']).'</h5>
				                                <p style="text-align:center; color: #333333;">'.$upcomingEvents[0]['teasertext'].'</p>
				                                <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" class="center-on-narrow" >
				                                                <tbody><tr>
				                                                    <td style="-webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; background: #b3975b; text-align: center;" class="button-td">
				                                                        <a href="'.base_url().'parties/'.$upcomingEvents[0]['alias'].'" style="background: #b3975b; border: 10px solid #b3975b; font-family: sans-serif; font-size: 13px; line-height: 1.1; text-align: center; text-decoration: none; display: block; -webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; font-weight: bold;" class="button-a">
				                                                            <span style="color:#ffffff;" class="button-link">&nbsp;&nbsp;&nbsp;&nbsp;'.(($langId==1)?'Mehr Infos':'Read More').'&nbsp;&nbsp;&nbsp;&nbsp;</span>
				                                                        </a>
				                                                    </td>
				                                                </tr>
				                                            </tbody>
				                                            </table>
				                            </td>
				                            <td class="stack-column-center" align="right" width="50%">
				                                <div style="overflow:hidden;">
				                                    <img width="100%" style="display:block; height:228px;" src="'.$upcomingcid0url.'" alt="">
				                                </div>
				                            </td>
				                        </tr>
				                    </table>
				                </td>
				            </tr>';
				        }    
				
				            
				$html.='    <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>';
						if(!empty($upcomingEvents))
				        {            
				            
				$html.='    <tr>
				               
				                <td>
				                	<div style="position: relative; display:block; overflow: hidden; min-height: 196px;">
				                  	 <img src="'.$upcomingcid1url.'" width="100%"  style="display:block; min-height:400px; width:700px; min-width:700px; position: absolute;" alt="">                   
				                	</div>
				                </td>
				            </tr>

				            <tr>               
				                <td bgcolor="#eeeeee" align="center" style="padding:30px">
				                   <h3 style="margin:0; font-size:20px; text-transform:uppercase; font-weight:normal; color: #333333;">'.$upcomingEvents[1]['title'].'</h3>
				                   <h5 style=" color:#b3975b; font-size: 16px; margin:5px 0 15px; text-transform:uppercase; font-weight:normal;">'.$upcomingEvents[1]['city'].' '.date('d.m.Y',$upcomingEvents[1]['time_from']).'</h5>
				                   <p style=" color: #333333;">'.$upcomingEvents[1]['teasertext'].'</p>  
				                   		<table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" class="center-on-narrow">
                                                <tbody><tr>
                                                    <td style="-webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; background: #b3975b; text-align: center;" class="button-td">
                                                        <a href="'.base_url().'parties/'.$upcomingEvents[1]['alias'].'" style="background: #b3975b; border: 10px solid #b3975b; font-family: sans-serif; font-size: 13px; line-height: 1.1; text-align: center; text-decoration: none; display: block; -webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; font-weight: bold;" class="button-a">
                                                            <span style="color:#ffffff;" class="button-link">&nbsp;&nbsp;&nbsp;&nbsp;'.(($langId==1)?'Mehr Infos':'Read More').'&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                                        </a>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>                 
				                </td>
				            </tr>';
				        }   
				             
				$html.='    <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>

				            
				            <tr>
				                <td bgcolor="#ffffff" align="center" valign="top" style="padding: 10px 0;">
				                    <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" width="100%">
				                        <tr>';
				                    if(!empty($upcomingEvents)){ 
                                        foreach ($upcomingEvents as $keys => $upcoming) {
				                           if($keys>1)
				                           { 
				$html.='                    <td width="33.33%" class="stack-column-center" style="padding: 0 10px 0 0;">
				                                <table width="100%" role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0">';
				                                   
				                                   if($keys==2)
				                                   {
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$upcomingcid2url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				                                   if($keys==3)
				                                   {
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$upcomingcid3url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				                                   if($keys==4)
				                                   {
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$upcomingcid4url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				
				$html.='                                    <tr>
				                                        <td align="center" bgcolor="#eeeeee" style="font-family: sans-serif; height: 233px; font-size: 15px; line-height: 20px; color: #555555; padding:20px 10px; " >
				                                            <h3 style="margin:0; font-size:18px; text-transform:uppercase; font-weight:normal; color: #333333;">'.$upcoming['title'].'</h3>
				                                            
				                                            <h5 style=" color:#b3975b; font-size: 16px; margin:5px 0 15px; text-transform:uppercase; font-weight:normal;">'.date('d.m.Y',$upcoming['time_from']).'</h5>
				                                            <div style="min-height:150ox; max-height: 150px; height: 150px; ">
				                                            	<p style="margin: 0 0 20px; color: #333333;">'.$upcoming['teasertext'].'</p>
				                                            </div>
				                                            <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" class="center-on-narrow" >
				                                                <tbody><tr>
				                                                    <td style="-webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; background: #b3975b; text-align: center;" class="button-td">
				                                                        <a href="'.base_url().'parties/'.$upcoming['alias'].'" style="background: #b3975b; border: 10px solid #b3975b; font-family: sans-serif; font-size: 13px; line-height: 1.1; text-align: center; text-decoration: none; display: block; -webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; font-weight: bold;" class="button-a">
				                                                            <span style="color:#ffffff;" class="button-link">&nbsp;&nbsp;&nbsp;&nbsp;'.(($langId==1)?'Mehr Infos':'Read More').'&nbsp;&nbsp;&nbsp;&nbsp;</span>
				                                                        </a>
				                                                    </td>
				                                                </tr>
				                                            </tbody>
				                                            </table>
				                                        </td>
				                                    </tr>
				                                </table>
				                            </td>';
				                        	}
				                        } }   
				                if(!empty($lastEvents)){ 
                                       for($i=0;$i<=(count($lastEvents)-count($upcomingEvents));$i++) {           
				                           
				                            
				$html.='                    <td width="33.33%" class="stack-column-center" style="padding: 0 10px 0 0;">
				                                <table width="100%" role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0">';
				                                   if($i==0)
				                                   { 
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$lastEventscid0url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				                                   if($i==1)
				                                   { 
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$lastEventscid1url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				                                   if($i==2)
				                                   {
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$lastEventscid2url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				                                   if($i==3)
				                                   {
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$lastEventscid3url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   }  
				                                   if($i==4)
				                                   {
				$html.='                            <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                            <img src="'.$lastEventscid4url.'" aria-hidden="true" width="100%" height="170" alt="alt_text" border="0" class="fluid" style="display:block;">
				                                        </td>
				                                    </tr>';                                   	
				                                   } 
				$html.='                            <tr>
				                                        <td align="center" bgcolor="#eeeeee" style="font-family: sans-serif; height: 233px; font-size: 15px; line-height: 20px; color: #555555; padding:20px 10px; " >
				                                            <h3 style="margin:0; font-size:18px; text-transform:uppercase; font-weight:normal; color: #333333;">'.$lastEvents[$i]['title'].'</h3>
				                                            <h5 style=" color:#b3975b; font-size: 16px; margin:5px 0 15px; text-transform:uppercase; font-weight:normal;">'.date('d.m.Y',$lastEvents[$i]['time_from']).'</h5>
				                                            <div style="min-height:150ox; max-height: 150px; height: 150px; ">
				                                            	<p style="margin: 0 0 20px; color: #333333;">'.$lastEvents[$i]['teasertext'].'</p>
				                                            </div>
				                                            <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" class="center-on-narrow" >
				                                                <tbody><tr>
				                                                    <td style="-webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; background: #b3975b; text-align: center;" class="button-td">
				                                                        <a href="'.base_url().'reviews/'.$lastEvents[$i]['alias'].'" style="background: #333; border: 10px solid #333; font-family: sans-serif; font-size: 13px; line-height: 1.1; text-align: center; text-decoration: none; display: block; -webkit-border-radius: 8px; -moz-border-radius: 8px; -ms-border-radius: 8px; -o-border-radius: 8px; -khtml-border-radius: 8px; border-radius: 8px; font-weight: bold;" class="button-a">
				                                                            <span style="color:#ffffff;" class="button-link">&nbsp;&nbsp;&nbsp;&nbsp;'.(($langId==1)?'Rückblick':'See Review').'&nbsp;&nbsp;&nbsp;&nbsp;</span>
				                                                        </a>
				                                                    </td>
				                                                </tr>
				                                            </tbody>
				                                            </table>
				                                        </td>
				                                    </tr>
				                                </table>
				                            </td>';                        
				                        } }      

				$html.='                </tr>
				                    </table>
				                </td>
				            </tr>';
				            
				            if($langId==1)
				            {
				          
				$html.='    <tr>
				                <td bgcolor="#ffffff">
				                    <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" width="100%">
				                        <tr>
				                            <td class="paddingnormal" align="center" style="padding: 40px 110px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #000000;">
				                            <h3 style="margin:0 0 10px; font-size:20px; text-transform:uppercase; font-weight:normal;  color: #333333">Spannendes Bei CastleEvents</h3>
				                            <h5 style="margin:0; font-size:16px; font-style: italic;  font-weight:normal;  color: #333333">Tauchen Sie ein in eine Welt voller Gefühle und Leidenschaften unserer Parties und Ihrer Mitglieder</h5>
				                                
				                            </td>
				                            </tr>
				                    </table>
				                </td>
				            </tr>';
				            }
				            else
				            {
				$html.='    <tr>
				                <td bgcolor="#ffffff">
				                    <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" width="100%">
				                        <tr>
				                            <td class="paddingnormal" align="center" style="padding: 40px 130px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #000000;">
				                            <h3 style="margin:0 0 10px; font-size:20px; text-transform:uppercase; font-weight:normal; color: #333333">Exciting CastleEvents</h3>
				                            <h5 style="margin:0; font-size:16px; font-style: italic;  font-weight:normal; color: #333333">Entering our community and join the most exclusive parties in the world of emotions and passions</h5>
				                                
				                            </td>
				                            </tr>
				                    </table>
				                </td>
				            </tr>';            	
				            }

				            
				$html.='    <tr>
				                <td bgcolor="#ffffff" align="center" valign="top" style="padding: 10px 0;">
				                    <table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" width="100%">
				                        <tr>';
				                        if(!empty($coupleOfTheWeek))
				                        {
				$html.='                	<td width="33.33%" class="stack-column-center" style="padding: 0 10px 0 0;">
				                                <table width="100%" bgcolor="#eeeeee" role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0">
				                                <tr>
				                                    <td align="center" style="padding:20px">
				                                        <h3 style="margin:0; color:#b3975b; font-size:18px; text-transform:uppercase; font-weight:normal;">'.$coupleOfTheWeek['username'].'</h3>
				                                        <h5 style=" font-size: 14px; color: #000000; margin:0; text-transform:uppercase; font-weight:normal;">'.$coupleOfTheWeek['accounttype'].', '.$coupleOfTheWeek['country_name'].'</h5>

				                                    </td>
				                                </tr>
				                                    <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                           <div style="width:150px; height:150px; overflow: hidden; display: inline-block; vertical-align: top; -webkit-border-radius:100%; -moz-border-radius:100%; -ms-border-radius:100%; -khtml-border-radius:100%; border-radius:100%;">
				                                               <img src="'.$coupleOfTheWeekcidurl.'" aria-hidden="true" width="100%" height="150px" alt="alt_text" border="0"  style="display:block;">
				                                           </div>
				                                            
				                                        </td>
				                                    </tr>
				                                    <tr>
				                                        <td align="center" bgcolor="#eeeeee" style=" height: 213px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555; padding:20px 10px; " >
				                                            <h3 style="margin:0 0 15px; font-family: times; font-size:21px; font-style: italic; font-weight:normal;">'.(($langId==1)?'Pärchen der Woche':'Couple of the week').'</h3>
				                                            
				                                            

				                                            <p style="margin: 0; font-style: italic;">'.preg_replace('/\s+?(\S+)?$/', '', substr($coupleOfTheWeek['about'], 0, 150)).'..</p>
				                                           
				                                        </td>
				                                    </tr>
				                                </table>
				                            </td>';                        	
				                        }

				                        if(!empty($ladyOfTheMonth))
				                        {
				$html.='                	<td width="33.33%" class="stack-column-center" style="padding: 0 10px 0 0;">
				                                <table width="100%" bgcolor="#eeeeee" role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0">
				                                <tr>
				                                    <td align="center" style="padding:20px">
				                                        <h3 style="margin:0; color:#b3975b; font-size:18px; text-transform:uppercase; font-weight:normal;">'.$ladyOfTheMonth['username'].'</h3>
				                                        <h5 style=" font-size: 14px; color: #000000; margin:0; text-transform:uppercase; font-weight:normal;">'.$ladyOfTheMonth['accounttype'].', '.$ladyOfTheMonth['country_name'].'</h5>

				                                    </td>
				                                </tr>
				                                    <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                           <div style="width:150px; height:150px; overflow: hidden; display: inline-block; vertical-align: top; -webkit-border-radius:100%; -moz-border-radius:100%; -ms-border-radius:100%; -khtml-border-radius:100%; border-radius:100%;">
				                                               <img src="'.$ladyOfTheMonthcidurl.'" aria-hidden="true" width="100%" height="150px" alt="alt_text" border="0"  style="display:block;">
				                                           </div>
				                                            
				                                        </td>
				                                    </tr>
				                                    <tr>
				                                        <td align="center" bgcolor="#eeeeee" style="  height: 213px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555; padding:20px 10px; " >
				                                            <h3 style="margin:0 0 15px;  font-family: times; font-size:21px; font-style: italic; font-weight:normal;">'.(($langId==1)?'Lady des Monats':'Lady of the month').'</h3>
				                                            
				                                            

				                                            <p style="margin: 0; font-style: italic;">'.preg_replace('/\s+?(\S+)?$/', '', substr($ladyOfTheMonth['about'], 0, 150)).'..</p>
				                                           
				                                        </td>
				                                    </tr>
				                                </table>
				                            </td>';                        	
				                        }
				                        if(!empty($visitorOfTheWeek))
				                        {
				$html.='                	<td width="33.33%" class="stack-column-center" style="padding: 0 10px 0 0;">
				                                <table width="100%" bgcolor="#eeeeee" role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0">
				                                <tr>
				                                    <td align="center" style="padding:20px">
				                                        <h3 style="margin:0; color:#b3975b; font-size:18px; text-transform:uppercase; font-weight:normal;">'.$visitorOfTheWeek['username'].'</h3>
				                                        <h5 style=" font-size: 14px; color: #000000; margin:0; text-transform:uppercase; font-weight:normal;">'.$visitorOfTheWeek['accounttype'].', '.$visitorOfTheWeek['country_name'].'</h5>

				                                    </td>
				                                </tr>
				                                    <tr>
				                                        <td style="margin: 10px 10px 0; text-align: center">
				                                           <div style="width:150px; height:150px; overflow: hidden; display: inline-block; vertical-align: top; -webkit-border-radius:100%; -moz-border-radius:100%; -ms-border-radius:100%; -khtml-border-radius:100%; border-radius:100%;">
				                                               <img src="'.$visitorOfTheWeekcidurl.'" aria-hidden="true" width="100%" height="150px" alt="alt_text" border="0"  style="display:block;">
				                                           </div>
				                                            
				                                        </td>
				                                    </tr>
				                                    <tr>
				                                        <td align="center" bgcolor="#eeeeee" style="height: 213px; font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555; padding:20px 10px; " >
				                                            <h3 style="margin:0 0 15px; font-family: times; font-size:21px; font-style: italic; font-weight:normal;">'.(($langId==1)?'Ihr letzter Besucher':'Your last visitor').'</h3>
				                                            
				                                            

				                                            <p style="margin: 0; font-style: italic;">'.preg_replace('/\s+?(\S+)?$/', '', substr($visitorOfTheWeek['about'], 0, 150)).'..</p>
				                                           
				                                        </td>
				                                    </tr>
				                                </table>
				                            </td>';                        	
				                        }  

				$html.='                </tr>
				                    </table>
				                </td>
				            </tr>
				           
				            
				           
				            <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>';
				            if(!empty($testimonial))
				            {
				             
				$html.='    <tr>
				                <td bgcolor="#131218" dir="ltr" align="center" valign="top" width="100%" style="padding: 10px;">
				                    <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                        <tbody><tr>
				                            

				                            <td width="33.33%" class="stack-column-center">
				                                <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                    <tbody><tr>
				                                        <td align="center" valign="top" style="padding: 0 10px;">
				                                          <a href="'.base_url().'testimonials">
				                                          <div style="width:120px; display: inline-block; vertical-align: top; height:120px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                                               <img width="100%" height="120px" src="'.$testimonialcidurl.'" alt="userpic">
				                                           </div>
				                                           </a>
				                                        </td>
				                                    </tr>
				                                </tbody></table>
				                            </td>
				                            
				                            
				                            <td width="66.66%" class="stack-column-center">
				                                <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                    <tbody><tr>
				                                        <td dir="ltr" valign="top" style="font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555; padding: 10px; text-align: left;" class="center-on-narrow">
				                                                    <h2 style="margin: 0 0 10px 0; font-family: sans-serif; font-size: 18px; line-height: 21px; color: #ffffff; font-weight: normal; text-transform:uppercase;"><span style="color:#b3975b;">'.$testimonial['name'].'</h2>
				                                                    <div style="margin: 0 0 10px 0; color:#e2e2e2; font-family:times; font-style:italic; font-size:16px;">'.$testimonial['text'].'</div>
				                                            
				                                            
				                                        </td>
				                                    </tr>
				                                </tbody></table>
				                            </td>
				                            
				                        </tr>
				                    </tbody></table>
				                </td>
				            </tr>';     
				        }


				           
				$html.='    <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>


				            <tr>
				                <td bgcolor="#eeeeee" dir="ltr" align="center" valign="top" width="100%" style="padding: 10px;">
				                    <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                        <tbody><tr>
				                            

				                            <td width="33.33%" class="stack-column-center">
				                                <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                    <tbody><tr>
				                                        <td align="center" valign="top" style="padding: 0 10px;">
				                                          <div style="width:120px; display: inline-block; vertical-align: top; height:120px; overflow:hidden; -webkit-border-radius:100%; -moz-border-radius:100%; -khtml-border-radius:100%; -ms-border-radius:100%; border-radius:100%;">
				                                               <img width="100%" height="120px" src="'.$supportcidurl.'" alt="userpic">
				                                           </div>
				                                        </td>
				                                    </tr>
				                                </tbody></table>
				                            </td>
				                            
				                            
				                            <td width="66.66%" class="stack-column-center">
				                                <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                    <tbody>
				                                      <tr>
				                                        <td dir="ltr" valign="top" style="font-family: sans-serif; font-size: 15px; line-height: 20px; color: #555555; padding: 10px; text-align: left;" class="center-on-narrow">
				                                                    <h2 style="margin: 0 0 10px 0; font-family: sans-serif; font-size: 18px; line-height: 21px; color: #ffffff; font-weight: normal; text-transform:uppercase;"><span style="color:#b3975b;">'.(($langId==1)?'KONTAKTIEREN SIE UNS':'Contact Us').'</span></h2>';
				                                                if($langId==1)
				                                                {
				                $html.='                             <p style="margin: 0 0 20px 0; color:#000; font-family:times; font-style:italic; font-size:18px;"><strong>Buchen</strong> Sie direkt per E-Mail <a href="mailto:info@castleevents.com" style="color:#000;">info@castleevents.com</a> wir beantworten Ihre Anfragen unverzüglich.</p>';   	
				                                                } 
				                                                else
				                                                {
				                $html.='                             <p style="margin: 0 0 20px 0; color:#000; font-family:times; font-style:italic; font-size:18px;"><strong>Book</strong> directly by email <a href="mailto:info@castleevents.com" style="color:#000;">info@castleevents.com</a> we will answer your request immediately.</p>';
				                                                }   
				                                                    
				                                                    
				                $html.='                        <table role="presentation" aria-hidden="true" align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
				                                                        <tr>
				                                                            <td>
				                                                              <a href="'.base_url().'" style="color:#b3975b; text-decoration:none; margin-right:20px;"><img src="'.$linkcidurl.'" valign="middle" style="margin-right:8px" alt=""> '.(($langId==1)?'Website besuchen':'Visit Website').'</a>  
				                                                              <a href="'.base_url().'home/language" style="color:#b3975b; text-decoration:none;"><img src="'.$internetcidurl.'" valign="middle" style="margin-right:8px" alt=""> '.(($langId==1)?'Sprache ändern':'Change language after login').'</a>  
				                                                            </td>
				                                                        </tr>
				                                                    </table>
				                                            
				                                            
				                                        </td>
				                                    </tr>
				                                </tbody></table>
				                            </td>
				                            
				                        </tr>
				                    </tbody></table>
				                </td>
				            </tr>



				            <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>

				            <tr>
				                <td align="right"><p style="color:#a7a7a7; font-style:italic; font-family: times; font-size:16px;"><a href="'.base_url().'home/unsubscribe/118a4ef469" style="color:#a7a7a7;">'.(($langId==1)?'Newsletter abmelden':'Newsletter unsubscribe').'</a></p></td>
				            </tr>

				            <tr>
				                <td height="20" style="font-size: 0; line-height: 0;">
				                    &nbsp;
				                </td>
				            </tr>
				            

				            

				        </table>
				    </center>
				</body>
				</html>
				';  	
			
		//echo $html; die;
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$url = "https://us14.api.mailchimp.com/3.0/templates";
		//$html = file_get_contents('https://castleevents.com/test_1/content');
		$operation = array(
	            //'method'=>'POST',
	            //'path'=>'templates/',
	            'name'=>'Newsletter template dated '.date('d-m-Y'),
	            //'html'=>'<p>test</p>'
	            'html'=>$html
	            );
	        
	    $request_encoded = json_encode($operation);
	    //var_dump($batch_operations);
	    //var_dump($request_encoded);
	    $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, 'POST');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		return $result;
		//print_r($result);
		//die;
	}
	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 unsubscribe()
	{
		$where = "subscribe = 1 and userlanguage = 3 and (email_status = 'sent' or email_status = '')";
		$userlist = $this->common_model->getAllMultipleJoin('feu_userdetails',$where,array(array('usr_users','feu_userdetails.user_id = usr_users.id')),'id ASC');
		if($userlist)
		{
			//echo '<pre>';print_r($userlist);die;
			foreach ($userlist as $key => $value) {
				//if($key==2)
				//{
					$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
					//print_r($subscribers); die;
					$listId = "a8efb2baef";
					$batch_operations = array();
					$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower($value['email']));
					$operation = array(
				            'email_address'=>$value['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); 
					$result = curl_exec($curl);
					echo $value['email'].'<pre>'.print_r(json_decode($result,true));
				//}
				
			}
		}
		
		die;
	}
	function checklist()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$this->load->model('common_model');
		$campaignId = "44df6226ab";
		$batch_operations = array();
		$url = "https://us14.api.mailchimp.com/3.0/campaigns/".$campaignId."/send-checklist";
		$operation = array();
		//$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, 'GET');
	    //curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		//var_dump($result);
		print_r(json_decode($result,true));
		die;
	}
	function members()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$this->load->model('common_model');
		$listId = "6d68e79437";
		$batch_operations = array();
		$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members";
		$operation = array();
		//$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, 'GET');
	    //curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		//var_dump($result);
		print_r(json_decode($result,true));
		die;
	}
	function delete_members()
	{
		$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
		$this->load->model('common_model');
		$listId = "4b705bab4e";
		$batch_operations = array();
		$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower('sayanchatterjee062@gmail.com'));
		$operation = array(
	            'email_address'=>'sayanchatterjee062@gmail.com',
	            
	            );
		$request_encoded = json_encode($operation);
	    $curl = curl_init($url);
	    curl_setopt($curl, CURLOPT_USERPWD, 'user:' . $apiKey);    
	    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
		$result = curl_exec($curl);
		var_dump($result);
		die;
	}
	function check_customer($cus_id='')
	{
		require $_SERVER['DOCUMENT_ROOT'].'/stripe/Stripe.php';
				$params = array(
						"testmode"   => "off",
						"private_live_key" => "sk_live_7yHhLLeHGtSdGfc0rJNbLXZl",
						"public_live_key"  => "pk_live_TyYHG0MtVuby9Ja5c8gkddCx",
					);
			
				if ($params['testmode'] == "on") {
					Stripe::setApiKey($params['private_test_key']);
					$pubkey = $params['public_test_key'];
				} else {
					Stripe::setApiKey($params['private_live_key']);
					$pubkey = $params['public_live_key'];
				}
				try {	
					$charge = Stripe_Customer::retrieve($cus_id);
			 		echo '<pre>';print_r($charge); //die;
			 		
					$result = "success";
		 
				} catch(Stripe_CardError $e) {			
			 
				$error = $e->getMessage();
					$result = "declined";
			 
				} catch (Stripe_InvalidRequestError $e) {
					$result = "declined";		  
				} catch (Stripe_AuthenticationError $e) {
					$result = "declined";
				} catch (Stripe_ApiConnectionError $e) {
					$result = "declined";
				} catch (Stripe_Error $e) {
					$result = "declined";
				} catch (Exception $e) {
			 
					if ($e->getMessage() == "zip_check_invalid") {
						$result = "declined";
					} else if ($e->getMessage() == "address_check_invalid") {
						$result = "declined";
					} else if ($e->getMessage() == "cvc_check_invalid") {
						$result = "declined";
					} else {
						$result = "declined";
					}		  
				}	
				echo $e->getMessage(); die;
			
	}
	function sendSMS()
	{
		include APPPATH.'libraries/Mailins.php';
	    $mailin = new Mailin('https://api.sendinblue.com/v2.0','bs8yJF0cRaCOGMPt', 5000);
		$data = array( "to" => "+917687823989",
			"from" => "Castle",
			"text" => "Good morning - test",
			"type" => "transactional"
		);
	 	//print_r($data); die;
		var_dump($mailin->send_sms($data));
		die;
	}
	function sendBulkSMS()
	{
		$url = "https://bulksms.vsms.net/eapi/submission/send_sms/2/2.0?username=Sakrileg&password=ppp79111&message=Hi+Mom+%26+Dad&msisdn=919748116201";
		$curl = curl_init($url);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
	    $result = curl_exec($curl);
		var_dump($result);
		die;
	}
	function adwords()
	{
		print_r($_SERVER['HTTP_REFERER']);

		if(preg_match('/gclid/i', $_SERVER['HTTP_REFERER']) or preg_match('/gclid/i', $_SERVER['REQUEST_URI'])) {

		echo "Google adwords visitor content";

		}

		else {

		echo "regular visitor content";

		}
		die;
	}
	function FBadwords()
	{
		print_r($_SERVER['HTTP_USER_AGENT']);

		if(preg_match('/facebook.com/i', $_SERVER['HTTP_USER_AGENT']) or preg_match('/facebook.com/i', $_SERVER['REQUEST_URI'])) {

		echo "Facebook adwords visitor content";

		}

		else {

		echo "regular visitor content";

		}
		die;
	}
	function payfast()
	{
		$paymant_method = array(
		    1 => 'eft', //sets eft payment method
		    2 => 'cc', //sets credit card payment method
		    3 => 'dc', //sets debit card payment method
		    4 => 'bc', //sets bitcoin payment method
		    5 => 'mp', //sets masterpass payment method
		    6 => 'mc', //sets mobicred payment method
		    7 => 'cd' //sets cash deposit payment method
		);
		$amount         = 150;
		$data           = array(
		    // Merchant details
		    'merchant_id' => '10008144',
		    'merchant_key' => '5974omhsj6oc4',
		    'return_url' => 'https://cisites.dapldevelopment.com/payfast/success.php',
		    'cancel_url' => 'https://cisites.dapldevelopment.com/payfast/cancel.php',
		    'notify_url' => 'https://cisites.dapldevelopment.com/payfast/notify.php',
		    // Buyer details
		    'name_first' => 'First',
		    'name_last' => 'Last',
		    'email_address' => 'test123.dapl@gmail.com',
		    // Transaction details
		    'm_payment_id' => '821', //Unique payment ID to pass through to notify_url
		    // Amount needs to be in ZAR
		    // If multicurrency system its conversion has to be done before building this array
		    'amount' => number_format(sprintf("%.2f", $amount), 2, '.', ''),
		    'item_name' => 'Item Name',
		    'item_description' => 'ItDescription',
		    'custom_int1' => '9861', //custom integer to be passed through
		    'custom_str1' => 'custom string is passed along with transaction to notify_url page'
		);
		$pfOutput = '';
		// Create GET string
		foreach ($data as $key => $val) {
		    if (!empty($val)) {
		        $pfOutput .= $key.'='.urlencode(trim($val)).'&';
		    }
		}
		// Remove last ampersand
		$passPhrase = 'testdevloper007';
		$getString = substr($pfOutput, 0, -1);
		if (isset($passPhrase)) {
		    $getString .= '&passphrase='.urlencode(trim($passPhrase));
		}
		$data['signature'] = md5($getString);

		// If in testing mode use the sandbox domain ?  sandbox.payfast.co.za else www.payfast.co.za
		$testingMode = true;
		$pfHost      = $testingMode ? 'sandbox.payfast.co.za' : 'www.payfast.co.za';
		/*$htmlForm    = '<form action = "https://'.$pfHost.'/eng/process" method = "post">';
		foreach ($data as $name => $value) {
		    $htmlForm .= '<input name= "'.$name.'" type = "hidden" value = "'.$value.'" />';
		}
		$htmlForm .= '<input type= "submit" value = "Pay Now" /></form>';
		echo $htmlForm;*/
		foreach ($data as $name => $value) {
		    $post_items .= $value.'&';
		}

		// Set up cURL, add "?testing=true" to the end when testing
		$ch = curl_init( "https://".$pfHost."/eng/process");
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch, CURLOPT_HEADER, false );
		curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 1 );
		curl_setopt( $ch, CURLOPT_TIMEOUT, 60 );
		curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
		// For the body values such as amount, item_name, & item_description
		curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $post_items ) );
		curl_setopt( $ch, CURLOPT_VERBOSE, 1 );

		// Execute and close cURL
		$response = curl_exec( $ch );
		$msg = $this->ParseMsg($result);print_r($msg); die;
		curl_close( $ch );
		var_dump($response);die;
	}
	public function ParseMsg($msg)
    {
        //convert to array data
        $parts = explode("&", $msg);
        $result = array();
        foreach ($parts as $i => $value) {
            $bits = explode("=", $value, 2);
            $result[$bits[0]] = urldecode($bits[1]);
        }
        return $result;
    }
    public function backup()
	{
	  
	  //if you have previously connected to the FTP server make sure you have closed the connection
	  //$this->ftp->close();  
	  
	  //the backup library requires that you have already connected to your database
	   
	  $prefs = array( 
	      "base_path"   => "/home/castleevents/", //the base path on your server when the file are located
	      "backup_dir"  => "backups", //the folder that you will use on this server to hold the backup files
	      "ignore_table"  => array(), //ignores tables in the database you are connected to
	      "backup_tables"  => array(), //backs up only these tables in the database you are connected to
	      "ftp_transfer"  => false, //true = attempts to connect to the FTP server to transfer your backup files, false = stores files locally only
	      "ftp_server"  => "176.10.116.163", //the ftp URL
	      "ftp_user"   => "castle@castleevents.com", //the ftp username
	      "ftp_pass"   => "wNZ3p}aZ]TQq", //the ftp password
	      "ftp_base_path"  => "public_html", //if your site is located in a public_html folder or other like this. No /(slash) required
	      "ftp_port"   => 21, //the ftp port number
	      "remote_dir"  => "remote_folder", //the folder on the remote server where the FTP will place files this can be a directory like `home/domain/folder`
	      "send_email"  => false, //true = sends backup files to the email address if it is able to, false = doesn't attempt an email
	      "email_addresses" => array("name@domain.com"), //email address(es) that the backup will be sent to
	      "email_from"  => "auto-backup@domain.com", //the email address that the backup email will be from
	      "email_from_name" => "Backup Script", //the name that the backup email will be from
	      "max_mail_size"  => 0, //the max size in bytes that the email account can receive
	      "file_backup"  => true, //true = backup the site files, false = just the databases
	      "directories"   => array(), //empty array backups everything or you can list directories to backup array("application", "forum", "resources/uploads")
	      "copy_directory" => "site_files" //this is the temp directory that is used when creating a backup of the site files
	  );
	     
	  $this->load->library("backup");  
	  
	  $this->backup->init($prefs);
	  $this->backup->run();
	  
	}
	function siteBack()
	{//echo $_SERVER['DOCUMENT_ROOT'].'/backups/';die;
		$this->load->library('zip'); 
	    $path = 'application/'; 
	    $time = time();
	    $this->zip->read_dir($path);  
	    //$result = $this->zip->download('backup.'.$time.'.zip'); 
	    $this->zip->archive('/home/castleevents/backups/backup.'.date('d-m-Y').'.zip'); 
	    return $result;  
	    exit;
	}
	function validate_mobile($mobile)
	{
	    preg_match_all('#(\d{4,})#', $mobile, $matches);
	    pr($matches);
	    die;
	}
	function lady()
	{
		$total_lady = $this->common_model->getAllMultipleJoin('feu_userdetails',array('accounttype'=>'lady','ordered'=>1),array(array('shop_carts','shop_carts.user_id = feu_userdetails.user_id')));
		pr($total_lady);
		//$paid_lady = $this->common_model->getAllMultipleJoin('feu_userdetails',array('accounttype'=>'lady','ordered'=>1),array(array('shop_carts','shop_carts.user_id = feu_userdetails.user_id')));
		//pr($paid_lady);
		//$avatar_lady = $this->common_model->getAllMultipleJoin('feu_userdetails',array('accounttype'=>'lady'),array(array('shop_carts','shop_carts.user_id = feu_userdetails.user_id')));
		//pr($lady);
	}
	function time()
	{
	    date_default_timezone_set("Europe/Zurich");
	    echo  date('H').'=';
	    echo getonline();
	    die;
	}
	function allsubscribed(){
		$qry = $this->db->query('select * from feu_userdetails join usr_users on feu_userdetails.user_id = usr_users.id where subscribe = 1');
        $getUserListData = $qry->result_array();
		if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Email';
			
			$output_filename = 'All subscribed users list.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getUserListData as $Result) {
				$leadArray['Email']=$Result['email'];
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
	}
	function deleteNewsletterlist()
	{
		$allusers = $this->common_model->getAll('deleted_users');
		if(count($allusers)>0)
		{
			foreach ($allusers as $key => $value) {
				/********Delete from Castleevents German************/
				$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
				$listId = "4b705bab4e";
				$batch_operations = array();
				$url = "https://us14.api.mailchimp.com/3.0/lists/".$listId."/members/".md5(strtolower('lmieschke@gmail.com'));
				$operation = array(
			            'email_address'=>'lmieschke@gmail.com',
			            
			            );
				$request_encoded = json_encode($operation);
			    $curl = curl_init($url);
			    curl_setopt($curl, CURLOPT_USERPWD, 'user:' . $apiKey);    
			    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
			    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
			    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
			    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encoded); 
				$result = curl_exec($curl);
				var_dump($result); 
				/********Delete from Castleevents German************/

				/********Delete from Castleevents English************/	
				$apiKey = "9a1d414f170b904492f76c4b4aaad59c-us14";
				$listIdEng = "a8efb2baef";
				$batch_operations = array();
				$urlEng = "https://us14.api.mailchimp.com/3.0/lists/".$listIdEng."/members/".md5(strtolower('lmieschke@gmail.com'));
				$operationEng = array(
			            'email_address'=>'lmieschke@gmail.com',
			            
			            );
				$request_encodedEng = json_encode($operationEng);
			    $curl = curl_init($urlEng);
			    curl_setopt($curl, CURLOPT_USERPWD, 'user:' . $apiKey);    
			    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
			    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
			    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
			    curl_setopt($curl, CURLOPT_POSTFIELDS, $request_encodedEng); 
				$result = curl_exec($curl);
				var_dump($result); 
				/********Delete from Castleevents English************/	
			}
		}
		die;
	}
	function safergetcharge(){
		$cards = $this->common_model->getAll('charge_card',array('date >'=>'2017-08-31 00:00:00','user_id >'=>0,'payment_status'=>'Unpaid'),'','date DESC');
		//pr($cards);
		if(count($cards)>0)
		{
			foreach ($cards as $key => $value) {
				$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$value['user_id']));
				$user_id = $userDetails['id'];
				$cartArr = array(
							'created'=>strtotime($value['date']),
							'user_id'=>$user_id,
							'session_id'=>$this->session->userdata('session_id'),
							'ordered'=>1
					);
				//$cartId = 1; 
				$cartId = $this->common_model->insertData('shop_carts',$cartArr);
				$type = 5;
				$time = 182;
				if($value['amount']>300)
				{
					$type = 4;
					$time = 365;
				}
				$artArr = array(
							'created'=>strtotime($value['date']),
							'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');
				$payment_fee = ($value['amount']*2.5)/100;
				$method = 13;
				if($value['error']=='Your card was declined')
				{
					$method = 14;
				}
				$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' 			=> ($value['amount']-$payment_fee)*100,
					'shipping_fee' 			=> 0,
					'payment_fee' 			=> $payment_fee*100,
					'vat' 					=> 0,
					'total_sum' 			=> $value['amount']*100 ,
					'payment_method_id' 	=> $method,
					'invoiceAddress' 		=> $userDetails['email'],
		            'discount'              => 0,
		            'payed'              	=> 0,
		            'time'					=> $time,
		            'created'				=> strtotime($value['date']),
		            'fail_reason'			=> $value['error'],
		            'is_renewed' 			=> 1,
				);
				$orderId = $this->common_model->insertData('shop_orders',$dataset);

				$this->common_model->UpdateData('shop_orders',array('order_id_masked'=>'CE-'.$orderId),array('order_id'=>$orderId));
			}
		}
		die;
	}
	/*function stripegetcharge(){
		$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`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked 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 GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 182 then (created >= '.(strtotime('2017-08-31')-(182*86400)).' AND created <= '.(strtotime('2018-07-24')-(182*86400)).') when time = 365 then (created >= '.(strtotime('2017-08-31')-(365*86400)).' AND created <='.(strtotime('2018-07-24')-(365*86400)).') END AND article_id in (5,4) AND payment_method_id = 14 order by b.created ASC');
		$cards = $qry->result_array();
		//echo $this->db->last_query();die;
		pr($cards);
		if(count($cards)>0)
		{
			foreach ($cards as $key => $value) {
				$userDetails = $this->common_model->getAllRow('usr_users',array('id'=>$value['user_id']));
				$user_id = $userDetails['id'];
				$cartArr = array(
							'created'=>$value['created'],
							'user_id'=>$user_id,
							'session_id'=>$this->session->userdata('session_id'),
							'ordered'=>1
					);
				$cartId = $this->common_model->insertData('shop_carts',$cartArr);
				$type = 5;
				$time = 182;
				if($value['amount']>300)
				{
					$type = 4;
					$time = 365;
				}
				$artArr = array(
							'created'=>$value['created'],
							'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');
				$payment_fee = ($value['amount']*2.5)/100;
				$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' 			=> $payment_fee*100,
					'vat' 					=> 0,
					'total_sum' 			=> $value['amount']*100 ,
					'payment_method_id' 	=> 14,
					'invoiceAddress' 		=> $userDetails['email'],
		            'discount'              => 0,
		            'time'					=>($origPrice==170 || $origPrice==690)?182:365,
		            'created'				=>$value['created'],
		            'fail_reason'			=> $value['error'],
				);
				$orderId = $this->common_model->insertData('shop_orders',$dataset);

				$this->common_model->UpdateData('shop_orders',array('order_id_masked'=>'CE-'.$orderId),array('order_id'=>$orderId));
			}
		}
	}*/
	function stripegetchargepay(){
		$qry = $this->db->query('select * from (select * from (SELECT case when shop_orders.time = 365 then DATE(FROM_UNIXTIME(shop_orders.created + (365 * 86400))) when shop_orders.time = 182 then DATE(FROM_UNIXTIME(shop_orders.created + (182 * 86400))) end as required_date,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`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked 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 GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 182 then (created >= 1488412800 AND created <= 1516924800) when time = 365 then (created >= 1472601600 AND created <=1501113600) END AND article_id in (5,4) and payment_method_id = 14 order by b.required_date ASC');
		$cards = $qry->result_array();
		//pr($cards);
		if(count($cards)>0)
		{
			foreach ($cards as $key => $value) {
				$dataset = array(
					'amount'=> $value['total_sum'],
					'card'=> '',
					'date'=> $value['required_date'],
					'cc_ref_id'=> time().rand(0,100),
					'payment_status'=> 'Unpaid',
					'error'=> 'Card Failure',
					'user_id'=> $value['user_id']
				);
				//echo '<pre>';print_r($dataset);
				$orderId = $this->common_model->insertData('charge_card',$dataset);
				//echo $this->db->last_query();die;
			}
		}
		die;
	}
	function stripegetchargepaynew(){
		$time = strtotime('2017-08-31');
		$qry = $this->db->query('select shop_orders.* from shop_orders join shop_carts on shop_carts.id = shop_orders.cart_id join shop_articles_carts on shop_carts.id = shop_articles_carts.cart_id where payment_method_id = 13 and shop_orders.created >'.$time.' and article_id in (4,5) order by shop_orders.created DESC');
		$cards = $qry->result_array();
		//pr($cards);
		if(count($cards)>0)
		{
			foreach ($cards as $key => $value) {
				//echo '<pre>';echo $value['order_id'].''.$value['order_id'];
				$orderId = $this->common_model->UpdateData('shop_orders',array('is_renewed'=>1),array('order_id'=>$value['order_id'],'payment_method_id'=>13,''));
				//echo $this->db->last_query();die;
			}
		}
		die;
	}
	function stripegetchargepaynewone(){
		$time = strtotime('2017-08-31');
		$qry = $this->db->query('SELECT * FROM `shop_orders` WHERE `created` > 1519862400 and payed = 1 and payment_method_id = 14 and is_booking = 0 and refund_trn_id = ""');
		$cards = $qry->result_array();
		//pr($cards);
		if(count($cards)>0)
		{
			foreach ($cards as $key => $value) {
				//echo '<pre>';echo $value['order_id'].''.$value['order_id'];
				$exist = $this->common_model->getAll('shop_orders',array('payed'=>1,'payment_method_id'=>14,'invoiceAddress'=>$value['invoiceAddress'],'is_booking'=>0,'refund_trn_id'=>''));
				if(count($exist)>1)
				{
					echo '<pre>'.$value['invoiceAddress'].'='.$value['order_id'];
					$orderId = $this->common_model->UpdateData('shop_orders',array('is_renewed'=>1),array('order_id'=>$value['order_id'],'payment_method_id'=>14));
				}
				//$orderId = $this->common_model->UpdateData('shop_orders',array('is_renewed'=>1),array('order_id'=>$value['order_id'],'payment_method_id'=>13,''));
				//echo $this->db->last_query();die;
			}
		}
		die;
	}
	function stripegetchargepaynewone2(){
		$time = strtotime('2017-08-31');
		$qry = $this->db->query('SELECT * FROM `shop_orders` WHERE order_id > 2968 and total_sum = "97375"');
		$cards = $qry->result_array();
		//pr($cards);
		if(count($cards)>0)
		{
			foreach ($cards as $key => $val) {
				//echo '<pre>';
				//if($val['total_sum'] = 25625)
				//{
					//$payment_fee = 625;
					//$total_base = 25000;
				//}
				$payment_fee = '1250';
				$total_base = '87500';
				
				// elseif($val['total_sum'] = 123000)
				// {
				// 	$payment_fee = 3000;
				// 	$total_base = 120000;
				// }
				// elseif($val['total_sum'] = 35000)
				// {
				// 	$payment_fee = 750;
				// 	$total_base = 27500;
				// }
				//echo $payment_fee.'='.$total_base.'='.$val['total_sum'];
				$orderId = $this->common_model->UpdateData('shop_orders',array('total_base'=>$total_base,'payment_fee'=>$payment_fee),array('order_id'=>$val['order_id']));
				//echo $this->db->last_query();
			}
		}
		die;
	}
	function stripegetchargepaynewone21(){
		$this->utility->sendCIRenewMail('sumitb@digitalaptech.com','Test mail','Test mail');
	}
	function event_test()
	{
		$bookingDetails = $this->common_model->getAllRow('shop_booking_details',array('cart_id'=>10366),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>';
		}
		echo $body; die;
	}
	function email_activity_api()
	{
		require_once $_SERVER['DOCUMENT_ROOT'].'/Mandrill.php';
		try {
		    $mandrill = new Mandrill('TveFwCTbtHjorrsBDKwJ8Q');
		    $query = 'full_email:testdevloper007@gmail.com';
		    $date_from = '2013-01-01';
		    $date_to = '2018-10-09';
		    $tags = array();
		    $senders = array('info@castleevents.com');
		    $api_keys = array('TveFwCTbtHjorrsBDKwJ8Q');
		    $limit = 100;
		    $result = $mandrill->messages->search($query, $date_from, $date_to, $tags, $senders, $api_keys, $limit);
		    echo '<pre>';print_r($result);
		} catch(Mandrill_Error $e) {
		    // Mandrill errors are thrown as exceptions
		    echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
		    // A mandrill error occurred: Mandrill_ServiceUnavailable - Service Temporarily Unavailable
		    throw $e;
		}
		die;
	}
	function findUser($username)
	{
		$userDetails = $this->common_model->getAllRow('feu_userdetails',array('username'=>$username));
		if(count($userDetails))
		{
			$where = 'user_id='.$userDetails['user_id'].' and path like "%avatar%"';
			$userspic = $this->common_model->getAll('sys_files',$where);
			print_r($userspic);
		}
		//print_r($userDetails);
		die;
	}
	function findUserUpdate($id)
	{
		$orderId = $this->common_model->UpdateData('sys_files',array('extension'=>'jpg'),array('id'=>$id));
		die;
	}
	function openpayApi()
	{
		$merchant_id = 'moiep6umtcnanql3jrxp';
		$private_key = 'sk_3433941e467c4875b178ce26348b0fac:';
		$customerData = array(
				'name' => 'Teofilo',
				'last_name' => 'Velazco',
				'email' => 'teofilo@payments.com',
				'phone_number' => '4421112233',
				'address' => array(
						'line1' => 'Privada Rio No. 12',
						'line2' => 'Co. El Tintero',
						'line3' => '',
						'postal_code' => '76920',
						'state' => 'Querétaro',
						'city' => 'Querétaro.',
						'country_code' => 'MX'));
		$headers = array(
					'Accept'=> 'application/json',
        			'Content-Type'=> 'application/x-www-form-urlencoded;charset=UTF-8',
					'Authorization'=> 'Basic c2tfMzQzMzk0MWU0NjdjNDg3NWIxNzhjZTI2MzQ4YjBmYWM6'
					);
		$params = $private_key;

        $url = "https://sandbox-api.openpay.mx/v1/".$merchant_id."/customers";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_URL, $url.'?'.http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER , true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, json_encode($headers));
        curl_setopt($ch, CURLOPT_USERPWD, $private_key);

        $result = curl_exec($ch);
        curl_close ($ch);
        $data = json_decode($result); 
        print_r($data);
		die;
	}
	function fileResize($source='',$dest='',$width='300',$height='')
	{
		$source = $_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/img/e1fb2932a561061801d9ee55d44c32b7.jpeg';
		$dest = $_SERVER['DOCUMENT_ROOT'].'/assets/userfiles/img/message/e1fb2932a561061801d9ee55d44c32b7.jpeg';
		$config['image_library'] = 'gd2';
	    $config['source_image']  = $source;
	    $config['new_image']  =  $dest;
		$config['overwrite'] = TRUE;
		$config['width']	 = '400';
		$config['maintain_ratio'] = TRUE;
	    $this->load->library('image_lib');      
	    $this->image_lib->initialize($config);      
	    $this->image_lib->resize();
		//print_r($size);
		die;
	}
	function opnpay()
	{
		$xml = '<?xml version="1.0"?><NewOnlineOrder><JamAuthToken>30000000000000889|155f5b95-a40a-4ae5-8273-41ae83fec8c9</JamAuthToken><PurchasePrice>100.00</PurchasePrice><PlanCreationType>Pending</PlanCreationType></NewOnlineOrder>';
		$ch = curl_init();
	    curl_setopt($ch, CURLOPT_HEADER, 0);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	    curl_setopt($ch, CURLOPT_URL, 'https://retailer.myopenpay.com.au/ServiceTraining/JAMServiceImpl.svc/NewOnlineOrder' );
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml );
	    curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/xml'));
	    $response=curl_exec($ch);
	    var_dump($response);
	    die;
	}
	function check()
	{
		$where = " shop_carts.user_id = 25267 AND `payed` = 1 AND `shop_articles_carts`.`event_id` >0 AND `shop_orders`.`is_booking` =0 and evt_events.id not in (1,2)";
		$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,shop_carts.user_id');
		echo $this->db->last_query();
		//print_r($content_data['userParticipation_old']);
		die;
	}
	function test()
	{
		/*$order_to_reminder = $this->common_model->getAllRowMultipleJoin('order_to_reminder',array('order_to_reminder.user_id'=>25267,'payed'=>0,'time_from >'=>time()),array(array('shop_orders','shop_orders.order_id = order_to_reminder.order_id'),array('evt_events','evt_events.id = order_to_reminder.event_id')),'count(*) DESC,event_id DESC','count(*) as total','order_to_reminder.order_id');
		echo $this->db->last_query();die;
		$data['content'] = $this->load->view('test', array(), TRUE);
		$this->load->view('template', $data);*/
		echo date('Y-m-d H:i:s');die;
	}
	function test_renew()
	{
		$order_data = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>5341),array(array('usr_users','shop_orders.invoiceAddress = usr_users.email')));
		//pr($order_data);
		/*********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": "'.(int)$order_data['total_sum'].'",
                  "CurrencyCode": "EUR"
                },
                "Description": "Renew Membership Order",
                "PayerNote": "Renew Membership Order"
              },
              "PaymentMeans": {
                "Alias": {
                  "Id": "'.$order_data['card_alias'].'"
                }
              }
            }';

            $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'];
                    }
                }
                //mail('testdevloper007@gmail.com','new cron fail','today saferpay json api');
                //$this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('cart_id'=>$order->cart_id));
                die($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($fail_reason);
            }
            curl_close($curl);
            $response = json_decode($jsonResponse, true);
            if($response)
            {
            	echo $transactionresponse['Transaction']['Id'];die;
                pr($response);die;
            }
            die;
	}
	function test_mail()
	{
		$this->load->library('Utility');
		/*echo $cc_pan = 'xxxx xxxx xxxx '.substr(4242424242424242, -4);
		echo $expYr = substr(2022, -2);
		echo $expMth = str_pad(4, 2, '0', STR_PAD_LEFT);
		echo $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'=>25267));
		echo $this->db->last_query();*/
		$to = 'sayan@digitalaptech.com';
		$sub = 'Payment recieved';
		$body= 'CE-'.'3365'.', EUR '.number_format(10021.01, 2,',', '.');
		$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);
		echo 1; die;
	}
	
	
	function renewalcheck(){
		
		$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 , 'is_booking'=>0 , 'invoiceAddress'=>$content_data['expiry'][0]['email'] ),'','created DESC'); 
		 
	/*  var_dump($shop_order);
	 echo base_url().'add_card/index'.$shop_order['order_id'];
	 die(); */
		
		 if(count($shop_order)>0){
			
			if($shop_order['payed']==0){
				
				$shop_order_id=base64_encode($shop_order['order_id']);
				redirect(base_url().'add_card/index/'.$shop_order_id);
			}
		} 
		
		
	}
	function oldcartdata(){
		
		
		$qry = $this->db->query('SELECT cart_id, total_base from old_cart_data where total_base <= 50000');
        $getUseroldcartData = $qry->result_array();
		var_dump($getUseroldcartData);
		
		
		
		 if(!empty($getUseroldcartData))
		{
			foreach($getUseroldcartData as $row){
		
			/* $dataset = array(
					'order_id'=> $row['order_id'],
					'total_base'=> $row['total_base'],
					'article_id'=> $row['article_id'],
					'cart_id'=> $row['cart'],
					'time'=>  $row['time']
				); */
				//echo '<pre>';print_r($dataset);
				//$this->common_model->insertData('old_cart_data',$dataset); 
				$orderId = $this->common_model->UpdateData('shop_articles_carts',array('article_id'=>5),array('cart_id'=>$row['cart_id']));
				
			}
		}
		die();
	}
	
	
	function saferpaypaiment(){
		
		$arr_upcoming_safer = array();
		$currVSyear[$n]['month'] = '';
		for($n=1;$n<13;$n++)
		{
			
			
			 if($n==1)
			{
				$startDate = date('01-'.date('m').'-'.date('Y'));
				$endDate = date("t-m-Y", strtotime($startDate));
			}
			else
			{
				$startDate = date('d-m-Y', strtotime('+1 month', strtotime($startDate)));
				//$startDate = '01-'.$i.'-'.date('Y');
				$endDate = date("t-m-Y", strtotime($startDate));
				//$endDate = '31-'.$i.'-'.date('Y');
			} 
			
	echo 'stdate='.$startDate ;
				//$startDate = '01-11-2019';
	echo 'endate='.$endDate."<br />" ;
		 		//$endDate = '30-11-2019';
			
			
			 $qryqrySaferpayPaidrenewal = $this->db->query('select * from (select * from (SELECT usr_users.saferpay_exp,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`.`card_alias`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked 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 GROUP BY a.user_id ORDER BY a.user_id DESC) as b

			where case when time = 182 then (created >= '.(strtotime($startDate)-(182*86400)).' AND created <= '.(strtotime($endDate)-(182*86400)).') when time = 365 then (created >= '.(strtotime($startDate)-(365*86400)).' AND created <='.(strtotime($endDate)-(365*86400)).') END AND article_id in (5,4) AND payment_method_id = 13 and `card_alias` is not NULL and `cc_ref_id` is NULL and saferpay_exp > 0 order by b.created DESC'); 
			
			
			/* echo 'select * from (select * from (SELECT usr_users.saferpay_exp,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`.`card_alias`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,shop_orders.total_base, shop_orders.total_sum,shop_orders.payment_method_id,shop_orders.order_id_masked 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 GROUP BY a.user_id ORDER BY a.user_id DESC) as b

			where case when time = 182 then (created >= '.(strtotime($startDate)-(182*86400)).' AND created <= '.(strtotime($endDate)-(182*86400)).') when time = 365 then (created >= '.(strtotime($startDate)-(365*86400)).' AND created <='.(strtotime($endDate)-(365*86400)).') END AND article_id in (5,4) AND payment_method_id = 13 and `card_alias` is not NULL and `cc_ref_id` is NULL and saferpay_exp > 0 order by b.created DESC';
			
			die(); */
        	$ordersSaferpayPaidrenewal = $qryqrySaferpayPaidrenewal->result_array();
        	if(count($ordersSaferpayPaidrenewal)>0)
        	{
        		$total3 = 0;
        		foreach ($ordersSaferpayPaidrenewal as $key => $SaferpayPaid) {
        			$total3 = $total3 + $SaferpayPaid['total_sum'];
        		}
        	}
			
			$arr_upcoming_safer[$n]['safermonth']= date('M',strtotime($startDate));
			$arr_upcoming_safer[$n]['total3']= ceil($total3/100);
		}
		
		
		var_dump($arr_upcoming_safer);
		
		die();
		
	}
	
	
	
	function saferpaypaimentrenew(){
			
		$arr_upcoming_safer_by_month = array();
		for($n=1;$n<13;$n++)
		{  $total_sum_by_month=0;
			if($n==1)
			{
				$startDate = date('01-'.date('m').'-'.date('Y'));
				$endDate = date("t-m-Y", strtotime($startDate));
			}
			else
			{
				$startDate = date('d-m-Y', strtotime('+1 month', strtotime($startDate)));
				//$startDate = '01-'.$i.'-'.date('Y');
				$endDate = date("t-m-Y", strtotime($startDate));
				//$endDate = '31-'.$i.'-'.date('Y');
			} 
			
	echo "<br /> stdate=".$startDate ;
				
	echo 'endate='.$endDate."<br />" ;
		 		
		$shop_orders='select * from shop_orders where is_renewed=1 and payed=1 and  case when time = 182 then (created >= '.(strtotime($startDate)-(182*86400)).' AND created <= '.(strtotime($endDate)-(182*86400)).') when time = 365 then (created >= '.(strtotime($startDate)-(365*86400)).' AND created <='.(strtotime($endDate)-(365*86400)).') END group by invoiceAddress';
			
			$qryqryshop_orders = $this->db->query($shop_orders);
			 
			//var_dump($qryqryshop_orders); 
			
			
        $qryqryshop_orders_res = $qryqryshop_orders->result_array();
		//var_dump( $qryqryshop_orders_res);
        	  if(count($qryqryshop_orders_res)>0)
        	{
        		foreach ($qryqryshop_orders_res as $key => $val) {
				//	var_dump($val['invoiceAddress']);
					$email = $val['invoiceAddress'];
        			$shop_orders_final = "select * from shop_orders where payed=1 and invoiceAddress='".$email."' and is_booking=0 and payment_method_id=14 order by created desc limit 1,1";
					//var_dump($shop_orders_final);
					$qryqryshop_orders_final = $this->db->query($shop_orders_final);
					$qryqryshop_orders_res_final = $qryqryshop_orders_final->result_array();
					
					foreach($qryqryshop_orders_res_final as $vals){
						$total_sum_by_month = $total_sum_by_month+$vals['total_sum'];
					}
					
        		}
        	} 
			
			$arr_upcoming_safer_by_month[$n]['safermonths']= date('M',strtotime($startDate));
			$arr_upcoming_safer_by_month[$n]['safer_by_month_ammount']= ceil($total_sum_by_month/100);
			var_dump (ceil($total_sum_by_month/100));
		} 
		var_dump($total_sum_by_month);
		
		//var_dump($qryqryshop_orders_res);
		
		//die();
		die();
	}
	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='0_09958800_156880622220181115_234338.jpg'){
		//$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
				echo $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);
				}
				echo $source_path = $org_path.'/'.$picval;die;
				$d_path = $folderpath.'/'.$picval;
				$this->createThumb($source_path,$d_path,$toWidth);
			}//end of avaters resizer
		
		echo '1';die;
	}
	public function new_upload($picval='0_09958800_156880622220181115_234338.jpg'){
		$source_path = $_SERVER['DOCUMENT_ROOT'] . '/assets/userfiles/avatars/' . $picval;
	    $target_path = $_SERVER['DOCUMENT_ROOT'] . '/assets/userfiles/avatars/80/';
	    $config_manip = array(
	          'image_library' => 'gd2',
	          'source_image' => $source_path,
	          'new_image' => $target_path,
	          'maintain_ratio' => TRUE,
	          'create_thumb' => TRUE,
	          'thumb_marker' => '',
	          'overwrite'=>true,
	          'width' => 80,
	          'height' => 80
	    );


	    $this->load->library('image_lib', $config_manip);
	    var_dump($this->image_lib->resize());
	    if (!$this->image_lib->resize()) {
	          echo $this->image_lib->display_errors();
	    } 
	    echo $this->image_lib->display_errors();

	    $this->image_lib->clear();
	    die;
	}
	public function location(){
		/*$locations = $this->common_model->getAll('feu_addresses','','','id DESC','','',0,1);
		//pr($locations);
		if($locations){
			foreach ($locations as $key => $location) {
				$prepAddr = str_replace(' ','+',$location['address']);
			    $geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?key=AIzaSyBhS6E7uMfyWdUstf1PXpYiEFay86uUj4A&address=Austria&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_lat'=>$latitude,
					    				'user_long'=>$longitude
					    				);
						$this->common_model->UpdateData('feu_addresses',$addArr,array('id'=>$location['id']));
			    	}
			    }//die;
			}
		}*/
		$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?key=AIzaSyBhS6E7uMfyWdUstf1PXpYiEFay86uUj4A&address=Australia&sensor=false');
		$output= json_decode($geocode);
		pr($output);
		die;
	}

	public function capital(){
		echo 'capital';
		$array = '[{"name":"Afghanistan","capital":"Kabul"},{"name":"Åland Islands","capital":"Mariehamn"},{"name":"Albania","capital":"Tirana"},{"name":"Algeria","capital":"Algiers"},{"name":"American Samoa","capital":"Pago Pago"},{"name":"Andorra","capital":"Andorra la Vella"},{"name":"Angola","capital":"Luanda"},{"name":"Anguilla","capital":"The Valley"},{"name":"Antarctica","capital":""},{"name":"Antigua and Barbuda","capital":"Saint Johns"},{"name":"Argentina","capital":"Buenos Aires"},{"name":"Armenia","capital":"Yerevan"},{"name":"Aruba","capital":"Oranjestad"},{"name":"Australia","capital":"Canberra"},{"name":"Austria","capital":"Vienna"},{"name":"Azerbaijan","capital":"Baku"},{"name":"Bahamas","capital":"Nassau"},{"name":"Bahrain","capital":"Manama"},{"name":"Bangladesh","capital":"Dhaka"},{"name":"Barbados","capital":"Bridgetown"},{"name":"Belarus","capital":"Minsk"},{"name":"Belgium","capital":"Brussels"},{"name":"Belize","capital":"Belmopan"},{"name":"Benin","capital":"Porto-Novo"},{"name":"Bermuda","capital":"Hamilton"},{"name":"Bhutan","capital":"Thimphu"},{"name":"Bolivia","capital":"Sucre"},{"name":"Bonaire, Sint Eustatius and Saba","capital":"Kralendijk"},{"name":"Bosnia and Herzegovina","capital":"Sarajevo"},{"name":"Botswana","capital":"Gaborone"},{"name":"Bouvet Island","capital":""},{"name":"Brazil","capital":"Brasília"},{"name":"British Indian Ocean Territory","capital":"Diego Garcia"},{"name":"United States Minor Outlying Islands","capital":""},{"name":"Virgin Islands","capital":"Road Town"},{"name":"Virgin Islands","capital":"Charlotte Amalie"},{"name":"Brunei Darussalam","capital":"Bandar Seri Begawan"},{"name":"Bulgaria","capital":"Sofia"},{"name":"Burkina Faso","capital":"Ouagadougou"},{"name":"Burundi","capital":"Bujumbura"},{"name":"Cambodia","capital":"Phnom Penh"},{"name":"Cameroon","capital":"Yaoundé"},{"name":"Canada","capital":"Ottawa"},{"name":"Cabo Verde","capital":"Praia"},{"name":"Cayman Islands","capital":"George Town"},{"name":"Central African Republic","capital":"Bangui"},{"name":"Chad","capital":"NDjamena"},{"name":"Chile","capital":"Santiago"},{"name":"China","capital":"Beijing"},{"name":"Christmas Island","capital":"Flying Fish Cove"},{"name":"Cocos Islands","capital":"West Island"},{"name":"Colombia","capital":"Bogotá"},{"name":"Comoros","capital":"Moroni"},{"name":"Congo","capital":"Brazzaville"},{"name":"Congo","capital":"Kinshasa"},{"name":"Cook Islands","capital":"Avarua"},{"name":"Costa Rica","capital":"San José"},{"name":"Croatia","capital":"Zagreb"},{"name":"Cuba","capital":"Havana"},{"name":"Curaçao","capital":"Willemstad"},{"name":"Cyprus","capital":"Nicosia"},{"name":"Czech Republic","capital":"Prague"},{"name":"Denmark","capital":"Copenhagen"},{"name":"Djibouti","capital":"Djibouti"},{"name":"Dominica","capital":"Roseau"},{"name":"Dominican Republic","capital":"Santo Domingo"},{"name":"Ecuador","capital":"Quito"},{"name":"Egypt","capital":"Cairo"},{"name":"El Salvador","capital":"San Salvador"},{"name":"Equatorial Guinea","capital":"Malabo"},{"name":"Eritrea","capital":"Asmara"},{"name":"Estonia","capital":"Tallinn"},{"name":"Ethiopia","capital":"Addis Ababa"},{"name":"Falkland Islands","capital":"Stanley"},{"name":"Faroe Islands","capital":"Tórshavn"},{"name":"Fiji","capital":"Suva"},{"name":"Finland","capital":"Helsinki"},{"name":"France","capital":"Paris"},{"name":"French Guiana","capital":"Cayenne"},{"name":"French Polynesia","capital":"Papeetē"},{"name":"French Southern Territories","capital":"Port-aux-Français"},{"name":"Gabon","capital":"Libreville"},{"name":"Gambia","capital":"Banjul"},{"name":"Georgia","capital":"Tbilisi"},{"name":"Germany","capital":"Berlin"},{"name":"Ghana","capital":"Accra"},{"name":"Gibraltar","capital":"Gibraltar"},{"name":"Greece","capital":"Athens"},{"name":"Greenland","capital":"Nuuk"},{"name":"Grenada","capital":"St. Georges"},{"name":"Guadeloupe","capital":"Basse-Terre"},{"name":"Guam","capital":"Hagåtña"},{"name":"Guatemala","capital":"Guatemala City"},{"name":"Guernsey","capital":"St. Peter Port"},{"name":"Guinea","capital":"Conakry"},{"name":"Guinea-Bissau","capital":"Bissau"},{"name":"Guyana","capital":"Georgetown"},{"name":"Haiti","capital":"Port-au-Prince"},{"name":"Heard Island and McDonald Islands","capital":""},{"name":"Holy See","capital":"Rome"},{"name":"Honduras","capital":"Tegucigalpa"},{"name":"Hong Kong","capital":"City of Victoria"},{"name":"Hungary","capital":"Budapest"},{"name":"Iceland","capital":"Reykjavík"},{"name":"India","capital":"New Delhi"},{"name":"Indonesia","capital":"Jakarta"},{"name":"Côte dIvoire","capital":"Yamoussoukro"},{"name":"Iran","capital":"Tehran"},{"name":"Iraq","capital":"Baghdad"},{"name":"Ireland","capital":"Dublin"},{"name":"Isle of Man","capital":"Douglas"},{"name":"Israel","capital":"Jerusalem"},{"name":"Italy","capital":"Rome"},{"name":"Jamaica","capital":"Kingston"},{"name":"Japan","capital":"Tokyo"},{"name":"Jersey","capital":"Saint Helier"},{"name":"Jordan","capital":"Amman"},{"name":"Kazakhstan","capital":"Astana"},{"name":"Kenya","capital":"Nairobi"},{"name":"Kiribati","capital":"South Tarawa"},{"name":"Kuwait","capital":"Kuwait City"},{"name":"Kyrgyzstan","capital":"Bishkek"},{"name":"Lao Peoples Democratic Republic","capital":"Vientiane"},{"name":"Latvia","capital":"Riga"},{"name":"Lebanon","capital":"Beirut"},{"name":"Lesotho","capital":"Maseru"},{"name":"Liberia","capital":"Monrovia"},{"name":"Libya","capital":"Tripoli"},{"name":"Liechtenstein","capital":"Vaduz"},{"name":"Lithuania","capital":"Vilnius"},{"name":"Luxembourg","capital":"Luxembourg"},{"name":"Macao","capital":""},{"name":"Macedonia","capital":"Skopje"},{"name":"Madagascar","capital":"Antananarivo"},{"name":"Malawi","capital":"Lilongwe"},{"name":"Malaysia","capital":"Kuala Lumpur"},{"name":"Maldives","capital":"Malé"},{"name":"Mali","capital":"Bamako"},{"name":"Malta","capital":"Valletta"},{"name":"Marshall Islands","capital":"Majuro"},{"name":"Martinique","capital":"Fort-de-France"},{"name":"Mauritania","capital":"Nouakchott"},{"name":"Mauritius","capital":"Port Louis"},{"name":"Mayotte","capital":"Mamoudzou"},{"name":"Mexico","capital":"Mexico City"},{"name":"Micronesia (Federated States of)","capital":"Palikir"},{"name":"Moldova","capital":"Chișinău"},{"name":"Monaco","capital":"Monaco"},{"name":"Mongolia","capital":"Ulan Bator"},{"name":"Montenegro","capital":"Podgorica"},{"name":"Montserrat","capital":"Plymouth"},{"name":"Morocco","capital":"Rabat"},{"name":"Mozambique","capital":"Maputo"},{"name":"Myanmar","capital":"Naypyidaw"},{"name":"Namibia","capital":"Windhoek"},{"name":"Nauru","capital":"Yaren"},{"name":"Nepal","capital":"Kathmandu"},{"name":"Netherlands","capital":"Amsterdam"},{"name":"New Caledonia","capital":"Nouméa"},{"name":"New Zealand","capital":"Wellington"},{"name":"Nicaragua","capital":"Managua"},{"name":"Niger","capital":"Niamey"},{"name":"Nigeria","capital":"Abuja"},{"name":"Niue","capital":"Alofi"},{"name":"Norfolk Island","capital":"Kingston"},{"name":"Korea, Republic of","capital":"Pyongyang"},{"name":"Northern Mariana Islands","capital":"Saipan"},{"name":"Norway","capital":"Oslo"},{"name":"Oman","capital":"Muscat"},{"name":"Pakistan","capital":"Islamabad"},{"name":"Palau","capital":"Ngerulmud"},{"name":"Palestine, State of","capital":"Ramallah"},{"name":"Panama","capital":"Panama City"},{"name":"Papua New Guinea","capital":"Port Moresby"},{"name":"Paraguay","capital":"Asunción"},{"name":"Peru","capital":"Lima"},{"name":"Philippines","capital":"Manila"},{"name":"Pitcairn","capital":"Adamstown"},{"name":"Poland","capital":"Warsaw"},{"name":"Portugal","capital":"Lisbon"},{"name":"Puerto Rico","capital":"San Juan"},{"name":"Qatar","capital":"Doha"},{"name":"Republic of Kosovo","capital":"Pristina"},{"name":"Réunion","capital":"Saint-Denis"},{"name":"Romania","capital":"Bucharest"},{"name":"Russian Federation","capital":"Moscow"},{"name":"Rwanda","capital":"Kigali"},{"name":"Saint Barthélemy","capital":"Gustavia"},{"name":"Saint Helena, Ascension and Tristan da Cunha","capital":"Jamestown"},{"name":"Saint Kitts and Nevis","capital":"Basseterre"},{"name":"Saint Lucia","capital":"Castries"},{"name":"Saint Martin (French part)","capital":"Marigot"},{"name":"Saint Pierre and Miquelon","capital":"Saint-Pierre"},{"name":"Saint Vincent and the Grenadines","capital":"Kingstown"},{"name":"Samoa","capital":"Apia"},{"name":"San Marino","capital":"City of San Marino"},{"name":"Sao Tome and Principe","capital":"São Tomé"},{"name":"Saudi Arabia","capital":"Riyadh"},{"name":"Senegal","capital":"Dakar"},{"name":"Serbia","capital":"Belgrade"},{"name":"Seychelles","capital":"Victoria"},{"name":"Sierra Leone","capital":"Freetown"},{"name":"Singapore","capital":"Singapore"},{"name":"Sint Maarten (Dutch part)","capital":"Philipsburg"},{"name":"Slovakia","capital":"Bratislava"},{"name":"Slovenia","capital":"Ljubljana"},{"name":"Solomon Islands","capital":"Honiara"},{"name":"Somalia","capital":"Mogadishu"},{"name":"South Africa","capital":"Pretoria"},{"name":"South Georgia and the South Sandwich Islands","capital":"King Edward Point"},{"name":"Korea, Democratic Peoples Republic of","capital":"Seoul"},{"name":"South Sudan","capital":"Juba"},{"name":"Spain","capital":"Madrid"},{"name":"Sri Lanka","capital":"Colombo"},{"name":"Sudan","capital":"Khartoum"},{"name":"Suriname","capital":"Paramaribo"},{"name":"Svalbard and Jan Mayen","capital":"Longyearbyen"},{"name":"Swaziland","capital":"Lobamba"},{"name":"Sweden","capital":"Stockholm"},{"name":"Switzerland","capital":"Bern"},{"name":"Syrian Arab Republic","capital":"Damascus"},{"name":"Taiwan","capital":"Taipei"},{"name":"Tajikistan","capital":"Dushanbe"},{"name":"Tanzania, United Republic of","capital":"Dodoma"},{"name":"Thailand","capital":"Bangkok"},{"name":"Timor-Leste","capital":"Dili"},{"name":"Togo","capital":"Lomé"},{"name":"Tokelau","capital":"Fakaofo"},{"name":"Tonga","capital":"Nukualofa"},{"name":"Trinidad and Tobago","capital":"Port of Spain"},{"name":"Tunisia","capital":"Tunis"},{"name":"Turkey","capital":"Ankara"},{"name":"Turkmenistan","capital":"Ashgabat"},{"name":"Turks and Caicos Islands","capital":"Cockburn Town"},{"name":"Tuvalu","capital":"Funafuti"},{"name":"Uganda","capital":"Kampala"},{"name":"Ukraine","capital":"Kiev"},{"name":"United Arab Emirates","capital":"Abu Dhabi"},{"name":"United Kingdom of Great Britain and Northern Ireland","capital":"London"},{"name":"United States of America","capital":"Washington, D.C."},{"name":"Uruguay","capital":"Montevideo"},{"name":"Uzbekistan","capital":"Tashkent"},{"name":"Vanuatu","capital":"Port Vila"},{"name":"Venezuela","capital":"Caracas"},{"name":"VietNam","capital":"Hanoi"},{"name":"Wallis and Futuna","capital":"Mata-Utu"},{"name":"Western Sahara","capital":"El Aaiún"},{"name":"Yemen","capital":"Sanaa"},{"name":"Zambia","capital":"Lusaka"},{"name":"Zimbabwe","capital":"Harare"}]';

		$json_arr = json_decode($array, true);
		//pr($json_arr);
		if($json_arr){
			foreach ($json_arr as $key => $value) {
				$country_founnd = $this->common_model->getAllRow('feu_countries', array('country_name'=>$value['name']));
				if($country_founnd){
					$this->common_model->UpdateData('feu_countries', array('capital_name'=>$value['capital']),array('country_name'=>$value['name']));
				}//die;
			}
		}
		
		die;
	}

	public function export_membership(){
		/*$getUserListData = $this->common_model->getAllMultipleJoin('shop_orders',array('is_booking'=>0, 'payed'=>1,'username !='=> '', 'total_sum <'=>140000, 'shop_orders.cancelled'=>0), array(array('shop_carts','shop_carts.id = shop_orders.cart_id'), array('shop_articles_carts','shop_carts.id = shop_articles_carts.cart_id'), array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id'), array('feu_countries','feu_countries.country_code = feu_userdetails.country')),'shop_orders.created DESC','username, total_sum, payment_date, shop_orders.created, time, trn_id, article_id, order_id_masked, payment_method_id, vat, ip_address, real_name, card_origin, feu_userdetails.user_id as user_id, country_name');*/
		$membershipsql = $this->db->query("SELECT feu_userdetails.user_id as user_id, `username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `time`, `trn_id`, `article_id`, `order_id_masked`, `payment_method_id`, `vat`, `ip_address`, `real_name`, `card_origin`, `country_name`, case when payment_date is NULL then DATE(FROM_UNIXTIME(shop_orders.created)) when payment_date is not NULL then payment_date end as required_date FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `feu_countries` ON `feu_countries`.`country_code` = `feu_userdetails`.`country` WHERE `is_booking` = 0 AND `payed` = 1 AND `username` != '' AND `total_sum` < 140000 AND `shop_orders`.`cancelled` = 0 AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$cal_year." ORDER BY required_date DESC");
		$getUserListData = $membershipsql->result_array();
		//echo $this->db->last_query();die;
		pr($getUserListData);
        if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Rechnung';
			$csv_fields[] = 'Mitgliedsnummer';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Währung';
			$csv_fields[] = 'Betrag';
			$csv_fields[] = 'Zahlungsdatum';
			$csv_fields[] = 'Zahlungsart';
			$csv_fields[] = 'Transaktions Ref. Nr.';
			$csv_fields[] = 'Mitgliedschaft';
			$csv_fields[] = 'Laufzeit';
			$csv_fields[] = 'Mitgliedschaft bis';
			$csv_fields[] = 'Schweizer Kunden';
			$csv_fields[] = 'IP Adresse';
			$csv_fields[] = 'Kartenursprung';
			$csv_fields[] = 'Besitzername';
			$csv_fields[] = 'Land';

			$output_filename = 'Membership-Payments.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			$total = 0;
			foreach ($getUserListData as $Result) {
				$total = $total + $Result['total_sum'];
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Rechnung']=$Result['order_id_masked'];
				$leadArray['Mitgliedsnummer']=$Result['user_id'];
				$leadArray['Username']=html_entity_decode($Result['username']);
				$leadArray['Währung']='Euro (€)';
				$leadArray['Betrag']=number_format($Result['total_sum']/100,2,',','.');
				$leadArray['Zahlungsdatum']=($Result['payment_date']!='') ? date('d-m-Y',strtotime($Result['payment_date'])) : date('d-m-Y',$Result['created']);
				$running = 0;
				if($Result['payment_method_id']==13){
					$payment_method_id = 'Six Payment Services';
				} elseif($Result['payment_method_id']==14){
					$payment_method_id = 'Stripe';
				} else {
					$payment_method_id = 'Banküberweisung';
				}
				$leadArray['Zahlungsart']=$payment_method_id;
				$leadArray['Transaktions Ref. Nr.']=$Result['trn_id'];
				$leadArray['Mitgliedschaft']=($Result['article_id']==4 || $Result['total_sum'] > 50000) ? "Premium" : "Basic";
				$leadArray['Laufzeit']=($Result['time']==365) ? "12 Monate" : "6 Monate";
				$leadArray['Mitgliedschaft bis']=date('d-m-Y', ($Result['created']+($Result['time']*86400)));
				$leadArray['Schweizer Kunden']=($Result['vat']==0) ? "No" : "Yes";
				$leadArray['IP Adresse']=$Result['ip_address'];
				$leadArray['Kartenursprung']=$Result['card_origin'];
				$leadArray['Besitzername']=$Result['real_name'];
				$leadArray['Land']=$Result['country_name'];
				fputcsv( $output_handle, $leadArray );
				$i++;
			}

			$leadArray['Rechnung']="";
			$leadArray['Mitgliedsnummer']="";
			$leadArray['Username']="";
			$leadArray['Währung']="";
			$leadArray['Betrag']="";
			$leadArray['Zahlungsdatum']="";
			$leadArray['Zahlungsart']="";
			$leadArray['Transaktions Ref. Nr.']="";
			$leadArray['Mitgliedschaft']="";
			$leadArray['Laufzeit']="";
			$leadArray['Mitgliedschaft bis']="";
			$leadArray['Schweizer Kunden']="";
			$leadArray['IP Adresse']="";
			$leadArray['Kartenursprung']="";
			$leadArray['Besitzername']="";
			$leadArray['Land']="";
			fputcsv( $output_handle, $leadArray );


			$leadArray['Rechnung']="";
			$leadArray['Mitgliedsnummer']="";
			$leadArray['Username']="";
			$leadArray['Währung']="";
			$leadArray['Betrag']="";
			$leadArray['Zahlungsdatum']="";
			$leadArray['Zahlungsart']="";
			$leadArray['Transaktions Ref. Nr.']="";
			$leadArray['Mitgliedschaft']="";
			$leadArray['Laufzeit']="";
			$leadArray['Mitgliedschaft bis']="";
			$leadArray['Schweizer Kunden']="";
			$leadArray['IP Adresse']="";
			$leadArray['Kartenursprung']="";
			$leadArray['Besitzername']="";
			$leadArray['Land']="";
			fputcsv( $output_handle, $leadArray );


			$leadArray['Rechnung']="";
			$leadArray['Mitgliedsnummer']="";
			$leadArray['Username']="Total";
			$leadArray['Währung']='Euro (€)';
			$leadArray['Betrag']=number_format($total/100,2,',','.');
			$leadArray['Zahlungsdatum']="";
			$leadArray['Zahlungsart']="";
			$leadArray['Transaktions Ref. Nr.']="";
			$leadArray['Mitgliedschaft']="";
			$leadArray['Laufzeit']="";
			$leadArray['Mitgliedschaft bis']="";
			$leadArray['Schweizer Kunden']="";
			$leadArray['IP Adresse']="";
			$leadArray['Kartenursprung']="";
			$leadArray['Besitzername']="";
			$leadArray['Land']="";
			fputcsv( $output_handle, $leadArray );

			fclose( $output_handle ); 
			die();
		}
		die();
	}


	public function export_monthly_membership($year, $month=null){
		/*$where = "is_booking = 0 AND payed = 1 AND username !='' AND total_sum < 140000 AND shop_orders.cancelled = 0 AND MONTH(FROM_UNIXTIME(shop_orders.created)) = ".$month."  AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$year;
		$getUserListData = $this->common_model->getAllMultipleJoin('shop_orders',$where, array(array('shop_carts','shop_carts.id = shop_orders.cart_id'), array('shop_articles_carts','shop_carts.id = shop_articles_carts.cart_id'), array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id')),'shop_orders.created DESC','username, total_sum, payment_date, shop_orders.created, time, trn_id, article_id, order_id_masked, payment_method_id, vat, ip_address, real_name, card_origin');*/
		if($month!=''){
			$sql = $this->db->query("SELECT feu_userdetails.user_id as user_id, `username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `time`, `trn_id`, `article_id`, `order_id_masked`, `payment_method_id`, `vat`, `ip_address`, `real_name`, `card_origin`, `country_name`, case when payment_date is NULL then DATE(FROM_UNIXTIME(shop_orders.created)) when payment_date is not NULL then payment_date end as required_date FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `feu_countries` ON `feu_countries`.`country_code` = `feu_userdetails`.`country` WHERE `is_booking` = 0 AND `payed` = 1 AND `username` != '' AND `total_sum` < 140000 AND `shop_orders`.`cancelled` = 0 AND MONTH(FROM_UNIXTIME(shop_orders.created)) = ".$month." AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$year." ORDER BY required_date DESC");
		} else {
			$sql = $this->db->query("SELECT feu_userdetails.user_id as user_id, `username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `time`, `trn_id`, `article_id`, `order_id_masked`, `payment_method_id`, `vat`, `ip_address`, `real_name`, `card_origin`, `country_name`, case when payment_date is NULL then DATE(FROM_UNIXTIME(shop_orders.created)) when payment_date is not NULL then payment_date end as required_date FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `feu_countries` ON `feu_countries`.`country_code` = `feu_userdetails`.`country` WHERE `is_booking` = 0 AND `payed` = 1 AND `username` != '' AND `total_sum` < 140000 AND `shop_orders`.`cancelled` = 0 AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$year." ORDER BY required_date DESC");
		}
		
		$getUserListData = $sql->result_array();
		//echo $this->db->last_query();die;
		//pr($getUserListData);die;
		$month_name = date("F", mktime(0, 0, 0, $month, 10)); 

        if(!empty($getUserListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Rechnung';
			$csv_fields[] = 'Mitgliedsnummer';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Währung';
			$csv_fields[] = 'Betrag';
			$csv_fields[] = 'Zahlungsdatum';
			$csv_fields[] = 'Zahlungsart';
			$csv_fields[] = 'Transaktions Ref. Nr.';
			$csv_fields[] = 'Mitgliedschaft';
			$csv_fields[] = 'Laufzeit';
			$csv_fields[] = 'Mitgliedschaft bis';
			$csv_fields[] = 'Schweizer Kunden';
			$csv_fields[] = 'IP Adresse';
			$csv_fields[] = 'Kartenursprung';
			$csv_fields[] = 'Besitzername';
			$csv_fields[] = 'Land';

			$output_filename = $year.' Buchhaltung.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			$total = 0;
			foreach ($getUserListData as $Result) {
				$total = $total + $Result['total_sum'];
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Rechnung']=$Result['order_id_masked'];
				$leadArray['Mitgliedsnummer']=$Result['user_id'];
				$leadArray['Username']=html_entity_decode($Result['username']);
				$leadArray['Währung']='Euro (€)';
				$leadArray['Betrag']=number_format($Result['total_sum']/100,2,',','.');
				$leadArray['Zahlungsdatum']=date('d-m-Y',strtotime($Result['required_date']));
				$running = 0;
				if($Result['payment_method_id']==13){
					$payment_method_id = 'Six Payment Services';
				} elseif($Result['payment_method_id']==14){
					$payment_method_id = 'Stripe';
				} else {
					$payment_method_id = 'Banküberweisung';
				}
				$leadArray['Zahlungsart']=$payment_method_id;
				$leadArray['Transaktions Ref. Nr.']=$Result['trn_id'];
				$leadArray['Mitgliedschaft']=($Result['article_id']==4 || $Result['total_sum'] > 50000) ? "Premium" : "Basic";
				$leadArray['Laufzeit']=($Result['time']==365) ? "12 Monate" : "6 Monate";
				$leadArray['Mitgliedschaft bis']=date('d-m-Y', ($Result['created']+($Result['time']*86400)));
				$leadArray['Schweizer Kunden']=($Result['vat']==0) ? "No" : "Yes";
				$leadArray['IP Adresse']=$Result['ip_address'];
				$leadArray['Kartenursprung']=$Result['card_origin'];
				$leadArray['Besitzername']=$Result['real_name'];
				$leadArray['Land']=$Result['country_name'];
				fputcsv( $output_handle, $leadArray );
				$i++;
			}

			$leadArray['Rechnung']="";
			$leadArray['Mitgliedsnummer']="";
			$leadArray['Username']="";
			$leadArray['Währung']="";
			$leadArray['Betrag']="";
			$leadArray['Zahlungsdatum']="";
			$leadArray['Zahlungsart']="";
			$leadArray['Transaktions Ref. Nr.']="";
			$leadArray['Mitgliedschaft']="";
			$leadArray['Laufzeit']="";
			$leadArray['Mitgliedschaft bis']="";
			$leadArray['Schweizer Kunden']="";
			$leadArray['IP Adresse']="";
			$leadArray['Kartenursprung']="";
			$leadArray['Besitzername']="";
			$leadArray['Land']="";
			fputcsv( $output_handle, $leadArray );


			$leadArray['Rechnung']="";
			$leadArray['Mitgliedsnummer']="";
			$leadArray['Username']="";
			$leadArray['Währung']="";
			$leadArray['Betrag']="";
			$leadArray['Zahlungsdatum']="";
			$leadArray['Zahlungsart']="";
			$leadArray['Transaktions Ref. Nr.']="";
			$leadArray['Mitgliedschaft']="";
			$leadArray['Laufzeit']="";
			$leadArray['Mitgliedschaft bis']="";
			$leadArray['Schweizer Kunden']="";
			$leadArray['IP Adresse']="";
			$leadArray['Kartenursprung']="";
			$leadArray['Besitzername']="";
			$leadArray['Land']="";
			fputcsv( $output_handle, $leadArray );


			$leadArray['Rechnung']="";
			$leadArray['Mitgliedsnummer']="";
			$leadArray['Username']="Total";
			$leadArray['Währung']='Euro (€)';
			$leadArray['Betrag']=number_format($total/100,2,',','.');
			$leadArray['Zahlungsdatum']="";
			$leadArray['Zahlungsart']="";
			$leadArray['Transaktions Ref. Nr.']="";
			$leadArray['Mitgliedschaft']="";
			$leadArray['Laufzeit']="";
			$leadArray['Mitgliedschaft bis']="";
			$leadArray['Schweizer Kunden']="";
			$leadArray['IP Adresse']="";
			$leadArray['Kartenursprung']="";
			$leadArray['Besitzername']="";
			$leadArray['Land']="";
			fputcsv( $output_handle, $leadArray );

			fclose( $output_handle ); 
			die();
		}
		die();
	}

	public function export_participants($cal_year){
		/*$membershipsql = $this->db->query("SELECT feu_userdetails.user_id as user_id, `username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `time`, `trn_id`, `article_id`, `order_id_masked`, `payment_method_id`, `vat`, `ip_address`, `real_name`, `card_origin`, `country_name`, case when payment_date is NULL then DATE(FROM_UNIXTIME(shop_orders.created)) when payment_date is not NULL then payment_date end as required_date FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `feu_countries` ON `feu_countries`.`country_code` = `feu_userdetails`.`country` WHERE `is_booking` = 0 AND `payed` = 1 AND `username` != '' AND `total_sum` < 140000 AND `shop_orders`.`cancelled` = 0 AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$cal_year." ORDER BY required_date DESC");
		$getMembership = $membershipsql->result_array();*/

		$getEventListData1Sql = $this->db->query("SELECT CASE WHEN `payment_date` is not NULL then`payment_date` WHEN `payment_date` is NULL then DATE(FROM_UNIXTIME(`shop_orders`.`created`)) END as required_date, `username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `title`, `trn_id`, `order_id_masked`, `evt_events`.`id` as `evt_id`, `payment_method_id`, event_unique_id, email,`feu_userdetails`.`user_id` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `shop_booking_details` ON `shop_booking_details`.`cart_id` = `shop_carts`.`id` LEFT JOIN `evt_events` ON `evt_events`.`id` = `shop_booking_details`.`event_id` LEFT JOIN `usr_users` ON `usr_users`.`id` = `feu_userdetails`.`user_id` WHERE `is_booking` = 1 AND `payed` = 1 AND `cancelled` =0 AND event_unique_id = '2020-3' GROUP BY `shop_booking_details`.`cart_id` ORDER BY `shop_orders`.`created` DESC");
		$getEventListData1 = $getEventListData1Sql->result_array();
		//echo $this->db->last_query();

		$getEventListData2Sql = $this->db->query("SELECT CASE WHEN `payment_date` is not NULL then`payment_date` WHEN `payment_date` is NULL then DATE(FROM_UNIXTIME(`shop_orders`.`created`)) END as required_date,`username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `title`, `trn_id`, `order_id_masked`, `evt_events`.`id` as `evt_id`, `payment_method_id`, event_unique_id, email,`feu_userdetails`.`user_id` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `shop_articles_carts` ON `shop_articles_carts`.`cart_id` = `shop_carts`.`id` LEFT JOIN `evt_events` ON `evt_events`.`id` = `shop_articles_carts`.`event_id` LEFT JOIN `usr_users` ON `usr_users`.`id` = `feu_userdetails`.`user_id` WHERE `is_booking` = 1 AND `payed` = 1 AND `shop_orders`.`cancelled` =0 AND `event_id` >0 AND event_unique_id = '2020-3' ORDER BY `shop_orders`.`created` DESC");
		$getEventListData2 = $getEventListData2Sql->result_array();
		//echo $this->db->last_query();die;

		$getCheckinListDataSql = $this->db->query("SELECT * from (SELECT `feu_userdetails`.`username`, `checkin_amount`, `confirmed`, `shop_orders`.`created`, `title`, `trasaction_id`, `order_id_masked`, `evt_events`.`id` as `evt_id`, `checkin_payment_method_id`,event_guest.order_id,`event_guest`.`id`, `event_guest`.`id` as checkin_id,cape, drink_price, `confirmed` as required_date, `event_guest`.`id` as gust_id, event_unique_id, email,`feu_userdetails`.`user_id` FROM `shop_orders` LEFT JOIN `event_guest` ON `event_guest`.`order_id` = `shop_orders`.`order_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`username` = `event_guest`.`username` LEFT JOIN `evt_events` ON `evt_events`.`id` = `event_guest`.`event_id` LEFT JOIN `usr_users` ON `usr_users`.`id` = `feu_userdetails`.`user_id` WHERE `checkin_payed` = 1 AND `checkin_amount` >0 AND `shop_orders`.`cancelled` =0 AND event_unique_id = '2020-3'  ORDER BY `event_guest`.`id` DESC) as a GROUP BY a.`order_id` order by a.id DESC");
		$getCheckinListData = $getCheckinListDataSql->result_array();

		$getEventListData = array_merge($getEventListData1, $getEventListData2, $getCheckinListData);
		//echo $this->db->last_query();die;
		//pr($getEventListData);

		foreach ($getEventListData as $key => $row)
		{
		    $vc_array_name[$key] = $row['required_date'];
		}
		array_multisort($vc_array_name, SORT_DESC, $getEventListData);
		//pr($getEventListData);

        if(!empty($getEventListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Rechnung';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Währung';
			$csv_fields[] = 'Betrag';
			$csv_fields[] = 'Zahlungsdatum';
			$csv_fields[] = 'Event ID';
			$csv_fields[] = 'User ID';
			$csv_fields[] = 'Beschreibung';
			$csv_fields[] = 'Bezeichnung';
			$csv_fields[] = 'Zahlungsart';
			$csv_fields[] = 'Transaktions Ref. Nr.';

			$output_filename = $cal_year.'_Eventbuchungen.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getEventListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Rechnung']=isset($Result['checkin_id']) ? str_replace('CE-', '', $Result['order_id_masked']).'-'.$Result['checkin_id'] : $Result['order_id_masked'];
				if(!empty($Result['username'])){ 
                  	$leadArray['Username']=html_entity_decode($Result['username']);
                } else {
                  	$unames = getUserDataByEmail($Result['email']);
                  	if($unames) {
                    	$leadArray['Username']=$unames;
                  	}
                }
				
				$leadArray['Email']=$Result['email'];
				$leadArray['Währung']='Euro (€)';

				$amount = 0; 
				if(isset($Result['gust_id'])){
					if($Result['gust_id'] < 323) { 
						$amount = number_format(((50*$Result['cape'])+$Result['drink_price']), 2, '.', ''); 
					} else { 
						$amount = number_format($Result['checkin_amount'], 2, '.', ''); 
					}
				} else {
					$amount = number_format($Result['total_sum']/100,2, '.', '');
				}
				

				$leadArray['Betrag']=$amount;

				$leadArray['Zahlungsdatum']=date('Y-m-d',strtotime($Result['required_date']));
				$leadArray['Event ID']='Evt-'.$Result['event_unique_id'];
				$leadArray['User ID']=$Result['user_id'];
				$leadArray['Beschreibung']=isset($Result['confirmed']) ? "Event check-in" : "Eventservice";
				$leadArray['Bezeichnung']=eventDetails($Result['evt_id']);
				if(isset($Result['checkin_payment_method_id'])){
					if($Result['checkin_payment_method_id']==1){
						$payment_method_id = 'Six Payment Services';
					} else if($Result['checkin_payment_method_id']==2){
						$payment_method_id = 'Premium users need not pay';
					} else {
						$payment_method_id = 'Banküberweisung';
					}
				} else {
					if($Result['payment_method_id']==13){
						$payment_method_id = 'Six Payment Services';
					} elseif($Result['payment_method_id']==14){
						$payment_method_id = 'Stripe';
					} else {
						$payment_method_id = 'Banküberweisung';
					}
				}

				$leadArray['Zahlungsart']=$payment_method_id;
				$leadArray['Transaktions Ref. Nr.']=isset($Result['trasaction_id']) ? $Result['trasaction_id'] : $Result['trn_id'];
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
		die();
	}

	public function export_memberships($cal_year){
		$membershipsql = $this->db->query("SELECT feu_userdetails.user_id as user_id, invoiceAddress, `username`, `total_sum`, `payment_date`, `shop_orders`.`created`, `time`, `trn_id`, `article_id`, `order_id_masked`, `payment_method_id`, `vat`, `ip_address`, `real_name`, `card_origin`, `country_name`, case when payment_date is NULL then DATE(FROM_UNIXTIME(shop_orders.created)) when payment_date is not NULL then payment_date end as required_date FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `shop_articles_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `shop_carts`.`user_id` LEFT JOIN `feu_countries` ON `feu_countries`.`country_code` = `feu_userdetails`.`country` WHERE `is_booking` = 0 AND `payed` = 1 AND `total_sum` < 140000 AND `shop_orders`.`cancelled` = 0 AND YEAR(FROM_UNIXTIME(shop_orders.created)) = ".$cal_year." ORDER BY required_date DESC");
		$getMembership = $membershipsql->result_array();

		$getEventListData = array_merge($getMembership);
		//echo $this->db->last_query();die;
		//pr($getEventListData);

		foreach ($getEventListData as $key => $row)
		{
		    $vc_array_name[$key] = $row['required_date'];
		}
		array_multisort($vc_array_name, SORT_DESC, $getEventListData);
		//pr($getEventListData);

        if(!empty($getEventListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Rechnung';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Währung';
			$csv_fields[] = 'Betrag';
			$csv_fields[] = 'Zahlungsdatum';
			$csv_fields[] = 'Unique ID';
			$csv_fields[] = 'Beschreibung';
			$csv_fields[] = 'Bezeichnung';
			$csv_fields[] = 'Zahlungsart';
			$csv_fields[] = 'Transaktions Ref. Nr.';

			$output_filename = $cal_year.'_Membership.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getEventListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Rechnung']=isset($Result['checkin_id']) ? str_replace('CE-', '', $Result['order_id_masked']).'-'.$Result['checkin_id'] : $Result['order_id_masked'];
				if(!empty($Result['username'])){ 
                  	$leadArray['Username']=html_entity_decode($Result['username']);
                } else {
                  	$unames = getUserDataByEmail($Result['invoiceAddress']);
                  	if($unames) {
                    	$leadArray['Username']=$unames;
                  	}
                }
				
				$leadArray['Email']=$Result['invoiceAddress'];
				$leadArray['Währung']='Euro (€)';

				$amount = 0; 
				if(isset($Result['gust_id'])){
					if($Result['gust_id'] < 323) { 
						$amount = number_format(((50*$Result['cape'])+$Result['drink_price']), 2, '.', ''); 
					} else { 
						$amount = number_format($Result['checkin_amount'], 2, '.', ''); 
					}
				} else {
					$amount = number_format($Result['total_sum']/100,2, '.', '');
				}
				

				$leadArray['Betrag']=$amount;

				$leadArray['Zahlungsdatum']=date('Y-m-d',strtotime($Result['required_date']));
				$leadArray['Unique ID']=$Result['user_id'];
				$leadArray['Beschreibung']=isset($Result['confirmed']) ? "Event check-in" : "Membership";
				$leadArray['Bezeichnung']=eventDetails($Result['evt_id']);
				if(isset($Result['checkin_payment_method_id'])){
					if($Result['checkin_payment_method_id']==1){
						$payment_method_id = 'Six Payment Services';
					} else if($Result['checkin_payment_method_id']==2){
						$payment_method_id = 'Premium users need not pay';
					} else {
						$payment_method_id = 'Banküberweisung';
					}
				} else {
					if($Result['payment_method_id']==13){
						$payment_method_id = 'Six Payment Services';
					} elseif($Result['payment_method_id']==14){
						$payment_method_id = 'Stripe';
					} else {
						$payment_method_id = 'Banküberweisung';
					}
				}

				$leadArray['Zahlungsart']=$payment_method_id;
				$leadArray['Transaktions Ref. Nr.']=isset($Result['trasaction_id']) ? $Result['trasaction_id'] : $Result['trn_id'];
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
		die();
	}

	public function export_checkin($cal_year){
		$getEventListDataSql = $this->db->query("SELECT * from (SELECT `feu_userdetails`.`username`, `checkin_amount`, `confirmed`, `shop_orders`.`created`, `title`, `trasaction_id`, `order_id_masked`, `evt_events`.`id` as `evt_id`, `checkin_payment_method_id`,event_guest.order_id,`event_guest`.`id`,cape, drink_price, event_unique_id, invoiceAddress as email, feu_userdetails.user_id FROM `shop_orders` LEFT JOIN `event_guest` ON `event_guest`.`order_id` = `shop_orders`.`order_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`username` = `event_guest`.`username` LEFT JOIN `evt_events` ON `evt_events`.`id` = `event_guest`.`event_id` WHERE `checkin_payed` = 1 AND `checkin_amount` >0 AND `feu_userdetails`.`username` != '' AND `cancelled` =0 AND YEAR(confirmed) = ".$cal_year." ORDER BY `event_guest`.`id` DESC) as a GROUP BY a.`order_id` order by a.id DESC");
		$getEventListData = $getEventListDataSql->result_array();
		//echo $this->db->last_query();die;
		//pr($getEventListData);
        if(!empty($getEventListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Rechnung';
			$csv_fields[] = 'User ID';
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Währung';
			$csv_fields[] = 'Betrag';
			$csv_fields[] = 'Zahlungsdatum';
			$csv_fields[] = 'Event ID';
			$csv_fields[] = 'Bezeichnung';
			$csv_fields[] = 'Zahlungsart';
			$csv_fields[] = 'Transaktions Ref. Nr.';

			$output_filename = $cal_year.'_Checkin_payment.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getEventListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Rechnung']=$Result['order_id_masked'];
				$leadArray['User ID']='USER-'.$Result['user_id'];
				$leadArray['Username']=html_entity_decode($Result['username']);
				$leadArray['Email']=$Result['email'];
				$leadArray['Währung']='Euro (€)';
				$amount = 0; 
				if($Result['id'] < 323) { 
					$amount = number_format(((50*$Result['cape'])+$Result['drink_price']), 2); 
				} else { 
					$amount = number_format($Result['checkin_amount'], 2); 
				}

				$leadArray['Betrag']=$amount;
				$leadArray['Zahlungsdatum']=date('d-m-Y',strtotime($Result['confirmed']));
				$leadArray['Event ID']='Evt-'.$Result['event_unique_id'];
				$leadArray['Bezeichnung']=eventDetails($Result['evt_id']);
				if($Result['checkin_payment_method_id']==1){
					$payment_method_id = 'Six Payment Services';
				} else if($Result['checkin_payment_method_id']==2){
					$payment_method_id = 'Premium users need not pay';
				} else {
					$payment_method_id = 'Banküberweisung';
				}
				$leadArray['Zahlungsart']=$payment_method_id;
				$leadArray['Transaktions Ref. Nr.']=$Result['trasaction_id'];
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
		die();
	}

	public function getcardInfo()
	{
		$order_data = $this->common_model->getAllMultipleJoin('shop_orders',array('payment_method_id'=>13, 'payed'=>1, 'card_alias !='=>''),array(array('usr_users','shop_orders.invoiceAddress = usr_users.email')),'shop_orders. created DESC','','',0,1);
		//pr($order_data);
		/*********LIVE*************/
        $CustomerId = 403547;
        $TerminalId = 17799239; 
        $username = 'API_403547_78643204';
        $password = 'JsonApiPwdAnexus1_a8EpfvCy';   
        /*********LIVE*************/
		if($order_data){
			foreach ($order_data as $key => $value) {
				$JSONObj  = '{
	              "RequestHeader": {
	                "SpecVersion": "1.10",
	                "CustomerId": "'.$CustomerId.'",
	                "RequestId": "aScdFewDSRFrfas2wsad3",
	                "RetryIndicator": 0
	              },
	              "TransactionReference": {
	                "TransactionId": "b0Szb2bU87UztA1W64fKAEQUCbpb"
	              }
	            }';
	            //echo $JSONObj;die;
	            //$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Inquire';
	            $url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Inquire';
	            
	            $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);
	                pr($errorresponse);die;
	                if($errorresponse)
	                {
	                    if($errorresponse['ProcessorMessage'])
	                    {
	                        $fail_reason = $errorresponse['ProcessorMessage'];
	                    }
	                }
	                die($fail_reason);
	            }
	            curl_close($curl);
	            $response = json_decode($jsonResponse, true);
	            if($response)
	            {
	                pr($response);die;
	                $this->common_model->UpdateData('shop_orders',array('real_name'=>$response['PaymentMeans']['Card']['HolderName'], 'card_origin'=>$response['PaymentMeans']['Card']['CountryCode']));
	            }
	            die;
			}
		}  
	}

	public function event_unique_id(){
		$getEventListDataSql = $this->db->query("SELECT id, title, YEAR(FROM_UNIXTIME(time_from)) as year, MONTH(FROM_UNIXTIME(time_from)) as month,event_unique_id FROM `evt_events` WHERE 1 order by YEAR(FROM_UNIXTIME(time_from)) ASC, MONTH(FROM_UNIXTIME(time_from)) ASC");
		$getEventListData = $getEventListDataSql->result_array();
		if($getEventListData){
			$num = 0;
			$year = 2005;
			foreach ($getEventListData as $key => $value) {
				if($year==$value['year']){
					$num = $num + 1;
				} else {
					$num = 1;
				}
				$this->common_model->UpdateData('evt_events',array('event_unique_id'=>$value['year'].'-'.$num),array('id'=>$value['id']));
				$year = $value['year'];
			}
		}
		die;
	}

	public function user_has_unpaid_invoice(){
		$getEventListDataSql = $this->db->query("SELECT `usr_users`.`id`,`feu_userdetails`.`username`,email, total_sum, `shop_orders`.`created` FROM `shop_orders` LEFT JOIN `shop_carts` ON `shop_carts`.`id` = `shop_orders`.`cart_id` LEFT JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` WHERE is_renewed = 1 and payed = 0 GROUP BY `usr_users`.`id` ORDER BY `shop_orders`.`created`");
		$getEventListData = $getEventListDataSql->result_array();
		//echo $this->db->last_query();die;
		//pr($getEventListData);
        if(!empty($getEventListData))
		{
			$csv_fields=array();
			$csv_fields[] = 'Username';
			$csv_fields[] = 'Email';
			$csv_fields[] = 'Total Amount';
			$csv_fields[] = 'Invoice Date';

			$output_filename = 'user_has_unpaid_invoice.csv';
			$output_handle = @fopen( 'php://output', 'w' );
			
			header( 'Content-type: text/csv' );
			header( 'Content-Disposition: attachment; filename=' . $output_filename );
			
			fputcsv( $output_handle, $csv_fields );
			$i=1;
			foreach ($getEventListData as $Result) {
				//$leadArray = (array) $Result; // Cast the Object to an array
				$leadArray['Username']=html_entity_decode($Result['username']);
				$leadArray['Email']=$Result['email'];
				$leadArray['Total Amount']=number_format($Result['total_sum']/100, 2,',', '.'); 
				$leadArray['Invoice Date']=date('d-m-Y',$Result['created']);
				fputcsv( $output_handle, $leadArray );
				$i++;
			}
			fclose( $output_handle ); 
			die();
		}
		die();
	}

	function cron_fires(){
		mail('testdevloper007@gmail.com','Cron Fires again','Cron Fires again');
		die;
	}

	function get_transaction()
	{
		//$order_data = $this->common_model->getAllRowMultipleJoin('shop_orders',array('order_id'=>5341),array(array('usr_users','shop_orders.invoiceAddress = usr_users.email')));
		//pr($order_data);
		/*********TEST*************/
        $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
              },
              "TransactionReference": {
			    "TransactionId": "S41dSOb5rE4SSA0W3SKzbUAQ9h4b"
			  }
            }';

            $url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Inquire';
            
            $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'];
                    }
                }
                //mail('testdevloper007@gmail.com','new cron fail','today saferpay json api');
                //$this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason),array('cart_id'=>$order->cart_id));
                die($fail_reason);
            }
            curl_close($curl);
            $transactionresponse = json_decode($jsonResponse, true);
            
            echo "<pre>";
            print_r($transactionresponse);//die;
        /***********************Create Transaction Direct********************/
            die;
	}
}
	

