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

class Communicator_event_booking extends CI_Controller
{
	public function index()
	{
		$this->load->model('common_model');
		$where = "payed = 1 and DATE_FORMAT(FROM_UNIXTIME(shop_orders.created), '%Y-%m-%d') = '".date('Y-m-d')."'";
		$guestlist = $this->common_model->getAllMultipleJoin('shop_booking_details',$where,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');
		$attachments = '';
		//print_r($guestlist);die;
		if($guestlist)
		{
			foreach ($guestlist as $key => $value) {
				
				$communicator_exist = $this->common_model->getAllMultipleJoin('communicator',array('event_id'=>$value['event_id'],'language_id'=>$value['userlanguage']));
				if($communicator_exist)
				{
					foreach ($communicator_exist as $k => $val) {
						$order_exist = $this->common_model->getAllMultipleJoin('communicator_to_user',array('order_id'=>$value['order_id'],'communicator_id'=>$val['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');
						//echo $this->db->last_query();
						//print_r($order_exist);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: 40px auto;">
                               <table cellspacing="0" cellpadding="0" border="0" width="100%" style="max-width: 90%;">
				                    <tr>
				                       <td>
				                          <table cellspacing="0" cellpadding="0" border="0" width="100%">
				                             
				                          	<tr>
				                                <td class="content_td" style="padding: 40px; 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>'.$val['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="margin:10px 0 0; font-weight: bold; ">CASTLEEVENTS.COM</p>
				                             		<p style="margin: 5px 0;">The Worlds Leading Eyes Wide Shut Parties</p>
				                             		<p style="margin: 5px 0;">info@castleevents.com </p>
				                             	</td>
				                             </tr>
				                          </table>
				                       </td>
				                    </tr>
				                </table></div>
                              </center>
                           </body>
                        </html>';
						if(count($order_exist)==0)
						{
							
							if($val['category']==1)
							{
								$mandrill_id = '';
								if($val['type']==3 || $val['type']==1)
								{
									$attachments = $val['attachment'];
								    	$from='noreply@castleevents.com';
										$email_config = Array(
											'protocol' => 'smtp',
								              'smtp_host' => 'smtp.mandrillapp.com',
								              'smtp_user' => 'castleevents',
								              'smtp_pass' => 'TveFwCTbtHjorrsBDKwJ8Q',
								              'smtp_port' => 587,
								              'mailtype' => 'html',
								              'priority'=>$val['priority'],
								              'crlf' => "rn",
								              'newline' => "rn",
								              'charset' => 'utf-8',
								              'wordwrap' => TRUE
										);

										$this->load->library('email');
										$this->email->initialize($email_config);
										$this->email->from($from, 'Castleevents');
										$this->email->to($value['email'],$value['username']); 
										//$this->CI->email->bcc('info@castleevents.com'); 
										$this->email->subject($val['subject']);
										$this->email->message($cont);
										if($attachments!='')
										{
											$this->email->attach($attachments);
										}
										$mail = $this->email->send();
								}
								if($val['type']==2 || $val['type']==1)
								{
									$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'=>$val['message']));
								}
								$array = array(
												'communicator_id'=>$val['id'],
												'user_id'=>$value['user_id'],
												'order_id'=>$value['order_id'],
											);
								$this->common_model->insertData('communicator_to_user',$array);
								//echo $this->db->last_query();
							}
							else
							{
								$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($val['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($val['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'=>$val['id'],
														'user_id'=>$value['user_id'],
														'order_id'=>$value['order_id'],
													);
										$this->common_model->insertData('communicator_to_user',$array);
								    }
								}
							}
						}
					}
				}
			}
		}
		
	}
	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;
	}
}