<?php
class Email_model extends CI_Model{
	
 	function email_model(){
  		//parent::CI_model();
		$this->load->library('email');		
 	}


//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+GMAIL SMTP
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//		$config['protocol']='smtp';  
//		$config['smtp_host']='ssl://smtp.googlemail.com';  
//		$config['smtp_port']='465';  
//		$config['smtp_timeout']='30';  
//		$config['smtp_user']='info@my-child.co.nz';  
//		$config['smtp_pass']='namibia1'; 
		
//MANDRILL		
//		$config['protocol']='smtp';  
//		$config['smtp_host']='smtp.mandrillapp.com';  
//		$config['smtp_port']='587';  
//		$config['smtp_timeout']='30';  
//		$config['smtp_user']='roland@my.na';  
//		$config['smtp_pass']='d3tAlotpZNobGiCfRk3Miw'; 

	
	
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//SEND ENQUIRY EMAIL
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //HTML 
	function send_enquiry($var)
	{
/*			$config['mailtype'] = 'html';
			$this->email->initialize($config);
			$this->email->from($var['email'],$var['name']);
			//GET CONTACT US EMAIL
			$business = $this->get_contact();
			
			$this->email->reply_to($var['email'],$var['name']);
			$this->email->to($business['contact_email']);
			//$this->email->cc('another@another-example.com'); 
			//$this->email->bcc('them@their-example.com'); 
			//build body
			
			$data['email'] = $var['email'];
			$data['base'] = base_url('/');
			$data['name'] = $var['name'];
			$data['msg'] = $var['body'];
			
			$body1 = $this->load->view('email/body_enquiry',$data , true);
					
			$this->email->subject('Enquiry via the Website');
			$this->email->message($body1); 
			//$this->email->attach('./img/icons/logo.png');
			
			$this->email->send();
			return;*/
		   
		    $this->load->config('mandrill');
	
			$this->load->library('mandrill');
			
			$mandrill_ready = NULL;
			
			try {
			
				$this->mandrill->init( $this->config->item('mandrill_api_key') );
				$mandrill_ready = TRUE;
				//echo 'yes';
			} catch(Mandrill_Exception $e) {
			
				$mandrill_ready = FALSE;
				//echo 'no';
			}

			if( $mandrill_ready ) {
				
				$to = array(array('email' => $var['email_to'] ));
				//Send us some email!
				  $email = array(
					  'html' => $var['body'], //Consider using a view file
					  'text' =>  strip_tags($var['body']),
					  'subject' => $var['subject'],
					  'from_email' => $var['email'],
					  'from_name' => $var['name'],
					  'to' => $to
					  );
					  
				  $result = $this->mandrill->messages_send($email);	
				
			}
			return;
	}
  	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//GET SETTINGS
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //HTML 
	function get_contact()
	{
			$query = $this->db->get('settings');
			$row = $query->row_array();
			return $row;
		
	}

	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	
	//SHOW EMAIL RECIPIENTS
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	

