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

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

		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$commentWhere = "(text !='' OR image_path != '')"; 
		$content_data['todaysComments'] = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','',$page,$limit);
		$todaysComments = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id');
		if($this->input->post())
		{
			if($this->input->post('search') && $this->input->post('search_name'))
			{
				$content_data['todaysComments'] = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','',$page,$limit,array('text'=>$this->input->post('search'),'username'=>$this->input->post('search_name')));
				$todaysComments = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','','','',array('text'=>$this->input->post('search'),'username'=>$this->input->post('search_name')));
			}
			if($this->input->post('search_name'))
			{
				$content_data['todaysComments'] = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','',$page,$limit,array('username'=>$this->input->post('search_name')));
				$todaysComments = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','','','',array('username'=>$this->input->post('search_name')));
			}
			if($this->input->post('search'))
			{
				$content_data['todaysComments'] = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','',$page,$limit,array('text'=>$this->input->post('search')));
				$todaysComments = $this->common_model->getAllMultipleJoin('msg_conversations',$commentWhere,array(array('msg_conversations_users','msg_conversations.id = msg_conversations_users.conversation_id'),array('msg_messages','msg_conversations.id = msg_messages.conversation_id'),array('feu_userdetails','feu_userdetails.user_id = msg_messages.from_user_id'),array('sys_files','sys_files.id = feu_userdetails.avatar_file_id')),'msg_messages.created DESC','msg_messages.*,sys_files.filename,sys_files.path,sys_files.extension,msg_messages.text,msg_messages.from_user_id,feu_userdetails.username,msg_conversations.id as msg_id,msg_conversations_users.user_id','','','',array('text'=>$this->input->post('search')));
			}
			//echo $this->db->last_query(); die;
		}
		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/message/alllist/';
		$config['total_rows'] = count($todaysComments);
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);
		//print_r($content_data); die;
		$content_data['link'] = $this->pagination->create_links();

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

				$this->utility->sendCIMail($to,$sub,$bodys);
			/**********************MAIL**************************/
			}
			redirect(base_url().str_replace('-', '/', $uri));
		}
	}
	public function communicator(){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$datas = $this->common_model->getAll('communicator','','','id DESC');
		//echo '<pre>';print_r($datas);
		if(count($datas)>0)
		{
			foreach ($datas as $key => $value) {
				$details = $this->common_model->getAll('communicator_to_user',array('communicator_id'=>$value['id']));
				$datas[$key]['receipent'] = count($details);
				$datas[$key]['open'] = 0;
				$datas[$key]['click'] = 0;
				if($details)
				{
					foreach ($details as $k => $v) {
						$datas[$key]['open'] += $v['open'];
						$datas[$key]['click'] += $v['click'];
					}
				}
			}
		}
		$content_data['datas'] = $datas;
		$data['content'] = $this->load->view('admin/communicator/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function communicator_details($id){
		$content_data = array();
		$id = base64_decode($id);
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['receipent'] = $this->common_model->getAllMultipleJoin('communicator_to_user',array('communicator_id'=>$id),array(array('communicator','communicator.id = communicator_to_user.communicator_id'),array('feu_userdetails','feu_userdetails.user_id = communicator_to_user.user_id')),'date DESC','*, communicator_to_user.open, communicator_to_user.click');
		$data['content'] = $this->load->view('admin/communicator/details', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function send(){
		$content_data = array();
		if($this->input->post())
		{
			$event_id = $this->input->post('event_id');
			if($this->input->post('test'))
			{
				if($this->input->post('sms_msg')==1)
				{
					$attachments = '';
					if($_FILES['file']['name']!='')
					{
						$uploadpath = 'message_big/';
						$filename = $_FILES['file']['name'];
				        $config = array(
				            'upload_path' 		=> FCPATH . $uploadpath . '/',
				            'allowed_types' 	=> 'jpg|gif|png|jpeg|JPG|PNG|pdf|xls|xlsx|txt|doc|docx',
				            'encrypt_name' 		=> false,
				            'file_name'			=> $filename,
				            'file_ext_tolower' 	=> true,
				            //'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
				        );
				        $this->load->library('upload', $config);
				        if(!$this->upload->do_upload('file')) {

				            echo $this->upload->display_errors();
				        }
				        $uploaddata = $this->upload->data();
				        if($uploaddata)
				        {
				        	$attachments = $uploaddata['full_path'];
				        }
				    }

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

						                </div>
		                              </center>
		                           </body>
		                        </html>';
					if($this->input->post('email'))
					{
						$from='info@castleevents.com';
						$email_config = Array(
							'protocol' => 'smtp',
				              'smtp_host' => 'smtp.sendgrid.net',
              				  'smtp_user' => 'apikey',
                              'smtp_pass' => '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',
				              'smtp_port' => 587,
				              'mailtype' => 'html',
				              'priority'=>$this->input->post('priority')?$this->input->post('priority'):3,
				              'crlf' => "rn",
				              'newline' => "rn",
				              'charset' => 'utf-8',
				              'wordwrap' => TRUE
						);

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

                    $array = array(
									'communicator_id'=>$communicator_id,
									'user_id'=>19624,
									'order_id'=>0,
								);
					$this->common_model->insertData('communicator_to_user',$array);
				}
			}
			else
			{
				$eventDetails = $this->common_model->getAllRow('evt_events',array('id'=>$event_id));
				$language_id = $this->input->post('language_id');
				//print_r($language_id);die;
				$attachments = '';
				$filename = '';
				$mimeType = '';
				
				$filecontent = '';
				if($_FILES['file']['name']!='')
				{
					$uploadpath = 'message_big/';
					/*if (!file_exists(FCPATH . $uploadpath)) {
					    mkdir(FCPATH . $uploadpath, 0777, true);
					} */ 
					$filename = $_FILES['file']['name'];
			        $config = array(
			            'upload_path' 		=> FCPATH . $uploadpath . '/',
			            'allowed_types' 	=> 'jpg|gif|png|jpeg|JPG|PNG|pdf|xls|xlsx|txt|doc|docx',
			            'encrypt_name' 		=> false,
			            'file_name'			=> $filename,
			            'file_ext_tolower' 	=> true,
			            //'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
			        );

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

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

			        $uploaddata = $this->upload->data();
			        if($uploaddata)
			        {
			        	$attachments = $uploaddata['full_path'];
			        }
			    }
				if($language_id)
				{
					foreach ($language_id as $key => $language) {
						//$guestlist = $this->common_model->getAllMultipleJoin('shop_booking_details',array('event_id'=>$event_id,'shop_orders.payed'=>1,'email'=>'sayan@digitalaptech.com'),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id'),array('usr_users','usr_users.id = feu_userdetails.user_id')),'shop_booking_details.id DESC','','shop_booking_details.cart_id');
						$guestlist = $this->common_model->getAllMultipleJoin('shop_booking_details',array('event_id'=>$event_id,'shop_orders.payed'=>1,'userlanguage'=>$language),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id'),array('usr_users','usr_users.id = feu_userdetails.user_id')),'shop_booking_details.id DESC','','shop_booking_details.cart_id');
						//echo '<pre>';print_r($guestlist);
						$type = 0;
						if($this->input->post('instant_message') && $this->input->post('email'))
						{
							$type = 1;
						}
						elseif($this->input->post('instant_message'))
						{
							$type = 2;
						}
						elseif($this->input->post('email'))
						{
							$type = 3;
						}
						$array = array(
										'date'=>date('Y-m-d'),
										'category'=>$this->input->post('sms_msg'),
										'title'=>$eventDetails['title'],
										'subject'=>$this->input->post('subject'),
										'message'=>$this->input->post('message'),
										'type'=>$type,
										'send_to_paid_only'=>$this->input->post('send_to')?$this->input->post('send_to'):0,
										'priority'=>$this->input->post('priority')?$this->input->post('priority'):0,
										'event_id'=>$this->input->post('event_id')?$this->input->post('event_id'):0,
										'language_id'=>$language,
										'attachment'=>$attachments,
									);
						$communicator_id = $this->common_model->insertData('communicator',$array);
						if(count($guestlist)>0)
						{
							foreach ($guestlist as $key => $value) 
							{
								$cont='<!DOCTYPE html>
					                    <html>
					                       <head>
					                          <meta charset="utf-8">
					                          <meta name="viewport" content="width=device-width">
					                          <meta http-equiv="X-UA-Compatible" content="IE=edge">
					                          <title>Varification</title>
					                          <style type="text/css">
					                             html,
					                             body {
					                             margin: 0 auto !important;
					                             padding: 0 !important;         
					                             width: 100% !important;
					                             }
					                             
					                             * {
					                             -ms-text-size-adjust: 100%;
					                             -webkit-text-size-adjust: 100%;
					                             }
					                             
					                             div[style*="margin: 16px 0"] {
					                             margin:0 !important;
					                             }
					                             
					                             table,
					                             td {
					                             mso-table-lspace: 0pt !important;
					                             mso-table-rspace: 0pt !important;
					                             }
					                          
					                             table {
					                             border-spacing: 0 !important;
					                             border-collapse: collapse !important;
					                             table-layout: fixed !important;
					                             Margin: 0 auto !important;
					                             }
					                             table table table {
					                             table-layout: auto; 
					                             }
					                           
					                             img {
					                             -ms-interpolation-mode:bicubic;
					                             }
					                            
					                             .mobile-link--footer a,
					                             a[x-apple-data-detectors] {
					                             color:inherit !important;
					                             text-decoration: underline !important;
					                             }
					                             @media only screen and (max-width: 767px)
					                             {
					                             	.content_td{padding: 40px 0 !important; }
					                             }
					                          </style>
					                         
					                          <style>
					                            
					                             .button-td,
					                             .button-a {
					                             transition: all 100ms ease-in;
					                             }
					                             .button-td:hover,
					                             .button-a:hover {
					                             background: #555555 !important;
					                             border-color: #555555 !important;
					                             }
					                          </style>
					                       </head>
					                       <body width="100%" style="Margin: 0;">
		                          <center style="width: 100%;">
		                             <div style="max-width: 90% margin: 40px auto;">
		                               
						                <table cellspacing="0" cellpadding="0" border="0" width="100%">
				                             <tr>
					                                <td class="content_td" style="padding: 40px; font-family: helvetica; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #000;">
					                                   <h2 style="font-weight:normal;">'.getAdminLang('Dear',$value['userlanguage']).' <span style="text-transform:capitalize">'.$value['username'].'</span> 
					                                   </h2>
					                                </td>
					                                <td>
					                                   <a href="'.base_url().'" style="float:right;"><img src="'.base_url().'newsletter_image/crown.gif" width="70" alt="Castleevents" border="0"></a>
					                                </td>
					                             </tr>
					                             <tr>
					                                <td class="content_td" colspan="2" style="font-family: sans-serif; color: #000; padding: 0px 180px 40px 40px; font-size: 16px; line-height: 30px;">
					                                   <p>'.$this->input->post('message').'
					                                   </p>
					                                   <br>
					                                </td>
					                             </tr>
					                             <tr>
					                             	<td class="content_td" colspan="2" align="" style="font-family: sans-serif; color: 000; padding: 20px 40px;">
					                             		<p style="padding-bottom: 20px; margin: 0">'.getAdminLang('Kind_regards',$value['userlanguage']).' </p>
					                             		<p style="padding-bottom: 20px; margin: 0">'.getAdminLang('your_castleevents_team_communicator',$value['userlanguage']).' </p>
					                             		<p style="margin:10px 0 0; font-weight: bold; ">CASTLEEVENTS.COM</p>
					                             		<p style="margin: 5px 0;">The Worlds Leading Eyes Wide Shut Parties</p>
					                             		<p style="margin: 5px 0;">info@castleevents.com | <a href="'.base_url().'">www.castleevents.com </a></p>
					                             	</td>
					                             </tr>
				                          </table>


						                </div>
		                              </center>
		                           </body>
					                        </html>';
								if($this->input->post('sms_msg')==1)
								{
									$mandrill_id = '';
									if($this->input->post('email'))
									{
										$from='info@castleevents.com';
										$email_config = Array(
											'protocol' => 'smtp',
								              'smtp_host' => 'smtp.sendgrid.net',
								              'smtp_user' => 'apikey',
								              'smtp_pass' => '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',
								              'smtp_port' => 587,
								              'mailtype' => 'html',
								              'priority'=>$this->input->post('priority')?$this->input->post('priority'):3,
								              'crlf' => "rn",
								              'newline' => "rn",
								              'charset' => 'utf-8',
								              'wordwrap' => TRUE
										);

										$this->load->library('email');
										$this->email->initialize($email_config);
										$this->email->from($from, 'CASTLEEVENTS');
										//$this->email->bcc('info@castleevents.com','CASTLEEVENTS');
										//$this->email->to('sayan@digitalaptech.com','Andrej'); 
										//$this->email->to('alorenc@me.com','Andrej'); 
										$this->email->to($value['email'],$value['username']); 
										$this->email->subject($this->input->post('subject'));
										$this->email->message($cont);
										if($attachments)
								    	{	
											$this->email->attach($attachments);
										}
										$mail = $this->email->send();
									}
									if($this->input->post('instant_message'))
									{
										$adminDetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('email'=>'info@castleevents.com'),array(array('feu_userdetails','feu_userdetails.user_id = usr_users.id')));
										$meg_conv_instId = $this->common_model->insertData('msg_conversations',array('created'=>time()));
										$meg_conv_user_instId = $this->common_model->insertData('msg_conversations_users',array('conversation_id'=>$meg_conv_instId,'user_id'=>$value['user_id'],'latest_read'=>0));
										$meg_message_instId = $this->common_model->insertData('msg_messages',array('created'=>time(),'conversation_id'=>$meg_conv_instId,'from_user_id'=>$adminDetails['user_id'],'text'=>$this->input->post('message')));
									}
									
							    	$array = array(
													'communicator_id'=>$communicator_id,
													'user_id'=>$value['user_id'],
													'order_id'=>$value['order_id'],
												);
									$this->common_model->insertData('communicator_to_user',$array);

								}
								elseif($this->input->post('sms_msg')==2)
								{
									$to_number = '';
									$userPhones = $this->common_model->getAllRow('usr_phones',array('user_id'=>$value['user_id']));
									if($value['mobile_number']!='')
									{
										if(strpos($value['mobile_number'],'+') === false)
										{
											$to_number = '+'.$value['mobile_number'];
										}
										else
										{
											$to_number = $value['mobile_number'];
										}
									}
									elseif($userPhones)
									{
										if(strpos($userPhones['mobile_number'],'+') === false)
										{
											$to_number = '+'.$userPhones['mobile_number'];
										}
										else
										{
											$to_number = $userPhones['mobile_number'];
										}
									}
									if($to_number!='')
									{
										$url = "https://api.budgetsms.net/sendsms/?username=CASTLE&handle=ba04586987ec104e74b2374f59d51593&userid=18554&msg=".str_replace('%C2%A0','+',urlencode(html_entity_decode(strip_tags($this->character_resolve($this->input->post('message'))),ENT_QUOTES)))."&from=Castle&to=".$to_number; 
										//$url = "https://bulksms.vsms.net/eapi/submission/send_sms/2/2.0?username=Sakrileg&password=ppp79111&message=".str_replace('%C2%A0','+',urlencode(html_entity_decode(strip_tags($this->character_resolve($this->input->post('message'))),ENT_QUOTES)))."&msisdn=".$to_number; 
					                    $curl = curl_init($url);
					                    curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
					                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//raw output
					                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
					                    $result = curl_exec($curl);
					                    if($result)
									    {
									    	$array = array(
															'communicator_id'=>$communicator_id,
															'user_id'=>$value['user_id'],
															'order_id'=>$value['order_id'],
														);
											$this->common_model->insertData('communicator_to_user',$array);
									    }
									}
								}
							}
						}
					}
					@unlink($attachments);
					
				}
			}
			$this->utility->setMsg('Message send successfully','SUCCESS');
			redirect(base_url().'admin/message/send');
		}
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		//$content_data['events'] = $this->common_model->getAll('evt_events',array('id'=>81));
		$content_data['events'] = $this->common_model->getAll('evt_events',array('time_from >'=>time()));
		$content_data['past_events'] = $this->common_model->getAll('evt_events',array('time_from <'=>time()),'','time_from DESC','*','',0,5);
		$data['content'] = $this->load->view('admin/communicator/send', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function character_resolve($body) {
	  $special_chrs = array(
	  'Δ'=>'0xD0', 'Φ'=>'0xDE', 'Γ'=>'0xAC', 'Λ'=>'0xC2', 'Ω'=>'0xDB',
	  'Π'=>'0xBA', 'Ψ'=>'0xDD', 'Σ'=>'0xCA', 'Θ'=>'0xD4', 'Ξ'=>'0xB1',
	  '¡'=>'0xA1', '£'=>'0xA3', '¤'=>'0xA4', '¥'=>'0xA5', '§'=>'0xA7',
	  '¿'=>'0xBF', 'Ä'=>'0xC4', 'Å'=>'0xC5', 'Æ'=>'0xC6', 'Ç'=>'0xC7',
	  'É'=>'0xC9', 'Ñ'=>'0xD1', 'Ö'=>'0xD6', 'Ø'=>'0xD8', 'Ü'=>'0xDC',
	  'ß'=>'0xDF', 'à'=>'0xE0', 'ä'=>'0xE4', 'å'=>'0xE5', 'æ'=>'0xE6',
	  'è'=>'0xE8', 'é'=>'0xE9', 'ì'=>'0xEC', 'ñ'=>'0xF1', 'ò'=>'0xF2',
	  'ö'=>'0xF6', 'ø'=>'0xF8', 'ù'=>'0xF9', 'ü'=>'0xFC',
	  );

	  $ret_msg = '';
	  if( mb_detect_encoding($body, 'UTF-8') != 'UTF-8' ) {
	    $body = utf8_encode($body);
	  }
	  for ( $i = 0; $i < mb_strlen( $body, 'UTF-8' ); $i++ ) {
	    $c = mb_substr( $body, $i, 1, 'UTF-8' );
	    if( isset( $special_chrs[ $c ] ) ) {
	      $ret_msg .= chr( $special_chrs[ $c ] );
	    }
	    else {
	      $ret_msg .= $c;
	    }
	  }
	  return $ret_msg;
	}
	function activity()
	{
		require_once $_SERVER['DOCUMENT_ROOT'].'/Mandrill.php';
		$mandrill = new Mandrill('TveFwCTbtHjorrsBDKwJ8Q');
	    $query = 'full_email:sayan@digitalaptech.com AND subject:test mail sub';
	    $date_from = date('Y-m-d');
	    $date_to = date('Y-m-d');
	    $tags = array();
	    $senders = array();
	    $api_keys = array('TveFwCTbtHjorrsBDKwJ8Q');
	    $limit = 1000;
	    $activity = $mandrill->messages->search($query, $date_from, $date_to, $tags, $senders, $api_keys, $limit);
	    print_r($activity);
	}
	function check_receipent()
	{
		$event_id = $this->input->post('event_id');
		$language_id = $this->input->post('language_id');
		$total = 0;
		$fullTotal = 0;
		if($language_id)
		{
			foreach ($language_id as $key => $language) 
			{
				$guestlist = $this->common_model->getAllMultipleJoin('shop_booking_details',array('event_id'=>$event_id,'shop_orders.payed'=>1,'userlanguage'=>$language),array(array('shop_carts','shop_carts.id = shop_booking_details.cart_id'),array('shop_orders','shop_orders.cart_id = shop_carts.id'),array('feu_userdetails','feu_userdetails.user_id = shop_carts.user_id'),array('usr_users','usr_users.id = feu_userdetails.user_id')),'shop_booking_details.id DESC','','shop_booking_details.cart_id');
				//echo $this->db->last_query();
				$fullTotal = $fullTotal+count($guestlist);
				if($this->input->post('sms_msg')==1)
				{
					$total = $total+count($guestlist);
				}
				elseif($this->input->post('sms_msg')==2)
				{
					if($guestlist)
					{
						foreach ($guestlist as $key => $value) {
							if($value['mobile_number']!='')
							{
								$total = $total+1;
							}
						}
					}
				}
			}
		}
		if($this->input->post('test')==1)
		{
			echo 'Total receipent: 1';
		}
		else
		{
			if($this->input->post('sms_msg')==1)
			{
				echo 'Total receipent: '.$total;
			}
			elseif($this->input->post('sms_msg')==2)
			{
				echo 'Total receipent: '.$total.' (having mobile verified) Out of total guest: '.$fullTotal;
			}
		}
		exit;
	}
}