	function show_email_recipients(){
      	
		//$this->db->limit('1000');
		$query = $this->db->get('members');
		if($query->result()){
			echo'<h4>Members</h4>
			<table cellpadding="0" cellspacing="0" style="font-size:12px" border="0" class="table table-striped" id="example" width="100%">
				<thead>
					<tr style="font-weight:bold">
						<th style="width:6%">ID</th>
           				<th style="width:84%">Name </th>
						<th style="width:10%" rel="tooltip" title="Select All"><input type="checkbox" name="selectall" id="selectall"  /></th>
					</tr>
				</thead>
				<tbody>';
			
			foreach($query->result() as $row){
				
				$str = "'".$row->ID."','main'";
				$java = "load_ajax_cat_sub('".$row->member_id."')";
				echo '<tr>
						<td style="width:6%">'.$row->member_id.'</td>
						<td style="width:84%">'.$row->name . ' </td>
					  	<td style="width:10%"><input type="checkbox" class="case" name="recipients['.$row->member_id.']" value="'. $row->member_id.'"></td>
					  </tr>';
			}
			
			
			echo '</tbody>
				</table>
				<hr />
				<div class="clearfix" style="height:30px;"></div>
				<script type="text/javascript">
				$(document).ready(function(){	
					  
					$("#selectall").bind("click", function () {
						  $(".case").attr("checked", this.checked);
						  $(".case").parent().addClass("checked");
					});

					$(".case").click(function(){
				 
						if($(".case").length == $(".caseT:checked").length) {
							$("#selectall").attr("checked", "checked");
						} else {
							$("#selectall").removeAttr("checked");
							 $("#selectall").parent().removeClass("checked");
						}
				 
					});
				});
				</script>';
			
		 }
		  	  
    }	
	
	
	//++++++++++++++++++++++++++++++++++++++++++++
	//SEND EMAIL
	//++++++++++++++++++++++++++++++++++++++++++++	
	function send_email()
	{
		 if($this->session->userdata('admin_id')){
			//GET EMAIL FILDS 	
			$recipients = $this->input->post('recipients',TRUE);
			$subject = $this->input->post('title',TRUE);
			$body = $this->input->post('content',FALSE);		
			$count = 0;
			//ALL SELECTED
			if(isset($_POST['selectall'])){
			
				    $query = $this->db->get('members');
					foreach($query->result() as $row){
					 
					      //BUILD MANDRILL ARRAY  
						  $mandrill = array(array('email' => $row->email ));
						  $business = $this->config->item('site_title');
						  //echo $row->email . '<br />';
						  //SEND MANDRILL
						  $data2['body'] = $body;
						  $body1 = $this->load->view('email/body_news',$data2,true);  
						  $this->send_newsletter_do($body1, $body, $subject, $mandrill, $business);
							
						  $count ++; 
					}	     
				   ////INSERT AS SENT EMAIL INTO EMAILS TABLE
					$data_sent['admin_id'] =  $this->session->userdata('admin_id');
					$data_sent['recipients'] = 'members';
					$data_sent['body'] = $body;
					$data_sent['title'] = $subject;
					$data_sent['status'] = 'sent';
					   
					$this->db->insert('emails',$data_sent);	
				  
				  //SUCCESS MESSAGE
					$this->session->set_flashdata('msg',$count.' emails sent');
					$str = "Successfully sent ".$count." emails.";
				   echo "<script>var options = {'text':'".$str."','layout':'bottomLeft','type':'success'};
						  noty(options);
						   $('#send_email_yes').html('Sent');
						   $('#modal-email').modal('hide');
						  </script>";	
			  
				  
			//ONLY SELECTED
			}elseif(!empty($_POST['recipients'])) {
					  $num = count($_POST['recipients']);
					   foreach($_POST['recipients'] as $value) {
						  
						  $row = $this->get_member($value);					  
						  
						  //BUILD MANDRILL ARRAY  
						  $mandrill = array(array('email' => $row['email'] ));
						  $business = $this->config->item('site_title');
						  //echo $row['email'] . '<br />';
						  //SEND MANDRILL
						  $data2['body'] = $body;
						  $body1 = $this->load->view('email/body_news',$data2,true);  
						  $this->send_newsletter_do($body1, $body, $subject, $mandrill, $business);
							
						  $count ++;    
					   }
					  
					  ////INSERT AS SENT EMAIL INTO EMAILS TABLE
					  $data_sent['admin_id'] =  $this->session->userdata('admin_id');
					  $data_sent['recipients'] = 'members';
					  $data_sent['body'] = $body;
					  $data_sent['title'] = $subject;
				      $data_sent['status'] = 'sent';
						 
					  $this->db->insert('emails',$data_sent);	
					  //LOG ACTION
					  $this->admin_model->system_log('sent_email-'. $count);
					  //SUCCESS MESSAGE
					  $this->session->set_flashdata('msg',$count.' emails sent');
					  $str = "Successfully sent ".$count." emails.";
					 echo "<script>var options = {'text':'".$str."','layout':'bottomLeft','type':'success'};
				            noty(options);
							 $('#send_email_yes').html('Sent');
							 $('#modal-email').modal('hide');
							</script>";	
					
					
			//NO RECIPIENTS SELECTED	  
			}else{
					  
				$this->session->set_flashdata('msg','Please select some recipients.');
				$str = "Please select some recipients.";
			   echo "<script>var options = {'text':'".$str."','layout':'bottomLeft','type':'error'};
					  noty(options);
					   $('#send_email_yes').html('Yes, Send');
					   $('#modal-email').modal('hide');
					  </script>";		
					
					  
			}
				  //echo 'Only selected<br />Recipients: '.$recipients.'<br />Title: ',$subject.'<br />Body: '.$body.'<br />count: '.$count .' = ' .$num; 
  
					
		
		//NOT LOGGED IN
		}else{
			
				redirect('/admin/logout/', 'refresh');	
			  
		 }
		
	}
	//++++++++++++++++++++++++++++++++++++++++++++
	//SEND EMAIL 
	//++++++++++++++++++++++++++++++++++++++++++++	
	function send_newsletter_do($HTML, $TEXT, $subject, $mandrill, $business){

			$this->load->config('mandrill');
	
			$this->load->library('mandrill');
			
			$mandrill_ready = NULL;
			
			try {
			
				$this->mandrill->init( $this->config->item('mandrill_api_key') );
				$mandrill_ready = TRUE;
				//echo 'yes';
			} catch(Mandrill_Exception $e) {
			
				$mandrill_ready = FALSE;
				//echo 'no';
			}
			
			if( $mandrill_ready ) {
				
				//Send us some email!
				  $email = array(
					  'html' => $HTML, //Consider using a view file
					  'text' =>  $TEXT,
					  'subject' => $subject,
					  'from_email' => 'no-reply@my.na',
					  'from_name' => $business,
					  'to' => $mandrill
					  );
					  
				  $result = $this->mandrill->messages_send($email);	
				
			}
			
			
		
	}
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//UPDATE MSG STATUS
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	function update_msg_status($msg_id, $status, $type){
		
		if($type == 'Business'){
			
			$data = array(
               'status' => $status
            );
		
		}else{
			$data = array(
               'status_client' => $status
            );
		
			
		}
         
		$this->db->where('msg_id', $msg_id);
		$this->db->update('u_business_messages', $data);
			
		
	}
	//+++++++++++++++++++++++++++
	//GET MEMBER DETAILS
	//++++++++++++++++++++++++++		 
		 
	function get_member($mem_id){
			
		$test = $this->db->where('member_id', $mem_id);
		$test = $this->db->get('members');
		return $test->row_array();	

	}
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//GET MSG
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	function get_message($msg_id){
		
        $test = $this->db->from('u_business_messages');
		$test = $this->db->where('msg_id', $msg_id);
		//$test = $this->db->where('status', 'unread');
		$test = $this->db->get();
		return $test->row_array();		
		
	}

	//Shorten String
	function shorten_string($phrase, $max_words) {
		
   		$phrase_array = explode(' ',$phrase);
		
   		if(count($phrase_array) > $max_words && $max_words > 0){
		
      		$phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';
		}
			
   		return $phrase;
		
	}

}
?>
