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

class Alert extends CI_Controller
{
	
	
    function __construct() {
        parent::__construct();
//set_time_limit(0);
				//ini_set('max_execution_time', 0); 
//ini_set('memory_limit','10048M');
  date_default_timezone_set('Africa/Nairobi');

        	$this->load->model('provincemodel','',TRUE);
			        	$this->load->model('usermodel','',TRUE);
$this->load->model('adminusermodel','',TRUE);
	
		$this->load->model('districtmodel','',TRUE);
		$this->load->model('countymodel','',TRUE);
		
		
		$this->load->model('nationmodel','',TRUE);
		$this->load->model('accomodationmodel','',TRUE);
 
 
 
  $this->load->model('systemusermodel','',TRUE);
   $this->load->model('studentprofilemodel','',TRUE);
    $this->load->library('email');
 
 
		
		
    }


	
	
	
	   public function getAttendance()
    {
						  $new_date=date("Y-m-d H:i");
						 						  $currentime=date("H:i");
						if (  $currentime> "08.10"){

		    //  $alerts = $this->usermodel->populateAlerts($mydate,'new');
			$attendance = $this->usermodel->populateall('attendance','timeout',"");

 if(is_array($attendance)) 

 {
	
   foreach($attendance as $result)
						{
       $timeid=$result->id;
	    $updatedata=array(		
		
	'timeout'=>$new_date,
	);
				$this->usermodel->updatedata($updatedata,'attendance','id',$timeid);

						}
 }
 
 
 
 
 
 
						}
 
	}
	
	
		public	function myformatMoney($number, $fractional=false) {
						if ($fractional) {
							$number = sprintf('%.2f', $number);
						}
						while (true) {
							$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1$2', $number);
							if ($replaced != $number) {
								$number = $replaced;
							} else {
								break;
							}
						}
						return $number;
					}
						
	
	
	
	
	
	
	
	
	
	
   public function getAlerts()
    {
		$mydate=date("Y-m-d");
		  $time= date('H:i');
		   $postedtime = date('Y-m-d');
		      $alerts = $this->usermodel->populateAlerts($mydate,'new');
			
 if(is_array($alerts)) 

 {
	
   foreach($alerts as $result) {
       $duetime=$result->duetime;
	          $groupname=$result->groupname;

	   $type=$result->type;
	   if($duetime<=$time){
		 
		   
		   if($type=="single"){
			   $contact=$result->contact;
			    $message=$result->message;
				$mycategoryid=$result->id;
							    $userid=$result->userid;
			    $companyid=$result->companyid;


			   $myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
	
	
	$allcontacts;
	
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			$confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
	
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$postedtime,
				
			
								);
									
			
			
				
			$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=$from&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";

			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				
				
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
				
										$mydata=array(	
										'deliverystatus'=>'sent',
										);
														$usr_result = $this->usermodel->updatedata($mydata,'alerts','id',$mycategoryid);
				echo "SMS SENT";


			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
						redirect('user/viewsms');		
				}
				
			
}
}
			   
			   
			   
			   
		   }else{
			   
			   
			  $confirmgroups= $this->usermodel->confirmgroupsaccount($groupname); 

			  $mymessage=$result->message;
				$mycategoryid=$result->id;
							    $userid=$result->userid;
			    $companyid=$result->companyid;

			
			
			
		
			
			if(is_array($confirmgroups)) {
				   	 
							
						$finalcode="";			
  
  	foreach ($confirmgroups as $row){ 


		$memberid=$row->memberid;
		$viewmember = $this->usermodel->populatmyemember($memberid);
					
					if(is_array($viewmember)) {

   foreach($viewmember as $c){
			 
				 

              

	   $mycontact= $c->phone ; 
	   					   
						   
			 $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						  	   $countmessage =strlen($mymessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$myusername=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$mypassword=$confirmsmsaccount_result[0]['password'];

    // DONE!!! 
											$data=array(		
			'userid'=>$userid,
			
				'contact'=>$mycontact,
			
		  	'message'=>$mymessage,
			
			'companyid'=>$companyid,
			'postedtime'=>$postedtime,
				
			
								);

								

	$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($mypassword) . "&partnerID=" . urlencode($myusername) . "&message=" . urlencode($mymessage) . "&shortcode=$from&mobile=$mycontact";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";


		
		
			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

					$ourdata=array(		
			
			
		  	'deliverystatus'=>'sent',
			 	
				
				
			
								);
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
				$usr_result = $this->usermodel->updatedata($ourdata,'alerts','id',$mycategoryid);
echo "sms sent";
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
						redirect('user/viewsms');		
				}
				

				}
	
	 
	 

}
	
			



}
					
	

}
								
if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewalerts');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewalerts');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewalerts');
			
				
			}






								
								   } 
			   
		   }
		   
		   
		   
		   
		   
		   
		   
	   }else{
		    echo"Bado"; 
	   }






   }
 }
	}
		
	
   public function getAlerts2()
    {
		$mydate=date("Y-m-d");
		  $time= date('H:i');
		   $postedtime = date('Y-m-d');
		      $alerts = $this->usermodel->populateAlerts($mydate,'new');
 if(is_array($alerts)) 

 {
	
   foreach($alerts as $result) {
       $duetime=$result->duetime;
	          $groupname=$result->groupname;

	   $type=$result->type;
	   if($duetime<=$time){
		 
		   
		   if($type=="single"){
			   $contact=$result->contact;
			    $message=$result->message;
				$mycategoryid=$result->id;
							    $userid=$result->userid;
			    $companyid=$result->companyid;


			   $myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
	
	
	$allcontacts;
	
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			$confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
	
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$postedtime,
				
			
								);
									
			
			
				
			$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=$from&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";

			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				
				
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
				
										$mydata=array(	
										'deliverystatus'=>'sent',
										);
														$usr_result = $this->usermodel->updatedata($mydata,'alerts','id',$mycategoryid);
				echo "SMS SENT";


			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
						redirect('user/viewsms');		
				}
				
			
}
}
			   
			   
			   
			   
		   }else{
			   
			   
			  $confirmgroups= $this->usermodel->confirmgroupsaccount($groupname); 

			  $mymessage=$result->message;
				$mycategoryid=$result->id;
							    $userid=$result->userid;
			    $companyid=$result->companyid;

			
			
			
		
			
			if(is_array($confirmgroups)) {
				   	 
							
						$finalcode="";			
  
  	foreach ($confirmgroups as $row){ 


		$memberid=$row->memberid;
		$viewmember = $this->usermodel->populatmyemember($memberid);
					
					if(is_array($viewmember)) {

   foreach($viewmember as $c){
			 
				 

              

	   $mycontact= $c->phone ; 
	   					   
						   
			 $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						  	   $countmessage =strlen($mymessage);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
								 return false;
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$myusername=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$mypassword=$confirmsmsaccount_result[0]['password'];

    // DONE!!! 
											$data=array(		
			'userid'=>$userid,
			
				'contact'=>$mycontact,
			
		  	'message'=>$mymessage,
			
			'companyid'=>$companyid,
			'postedtime'=>$postedtime,
				
			
								);

								

	$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($mypassword) . "&partnerID=" . urlencode($myusername) . "&message=" . urlencode($mymessage) . "&shortcode=$from&mobile=$mycontact";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";


		
		
			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

					$ourdata=array(		
			
			
		  	'deliverystatus'=>'sent',
			 	
				
				
			
								);
				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
				$usr_result = $this->usermodel->updatedata($ourdata,'alerts','id',$mycategoryid);
echo "sms sent";
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
						redirect('user/viewsms');		
				}
				

				}
	
	 
	 

}
	
			



}
					
	

}
								
if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewalerts');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewalerts');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewalerts');
			
				
			}






								
								   } 
			   
		   }
		   
		   
		   
		   
		   
		   
		   
	   }else{
		    echo"Bado"; 
	   }






   }
 }
	
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
  	function pushroomsms($mainmessage,$maincontact,$myview)
	{
 
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 //$userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		// $contact = trim($this->input->post("contact"));
				
				
				
				
				
					$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);




				$userid=$configuration[0]["paymenttypes"];

		$sigature=$configuration[0]["sigature"];

	if($sigature!=""){
		
		$mainmessage=$mainmessage. " ".$sigature;
	}else{
				$mainmessage=$mainmessage;
	}
				
				
				
				
				
				
				
				
				
				
				
				
				
								$contact = htmlspecialchars(trim($maincontact));

		   	  $mymessage = trim($mainmessage);
			
				
				
				
				
				
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			
			 
			 
						   
				
					 
			
				// $xml = "<smslist><sms><user>robiseach</user><password>r12345</password><message>Hi robert Manyala</message><mobiles>25418667391</mobiles><senderid>INFOTEXT</senderid><cdmasenderid>00201009546244</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid><accountusagetypeid>1</accountusagetypeid></sms></smslist>";

			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
//$stop=$confirmaccount_result[0]['stop'];

						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=144){
				
					$COST=1;
				 }else if($countmessage<=304){
					 
					$COST=2;
				 }else if($countmessage<=464){
					$COST=3;
					
				 }
				 else if($countmessage<=624){
					$COST=4;
				
				 }
				 else if($countmessage<=784){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 //redirect($myview);
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		
			
			
			
			
			$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=$from&mobile=$allcontacts";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $finalURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
$finalcode="";

			    if ($output != null) {
        $responseData = json_decode($output, TRUE);


	
	 if(isset($responseData["responses"][0]["response-description"])){
	$finalcode=$responseData["responses"][0]["response-description"];

	} 
	if(isset($responseData["response-description"])){
		
		$finalcode=$responseData["response-description"];
		
	}
 

				if($finalcode=="Success"){
	$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=144){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=304){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=464){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=624){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=784){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} else {

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance.Try again </div>');
								// redirect($myview);
				}
				
			
}
}
			
				if($finalcode=="Success"){	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
								// redirect($myview);
			}else{
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$finalcode .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
								 //redirect($myview);

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  
  
  
  
  
	
	
	
	
	
	
	
	
	
	function bulkinvoice()
    {
		  $createdats = Date('Y-m-d H:i:s') ;
	
	
	

	 $createdat = Date('Y-m-d') ;
		 	 $year = Date('Y') ;
		  $month = Date('m') ;
  $day = Date('d') ;


			 $getplots = $this->accomodationmodel->getplotforbulkinvoice($day);

if(is_array($getplots)) {

   foreach($getplots as $getplotsrow){


 $myduedate = Date('Y-m') ;

	$penaltydate =(($getplotsrow->duedate));
		
			 $duedate = $myduedate."-".$penaltydate;
			

		$companyid =$getplotsrow->companyid;
			$branchid =$getplotsrow->branchid;
			$userid =$getplotsrow->userid;
		   
				$plotno =$getplotsrow->id;
		   
 			  
				
			$description = "Monthy Invoice";
						
         	$transactioncode=0;
		  	
	
		
			 $plots = $this->accomodationmodel->dispalytenantavailable($plotno);
$utilities="";

$i=0;
$plotpayments="";
$result="";
if(is_array($plots)) {

   foreach($plots as $plotsrow){

$plotpayments=$plotsrow->invoicesms;

	$plotutility=$plotsrow->utility;
				
				if($plotutility=="no"){
				$utilities="";
				}else{
				$utilities="and utilities";

				}

$totalinvoice=0;
$paymentdetails="";
  $i++;
    $houserent = $this->accomodationmodel->tenantavailableonly($plotno,$plotsrow->houseno);
if(is_array($houserent)) {

   foreach($houserent as $houserentrow){

	$transactioncode='IN-'.$userid.time().$i;
	
	

	
   $type="";
      $cost=0;
  $tenantid=$houserentrow->tenantid;
   
   $insertcharges = array();
   		
	
				
				
				
				
						$finalvat=0;
			$houseno="";
			 
			 	   	$houserent = $this->accomodationmodel->gethousedetails($plotsrow->plotno,$plotsrow->houseno);
$roomid=$houserent[0]['id'];
				$paymentdetails=$houserent[0]["paymentdetails"];

  $debitcreditdata=array();


		 $vat=$houserent[0]["vat"];
	 $charges = $this->accomodationmodel->getplotcharges($plotno,$roomid);
if(is_array($charges)) {

   foreach($charges as $charges){
	   
	   
	     $type=trim($charges->chargeid);
	     $amount=$charges->cost;
		 
		 	if (!($this->accomodationmodel->checkinvoice($plotsrow->plotno,$plotsrow->houseno,$type,$month,$year))==TRUE )
	{
		
		$totalinvoice=$totalinvoice+ $amount;
		   		  
				  
				  	    if(($type=="1")||($type=="6")) {
								  $mytax=1+($vat/100); 
								 $vatable=($amount/$mytax);
								 $myfinaltax=($amount-$vatable);


								$finalvat= $this->myformatMoney($myfinaltax, true);
							 }else{
								 

								 								$finalvat=0; 

							 }	
				
				  $accountname = $this->usermodel->populatealldataarray('rentalpaymentmethodes','chargeid', $type,'branchid', $branchid);

		$accountno= $accountname[0]['type'];
	
				  
				  $debitcreditdata[]=array( 'userid'=>$userid,'account'=>$accountno,'credit'=>$amount,'description'=>$description,'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $houserentrow->branchid,'companyid'=> $houserentrow->companyid,'type'=>'sales' ,'supplier'=> $houserentrow->tenantid);

				$houseno=$plotsrow->houseno;
				  
				  
			 $insertcharges[]=array(	
						  
               	'vat' => $finalvat,

				'houseno' => $plotsrow->houseno,
				'plotno' => $plotsrow->plotno,
				'type' => $type,
				'tenantid' => $houserentrow->tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
				'amount' => $amount,
					'branchid' => $branchid,
						'companyid' => $companyid,
				'transactioncode' => $transactioncode,
				'month' => $month,
				'year' => $year,
				'duedate' => $duedate,
				'description' => $description
                       	
                                );
								
								
			}			
								
								
	   
   }

if(!empty($insertcharges)){
   $usr_result =$this->db->insert_batch('invoice', $insertcharges); 
	$this->db->insert_batch('debitcredit', $debitcreditdata);

}else{
 $usr_result =0;
	
}







}



        if($usr_result > 0)
	{
		
		if($totalinvoice>0){
								
								$invoicedata = array(
				'houseno' => $plotsrow->houseno,
				
				'amount' => $totalinvoice,
				'plotno' => $plotsrow->plotno,
			
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
					'exactime' => $duedate,
				'userid' => $userid,
					'paidby' => "",
								'paymentmode' => 0,
						'overpayment' => 0,
						'paymentcode' => 0,


								'companyid' => $companyid,

				'description' => $description
			);

					
				$result =	$this->usermodel->add($invoicedata,'receipt');
								
								
						

										$users = $this->usermodel->populateallarray('people','id', $tenantid);
										$currentuserbalance=$users[0]['balance'];
								
								
								
									$myhouserent = $this->accomodationmodel->getbookingbytenant($plotsrow->plotno,$plotsrow->houseno);
									$rentalid=$myhouserent[0]["id"];
										$prvioushousebalance=$myhouserent[0]["totalamount"];
							
									$updatedata = array('totalamount' => ($totalinvoice+$prvioushousebalance),
									
									
									);
									$this->usermodel->updatedata($updatedata,'bookroom','id',$rentalid);
									
															$peopledta = array('balance' => ($totalinvoice+$currentuserbalance),);

						
												$this->usermodel->updatemember($peopledta,$tenantid) ;

$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'debit'=>$totalinvoice,'description'=>$description,'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$plotsrow->houseno ,'supplier'=> $tenantid);
							$this->usermodel->add($debitdata,'debitcredit');



$contact=$users[0]['phone'];

  $correctime = date("d/m/Y", strtotime($createdat));
			   $correctduetime = date("d/m/Y", strtotime($duedate));


		 	$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for rent ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". Your total balance is now Ksh.". ($totalinvoice+$currentuserbalance) ." . Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments;
					
									$myview="";
										

									  $this->pushroomsms($taskmessage,$contact,$myview);









						
		
		}
		
		
		}
		
	}



}


}

	if ($result==true)
			{
				echo "Invoice is added Successfully ";
					 //redirect('bulkinvoice');	
			}
			else
			{
						
				
				echo "Oops! Error. Invoice not added may be because the rooms have been invoiced or no vacant  room available by now. Please try again ";
					// redirect('bulkinvoice');

			}


} 
	
   }	
			 
	
	




}else{
	echo "No plot available";
	
}
}
	
	
	
	
	
	

		
		
			function bulkpenalty()
    {
		  $createdats = Date('Y-m-d H:i:s') ;
	
	
	

	 $createdat = Date('Y-m-d') ;
		 	 $year = Date('Y') ;
		  $month = Date('m') ;
  $day = Date('d') ;


			 $getplots = $this->accomodationmodel->getplotforbulkpenaltyinvoice($day);

if(is_array($getplots)) {

   foreach($getplots as $getplotsrow){


 $myduedate = Date('Y-m') ;

	$penaltydate =(($getplotsrow->duedate));
		
			 $duedate = $myduedate."-".$penaltydate;
			

		$companyid =$getplotsrow->companyid;
			$branchid =$getplotsrow->branchid;
			$userid =$getplotsrow->userid;
		   
				$plotno =$getplotsrow->id;
		   
 			  
				
			$description = "Monthy Penalty Invoice";
						
         	$transactioncode=0;
		  	
		
		
		
		
		
		
		
		
		
		


			$transactioncode=0;
		   
 			  
				$type = 4;
				
						
      
			 
			 		        $plots = $this->accomodationmodel->getplotcoparentbalance($plotno,$duedate,$month,$year);

			 //$plots = $this->accomodationmodel->dispalytenantavailable($plotno);

	 
		$totalinvoice=0;
$bulkinvoice=array();
$bulkreceipt=array();

$bulkbalance=array();
$amount=0;

$i=0;
if(is_array($plots)) {

   foreach($plots as $plotsrow){
	   
	       $i++;
	   


	   
	   
	   
	   
	   
	   
	   			
$confirminvoice=$this->accomodationmodel->checkinvoice($plotno,$plotsrow->houseno,$type,$month,$year);
	  
	  
	
	   	if ($confirminvoice==FALSE )
			{	
			$transactioncode='IN-'.$userid.time().$i;


       $balancepayments = $this->accomodationmodel->getplotbalance($plotno,$plotsrow->houseno,$plotsrow->tenantid,$duedate,$month,$year);

    $rates = $this->usermodel->populateallarray('plot','id', $plotno);

	 $penaltyrates=$rates[0]['penalty'];
	 	 $penaltytype=$rates[0]['penaltytype'];
$tenantid=$plotsrow->tenantid;

    $houserent = $this->accomodationmodel->getmybulkhousedetails($plotno,$plotsrow->houseno);

if($houserent[0]['priority']!=""){
	$mypriority=$houserent[0]['priority'];
}else{
	
		$mypriority=0;
}
	//$transactioncode='IN-'.$userid.time()+1;

							
  
   						
						$paid=$balancepayments[0]['paid'];
						$invoiced=$balancepayments[0]['amount'];
						$balance=$invoiced-	$paid;
							
							
						if($balance >0){
							if($penaltytype=="amount"){
								
															 $myfinalpenalty=($penaltyrates);

							}else{
														 $myfinalpenalty=(($penaltyrates/100)*$balance);
	
								
							}

								$amount= $this->myformatMoney($myfinalpenalty, true);
							
							
							
		 $priority = $this->accomodationmodel->populatealldataarray('plotcharges','plotno', $plotno,'chargeid', 4);
			
						
if($priority[0]['order']){
	$order=$priority[0]['order'];
	
}else{
		$order="0";

}
  // $plotsrow->plotno; 


   	$totalinvoice=$totalinvoice+$amount;
			
			$bulkinvoice[] = array(
				'houseno' => $plotsrow->houseno,
				'plotno' => $plotsrow->plotno,
				'type' => $type,
				'tenantid' => $plotsrow->tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
				'amount' => $amount,
				'order' => $order,
				'transactioncode' => $transactioncode,
				'month' => $month,
					'userid' => $userid,
				'year' => $year,
				'duedate' => $duedate,
				'description' => $description,
					'priority' => $mypriority,
						'companyid' => $companyid,
			);  
				
				
					if($totalinvoice>0){
								
								$bulkreceipt[] = array(
				'houseno' => $plotsrow->houseno,
				
				'amount' => $totalinvoice,
				'plotno' => $plotsrow->plotno,
			
				'transactioncode' => $transactioncode,
				'tenantid' => $plotsrow->tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
					'exactime' => $duedate,
				'userid' => $userid,
					'paidby' => "",
								'paymentmode' => 0,
						'overpayment' => 0,
						'paymentcode' => 0,
				'description' => $description,


								'companyid' => $companyid,

			);
			
			
			
				$users = $this->usermodel->populateallarray('people','id', $tenantid);
						$currentuserbalance=$users[0]['balance'];
								
								
								
								
								
								
									$myhouserent = $this->accomodationmodel->getbookingbytenant($plotsrow->plotno,$plotsrow->houseno);
									$rentalid=$myhouserent[0]["id"];
										$prvioushousebalance=$myhouserent[0]["totalamount"];
			
			
					$bulkbalance[] = array(
				'totalamount' => ($totalinvoice+$prvioushousebalance),
				
				'id' => $rentalid,
		
	

						);
			
				$bulkpeople[] = array(
				'balance' => ($totalinvoice+$currentuserbalance),
				
				'id' => $tenantid,
		
	

						);
			
			
			
			

					
			//	$result =	$this->usermodel->add($invoicedata,'receipt');
								
								
							
		
		}	

			}

   }
}

if(!empty($bulkinvoice)){
	 $usr_result =$this->db->insert_batch('invoice', $bulkinvoice); 

}else{
 $usr_result =0;
	
}



















        if($usr_result > 0)
	{

$this->db->insert_batch('receipt', $bulkreceipt); 


$this->db->update_batch('bookroom',$bulkbalance, 'id');
$this->db->update_batch('people',$bulkpeople, 'id');

		















	
			$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Penalty Invoice is added Successfully ! !!!</div>');
					 redirect('admin/penaltyinvoice?randomitemidentifier1='.$plotno);	
			}
			else
			{
						
				

				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Penalty Invoice not added. Please try again </div>');
				 redirect('admin/penaltyinvoice?randomitemidentifier1='.$plotno);
			}


} else {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">! Error. This building does not have active penalty.Please update the penalty  to be charged for late payment first. </div>');
				 redirect('admin/penaltyinvoice?randomitemidentifier1='.$plotno);
				 
				 }
			 
			 
			
			
			
			
	
			
		}
		}
	}
	
	
	
	
		 public function GetBackup() {

		
		
		
		
			        		$getalldbs = $this->usermodel->populateall('backup','status', "active");

	  	if(is_array($getalldbs)){
	 
	 foreach ($getalldbs as $c){
		 
		 
		 
			  
			  
			  		   $mypath=$c->path;
			 $server=$c->server;

		    $user=$c->user;
			    $password=$c->password;
				    $host=$c->host;
					    $database=$c->database;		 
			  
$local_file = $mypath.date('Y-m-d').$database."-".date('H').".sql";
  //$local_file = $mypath.date('Y-m-d').$database."-".date('H').".gz";
//if(exec(''.$server.'mysqldump.exe --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . ' | gzip > ' . $local_file))

exec(''.$server.'mysqldump.exe --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . '  > ' . $local_file);
	
								
				
						
  
		 
	 }
	 
	 echo "You have successfully done the backup";
		}
		
		
		
		
		
		
		
		


		
		
	
  }
	
	
	
	
	
	
	
	
		 public function GetOnlineBackup() {

		
		
		
		
			        		$getalldbs = $this->usermodel->populateall('backup','status', "active");

	  	if(is_array($getalldbs)){
	 
	 foreach ($getalldbs as $c){
		 
		 
		 
			  
			  
			  		   $mypath=$c->path;
			 $server=$c->server;

		    $user=$c->user;
			    $password=$c->password;
				    $host=$c->host;
					    $database=$c->database;		 
			  
//$local_file = $mypath.date('Y-m-d').$database."-".date('H').".sql";
  $local_file = $mypath.date('Y-m-d').$database."-".date('H').".gz";
//if(exec(''.$server.'mysqldump.exe --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . ' | gzip > ' . $local_file))
    exec('mysqldump --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . ' | gzip > ' . $local_file);

//exec(''.$server.'mysqldump.exe --user='.$user.' --password='.$password.' --host='.$host.' ' . $database . '  > ' . $local_file);
	
		
		
	 }
	 
	 echo "You have successfully done the backup";
	 
	 $headers = "From: support@robisearch.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$to = 'robisearch@gmail.com';
$subject = 'API BACKUPS';
$message .= '<p>Backup complete...</p>';

mail($to, $subject, $message, $headers);
//echo 'Databases backed up...';
		}
		
		
		
		
		
		
		
		


		
		
	
  }
	
	
	
	
	
	
	
	function loadetims()
    {
	
	
	
		
		
		
		  $createdats = Date('Y-m-d H:i:s') ;
	
	$apiUrl = 'https://etims-api.kra.go.ke/etims-api/saveTrnsSales';
	$apiUrl2 = 'https://etims-api.kra.go.ke/etims-api/saveTrnsSalesReceipt';

		$apiUrl3 = 'https://etims-api.kra.go.ke/etims-api/saveStockMaster';


$createdat = Date('Y-m-d') ;
$year = Date('Y') ;
$month = Date('m') ;
$day = Date('d') ;

$companyid=1;


 $currentDateTime =date('YmdHis');
		  
			 $currentDate =date('Ymd');

			$getbranch  = $this->usermodel->populatealldatanoarrayorderbydata('etiminitialization','id > ', 0,'verification <>',"",'id',"ASC" );

  		 // $getbranch= $this->usermodel->populateall('etiminitialization','id >',0);


if(is_array($getbranch)) {

   foreach($getbranch as $getbranchrow){
$branchid =$getbranchrow->branchid;



$kra_pin=trim($getbranchrow->tin);	   
$branch_id=trim($getbranchrow->bhfid);
$sign_key=trim($getbranchrow->cmcKey);
$mrcNo=trim($getbranchrow->mrcNo);
$etimsurl=trim($getbranchrow->url);
$onlineoffline=trim($getbranchrow->onlineoffline);


$pendinginvoice = $this->usermodel->populatealldatanoarrayfiveEtims('sales','salesdump<>',"",'rcptsign<>',"",'companyid', $companyid,'branch',$branchid,'etimsstatus',2);


if(is_array($pendinginvoice)) {

   foreach($pendinginvoice as $etimsdatarow){


 $myduedate = Date('Y-m') ;

	$salesdump =(($etimsdatarow->salesdump));
		
				$salesidinvoice =$etimsdatarow->id;
		$invoice =$etimsdatarow->invoice;

		$companyid =$etimsdatarow->companyid;
		$salesdata =$etimsdatarow->salesdump;
		$Receiptdata =$etimsdatarow->receiptdump;
		$salesdump =$etimsdatarow->salesdump;
		$etimsstatus =$etimsdatarow->etimsstatus;
		$salesdump =$etimsdatarow->salesdump;
		$receiptdump =$etimsdatarow->receiptdump;
		$branchid =$etimsdatarow->branch;
		$sdcId =$etimsdatarow->sdcId;
		$mrcNo =$etimsdatarow->mrcNo;
				$currcptno =$etimsdatarow->currcptno;
		$totrcptno =$etimsdatarow->totrcptno;
		
		$rcptsign =$etimsdatarow->rcptsign;
		$intrldata =$etimsdatarow->intrldata;
		$rcptsign =$etimsdatarow->rcptsign;
		$sdcdatetime =$etimsdatarow->sdcdatetime;
			$itemsstockmaster =$etimsdatarow->itemsstockmaster;
		
  if($etimsstatus =="3"){
	
	  
	    $jsonData = ($salesdata);

        // Initialize cURL session
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch);
					
					//   echo "<br>";
	   
		$all= $response;
	
		//echo "<BR>";
		//Not selling
		
        // Check for cURL errors
		    // Check for cURL errors
            if (curl_errno($ch)) {


							   // $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 ECHO "Error occurred during submitting ETIMS sales :'.curl_error($ch).',Details:'.var_dump($response).'. Try again ";
								
						//  redirect('user/viewsales');
						   

						   
						   return false;
				
				
				
            } else {
				
				
            $responseArray = json_decode($response, true);

//VAR_DUMP($responseArray );

///EXIT;
			$resultCd = $responseArray['resultCd'];
			$resultDt = $responseArray['resultDt'];
			 $resultMsg = $responseArray['resultMsg'];




            if ($resultCd == '000') {
			   
							$updateinvoicedata=array(		
												'etimsstatus'=>2,

												
												
													);
								
								//cccccc
										$this->usermodel->updatedata($updateinvoicedata,'sales','id',$salesidinvoice);   
				
					
					

	   $jsonData2 = ($Receiptdata);
	   
        // Initialize cURL session
        $ch2 = curl_init();
		

        // Set cURL options
        curl_setopt($ch2, CURLOPT_URL, $apiUrl2);
        curl_setopt($ch2, CURLOPT_POST, 1);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, $jsonData2);
        curl_setopt($ch2, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response2 = curl_exec($ch2);	


 $responseArray2 = json_decode($response2, true);

//VAR_DUMP($responseArray );

///EXIT;
			$resultCd2 = $responseArray2['resultCd'];
			$resultDt2 = $responseArray2['resultDt'];
			 $resultMsg2 = $responseArray2['resultMsg'];




            if ($resultCd2 == '000') {

										$updateinvoicedata=array(		
												'etimsstatus'=>1,

												
												
													);
								
								//cccccc
										$this->usermodel->updatedata($updateinvoicedata,'sales','id',$salesidinvoice);   
				
					


$stockmasterqueries = json_decode($itemsstockmaster);	
		if(is_array($stockmasterqueries)) {
		foreach($stockmasterqueries as $query){

	$stockmasterdata = [
		  	'tin' => $query->tin,
            'bhfId' => $query->bhfId,
            "itemCd" => $query->itemCd,
            "rsdQty" => $query->rsdQty,
            "regrId" => $query->regrId,
            "regrNm" => $query->regrNm,
            "modrNm" => $query->modrNm,
            "modrId" => $query->modrId
			
        ];
		
		
		 $jsonData3 = json_encode($stockmasterdata);
						
			$ch3 = curl_init();

        // Set cURL options
        curl_setopt($ch3, CURLOPT_URL, $apiUrl3);
        curl_setopt($ch3, CURLOPT_POST, 1);
        curl_setopt($ch3, CURLOPT_POSTFIELDS, $jsonData3);
        curl_setopt($ch3, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch3);
		//var_dump($response);
		//exit;
        // Check for cURL errors
            if (curl_errno($ch3)) {


				echo "error sending stock master";		
				
				
				
           } else {
				
				
				
            $responseArray3 = json_decode($response, true);


			$resultCd3 = $responseArray3['resultCd'];
			$resultDt3 = $responseArray3['resultDt'];
			 $resultMsg3 = $responseArray3['resultMsg'];

			 if ($resultCd3 == '000') {
				 
				 echo "Stock master submitted";
				 				$updateinvoicedata=array(		
												'etimsstatus'=>1,

												
												
													);
								
								//cccccc
										$this->usermodel->updatedata($updateinvoicedata,'sales','id',$salesidinvoice);   
				
				 
			 }else{
				
				
							echo" Error! Stock master submitted data was not submitted to  ETIMS Due to:. ".$resultMsg3.". Try again";
	
			 
				 
				 
			 }
 
		
			}		   
				
		
			}
				

		}	
		
		
		










			}else{
				
							echo" Error! Receipts data was not submitted to  ETIMS Due to:. ".$resultMsg2.". Try again";
	
			}

		
		
				   
						   
			}else{
			  // $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
				echo" Error! Sales data was not submitted to  ETIMS Due to:. ".$resultMsg.". Try again";
								
							//redirect("user/viewsales");
						   	
				
			}
		
		
		}
  }else{


	   $jsonData2 = ($Receiptdata);
	   
        // Initialize cURL session
        $ch2 = curl_init();
		

        // Set cURL options
        curl_setopt($ch2, CURLOPT_URL, $apiUrl2);
        curl_setopt($ch2, CURLOPT_POST, 1);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, $jsonData2);
        curl_setopt($ch2, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response2 = curl_exec($ch2);	


 $responseArray2 = json_decode($response2, true);

//VAR_DUMP($responseArray );

///EXIT;
			$resultCd2 = $responseArray2['resultCd'];
			$resultDt2 = $responseArray2['resultDt'];
			 $resultMsg2 = $responseArray2['resultMsg'];




            if ($resultCd2 == '000') {

										$updateinvoicedata=array(		
												'etimsstatus'=>1,

												
												
													);
								
								//cccccc
										$this->usermodel->updatedata($updateinvoicedata,'sales','id',$salesidinvoice);   
				
					
				


$stockmasterqueries = json_decode($itemsstockmaster);	
		if(is_array($stockmasterqueries)) {
		foreach($stockmasterqueries as $query){

	$stockmasterdata = [
		  	'tin' => $query->tin,
            'bhfId' => $query->bhfId,
            "itemCd" => $query->itemCd,
            "rsdQty" => $$query->rsdQty,
            "regrId" => $query->regrId,
            "regrNm" => $query->regrNm,
            "modrNm" => $query->modrNm,
            "modrId" => $query->modrId
			
        ];
		
		
		 $jsonData3 = json_encode($stockmasterdata);
						
			$ch3 = curl_init();

        // Set cURL options
        curl_setopt($ch3, CURLOPT_URL, $apiUrl3);
        curl_setopt($ch3, CURLOPT_POST, 1);
        curl_setopt($ch3, CURLOPT_POSTFIELDS, $jsonData3);
        curl_setopt($ch3, CURLOPT_HTTPHEADER,
            array('tin:' . $kra_pin,
                'bhfId:' . $branch_id,
                'cmcKey:' . $sign_key,
                'Content-Type: application/json'

            ));
        curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);

        // Execute the cURL request
        $response = curl_exec($ch3);
		//var_dump($response);
		//exit;
        // Check for cURL errors
            if (curl_errno($ch3)) {


				echo "error sending stock master";		
				
				
				
           } else {
				
				
				
            $responseArray3 = json_decode($response, true);


			$resultCd3 = $responseArray3['resultCd'];
			$resultDt3 = $responseArray3['resultDt'];
			 if ($resultCd3 == '000') {
				 
				 echo "Stock master submitted";
				 				$updateinvoicedata=array(		
												'etimsstatus'=>1,

												
												
													);
								
								//cccccc
										$this->usermodel->updatedata($updateinvoicedata,'sales','id',$salesidinvoice);   
				
				 
			 }
 
		
			}		   
				
		
			}
				

		}	
		


			}else{
			  // $this->session->set_flashdata('msg', '<div class="alert alert-warning fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
				echo" Error! Receipts data was not submitted to  ETIMS Due to:. ".$resultMsg2.". Try again";
								
							//redirect("user/viewsales");
						   	
				
			}

		
		
				   
	


  }	  

   }
	
}else{
	
				echo"No sales or Receipt sales pending for submission to Kra. Try again";
	
}
	}	
	
	}else{
						echo"No active branch or etims has not been activated by Robisearch Ltd. Try again";

		
	}
	}
	
	function bulkpenaltyinvoice()
    {
		  $createdats = Date('Y-m-d H:i:s') ;
	
	
	

	 $createdat = Date('Y-m-d') ;
		 	 $year = Date('Y') ;
		  $month = Date('m') ;
  $day = Date('d') ;


			 $getplots = $this->accomodationmodel->getplotforbulkpenaltyinvoice($day);

if(is_array($getplots)) {

   foreach($getplots as $getplotsrow){


 $myduedate = Date('Y-m') ;

	$penaltydate =(($getplotsrow->duedate));
		
			 $duedate = $myduedate."-".$penaltydate;
			

		$companyid =$getplotsrow->companyid;
			$branchid =$getplotsrow->branchid;
			$userid =$getplotsrow->userid;
		   
				$plotno =$getplotsrow->id;
		   
 			  
				
			$description = "Monthy Invoice";
						
         	$transactioncode=0;
		  	
	
		
			 $plots = $this->accomodationmodel->dispalytenantavailable($plotno);

$i=0;
$result="";
if(is_array($plots)) {

   foreach($plots as $plotsrow){


$totalinvoice=0;

  $i++;
    $houserent = $this->accomodationmodel->tenantavailableonly($plotno,$plotsrow->houseno);
if(is_array($houserent)) {

   foreach($houserent as $houserentrow){

	$transactioncode='IN-'.$userid.time().$i;
	
	
	
   $type="";
      $cost=0;
  $tenantid=$houserentrow->tenantid;
   
   $insertcharges = array();
   		
	
				
				
				
				
						$finalvat=0;
			
			 
			 	   	$houserent = $this->accomodationmodel->gethousedetails($plotsrow->plotno,$plotsrow->houseno);
$roomid=$houserent[0]['id'];
		 $vat=$houserent[0]["vat"];
	 $charges = $this->accomodationmodel->getplotcharges($plotno,$roomid);
if(is_array($charges)) {

   foreach($charges as $charges){
	   
	   
	     $type=trim($charges->chargeid);
	     $amount=$charges->cost;
		 
		 	if (!($this->accomodationmodel->checkinvoice($plotsrow->plotno,$plotsrow->houseno,$type,$month,$year))==TRUE )
	{
		
		$totalinvoice=$totalinvoice+ $amount;
		   		  
				  
				  	    if(($type=="1")||($type=="6")) {
								  $mytax=1+($vat/100); 
								 $vatable=($amount/$mytax);
								 $myfinaltax=($amount-$vatable);


								$finalvat= $this->myformatMoney($myfinaltax, true);
							 }else{
								 

								 								$finalvat=0; 

							 }	
				
				
				
				  
				  
			 $insertcharges[]=array(	
						  
               	'vat' => $finalvat,

				'houseno' => $plotsrow->houseno,
				'plotno' => $plotsrow->plotno,
				'type' => $type,
				'tenantid' => $houserentrow->tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
				'amount' => $amount,
					'branchid' => $branchid,
						'companyid' => $companyid,
				'transactioncode' => $transactioncode,
				'month' => $month,
				'year' => $year,
				'duedate' => $duedate,
				'description' => $description
                       	
                                );
								
								
			}			
								
								
	   
   }

if(!empty($insertcharges)){
   $usr_result =$this->db->insert_batch('invoice', $insertcharges); 

}else{
 $usr_result =0;
	
}







}



        if($usr_result > 0)
	{
		
		if($totalinvoice>0){
								
								$invoicedata = array(
				'houseno' => $plotsrow->houseno,
				
				'amount' => $totalinvoice,
				'plotno' => $plotsrow->plotno,
			
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
					'exactime' => $duedate,
				'userid' => $userid,
					'paidby' => "",
								'paymentmode' => 0,
						'overpayment' => 0,
						'paymentcode' => 0,


								'companyid' => $companyid,

				'description' => $description
			);

					
				$result =	$this->usermodel->add($invoicedata,'receipt');
								
								
						

										$users = $this->usermodel->populateallarray('people','id', $tenantid);
										$currentuserbalance=$users[0]['balance'];
								
								
								
									$myhouserent = $this->accomodationmodel->getbookingbytenant($plotsrow->plotno,$plotsrow->houseno);
									$rentalid=$myhouserent[0]["id"];
										$prvioushousebalance=$myhouserent[0]["totalamount"];
							
									$updatedata = array('totalamount' => ($totalinvoice+$prvioushousebalance),
									
									
									);
									$this->usermodel->updatedata($updatedata,'bookroom','id',$rentalid);
									
															$peopledta = array('balance' => ($totalinvoice+$currentuserbalance),);

						
												$this->usermodel->updatemember($peopledta,$tenantid) ;

$contact=$users[0]['phone'];

  $correctime = date("d/m/Y", strtotime($createdat));
			   $correctduetime = date("d/m/Y", strtotime($duedate));


		 	//$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for Hs No.". $houseno ." on  ". $correctime .". Your total balance is Ksh.". ($totalinvoice+$currentuserbalance) ." . Kindly pay your bills before ". $correctduetime ." to avoid penalty.".$paymentdetails.".".$plotpayments;
			$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for rent and utilities for Hs No.". $houseno ." on ". $correctime .". Your total balance is now Ksh.". ($totalinvoice+$currentuserbalance) ." . Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments;

					
									$myview="";
											$myview="admin/rentinvoice?randomitemidentifier1=".$plotno;

									  $this->pushroomsms($taskmessage,$contact,$myview);













						
		
		}
		
		
		}
		
	}



}


}

	if ($result==true)
			{
				echo "Invoice is added Successfully ";
					 //redirect('bulkinvoice');	
			}
			else
			{
						
				
				echo "Oops! Error. Invoice not added may be because the rooms have been invoiced or no vacant  room available by now. Please try again ";
					// redirect('bulkinvoice');

			}


} 
	
   }	
			 
	
	




}else{
	echo "No plot available";
	
}
}
	
	
	
	
	
	
	
	
	
	
  function verifyinvoice($originalamount,$paymentcode,$createdat,$houseno,$plotno)
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $createdats = Date('Y-m-d H:i:s') ;
	$action ="insert";
		 $paymentid = "";


	// $originalamount = trim($this->input->post("originalamount"));
		
			
								 $this->load->view("template/tableheader");


		//$plotno = $this->input->post("plotno");
		
			//$houseno = $this->input->post("houseno");
		   
		$paymentmode = "4";
	
         			//$paymentcode = $paymentcode;

	
				 $myplotdata=$this->usermodel->populatealldatanoarray('bookroom','houseno', $houseno,'status', "active");
				 				 $tenantid=trim($plotdata[0]['tenantid']);
				 				 $plotno=trim($plotdata[0]['plotno']);

				 
	 $plotdata=$this->usermodel->populateallarray('plot','id', $plotno);
				 $category=trim($plotdata[0]['category']);

		$data['category']=$category;

		
		










	
					if($this->accomodationmodel->checkpayamntacode($paymentcode)==TRUE){

	$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error. That transaction code  has been used. Please try again </div>');
				 redirect('admin/receivepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
							

		return false;

					}
					
				
					 if($paymentid!=""){
									
									     		$paymentdata = $this->usermodel->populateallarray('receipt','id',$paymentid);

	   
	       $currentoverpayment=$paymentdata[0]["overpayment"];
		   if($originalamount>$currentoverpayment){
			   
		  
		   
		   	$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error. The money your paying ('.$originalamount.') is more than the availble overpayemnt ('.$currentoverpayment.') . Try gain with less amount </div>');
				 redirect('admin/receivepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
				 	return false;
					 }
					 }
					 
					 

					 
					 if($paymentcode!=""){
				 $confirmpayment = $this->usermodel->populateallarray('receipt','paymentcode',$paymentcode);
		

	   
	       
		   if($confirmpayment==TRUE){
			   
		  
		   
		   	$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error. That payment code has been used. Try again </div>');
				 redirect('admin/receivepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
				 	return false;
					 }
					 }
					 
					 
			
					 
					 
					$invoiceid = $this->input->post("invoiceid");
					
					
	
		
		//$transactioncode='RC-'.$this->createRandomPassword();
		$transactioncode='RC-'.$userid.time();
		
		
	
			
		   
		
           //$createdat = $this->input->post("createdat");
 		
				 			    $paidby = $this->input->post("mytenantid");

							 
							 						
											$overpayment = $this->input->post("overpayment");
													$amount = $this->input->post("payment");
							 							 $vat = $this->input->post("vat");
							 							// $vat = htmlspecialchars(trim($this->input->post("vat")));

							 							  $commission = $this->input->post("commission");

			$description = "Payment Received";
					

//$mypaymentmode = $this->input->post("paymentmode");
					
				
				
				
				
				
				
				
				




				
				
				
				
					$finaloverpayemnt=0;
					if($overpayment>0){
						
							$finaloverpayemnt=$overpayment;
					}else{
							$finaloverpayemnt=0;
					}
					
					
					
										$users = $this->usermodel->populateallarray('people','id', $tenantid);
										$currentuserbalance=$users[0]['balance'];
																	$contact=$users[0]['phone'];
								
								
								
								
								
									$houserent = $this->accomodationmodel->getbookingbytenant($plotno,$houseno);
									$rentalid=$houserent[0]["id"];
										$prvioushousebalance=$houserent[0]["totalamount"];
									$CURRENTOVERPAYMENTMADE=$houserent[0]["overpayment"];
															 $totalinvoice=0;

					
					
			 		$type = $this->input->post("type");

			  
							 $finalvat=0;
							 	 $finalcommission=0;

							
							
				
			$data = array(
				'houseno' => $houseno,
				
				'amount' => $originalamount,
				'plotno' => $plotno,
			
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'receipt',
				'createdat' => $createdat,
				
				'userid' => $userid,
					'paidby' => $paidby,
								'paymentmode' => $mypaymentmode,
						'overpayment' => $finaloverpayemnt,
						'paymentcode' => $paymentcode,


								'companyid' => $companyid,

				'description' => $description
			);

					
					if($this->usermodel->add($data,'receipt')){
						
						
										

			$count = count($invoiceid);

   for($i=0; $i< $count; $i++) {
	   
	   
	   
	   	 $totalinvoice=$totalinvoice+$amount[$i];
	   
	    
	    if(($type[$i]=="1")||($type[$i]=="6")) {
								 // $mytax=1+($vat/100); 
								 //$vatable=($amount[$i]/$mytax);
								 //$myfinaltax=($amount[$i]-$vatable);
								 $myfinalcommission=(($commission/100)*$amount[$i]);

							$finalcommission= $this->myformatMoney($myfinalcommission, true);
							

							 }else{
								 
															 	 $finalcommission=0;


							 }
	   
	   
	   
	   
	   
	   
	
							 
	   
	           		$totaldata = $this->usermodel->populateallarray('invoice','id',$invoiceid[$i]);

	   $exactinvoice=$totaldata[0]["amount"];
	       $origalpayment=$totaldata[0]["paid"];
	   $finalamount= $origalpayment+$amount[$i];
	   
      $invoicedata=array(
			 'paid' =>$amount[$i],		
	   'amount' =>$exactinvoice,
	   'plotno' =>$totaldata[0]["plotno"],
	   'houseno' =>$totaldata[0]["houseno"],
	   'tenantid' =>$totaldata[0]["tenantid"],
	   'type' =>$totaldata[0]["type"],
	   	   'companyid' =>$totaldata[0]["companyid"],
	   'branchid' =>$totaldata[0]["branchid"],

   'month' =>$totaldata[0]["month"],
	   'year' =>$totaldata[0]["year"],
	   'balance' =>($totaldata[0]["amount"]- $finalamount),
	   
		'transactioncode' => $totaldata[0]["transactioncode"],
'description' => $description,
		'paymentcode' => $transactioncode,
			'paymentdate' => $createdat,
	
							
								);
      $paymentdata=array(
					
	   'paid' =>$finalamount,
	   
	'commission' => $finalcommission,

		'paymentcode' => $transactioncode,
			'paymentdate' => $createdat,
	
							
								);
								if($amount[$i]!=0){
										$usr_result= $this->usermodel->updatedata($paymentdata,'invoice','id',$invoiceid[$i]);
				$result =	$this->usermodel->add($invoicedata,'utilityinvoice');

									
								}
								
			
						

				
		
		
					
       
		
			}
			}	
			
				if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								
									
								
								
								
								
								
								
								
								
								if($paymentid!=""){
									
									     	
	    $finalamountbalance= $currentoverpayment-$originalamount;
	
      $overpaymentdata=array(
					
	   'overpayment' =>$finalamountbalance


							
								);
									
									$this->usermodel->updatedata($overpaymentdata,'receipt','id',$paymentid);
								}
								
								if( $overpayment>0){
					
														     	
	    $finalamountbalance= $CURRENTOVERPAYMENTMADE +$overpayment;
	
								}else{
						  $finalamountbalance= $CURRENTOVERPAYMENTMADE;
	
								}
					
						
									$updatedata = array('totalamount' => ($prvioushousebalance-$totalinvoice),
									'overpayment' => $finalamountbalance,
								
									);
									$this->usermodel->updatedata($updatedata,'bookroom','id',$rentalid);
									
								
															$peopledta = array('balance' => ($currentuserbalance-$totalinvoice),);

						
												$this->usermodel->updatemember($peopledta,$tenantid) ;
								
									$ttbalance=($prvioushousebalance-$totalinvoice);
							
								
								
							
								
										if($originalamount>0){
								
			   $correctime = date("d/m/Y", strtotime($createdat));

if($ttbalance<0){
	$ttbalance=0;
	
}else{
		$ttbalance=	$ttbalance;
	
}
		$myview="";
		 	$taskmessage = "Dear ". $users[0]['firstname'] ."! We have received your payment of Ksh.". $originalamount ." for rent and utilities for Hs No.". $houseno ." on  ". $correctime .". Your total balance is now Ksh.". $ttbalance .".Thank you for your support.";


									$myview="admin/receivepayment?randomitemidentifier=".$houseno."&randomitemidentifier1=".$plotno;
									  $this->pushroomsms($taskmessage,$contact,$myview);
								}
								
										
								
								
								
								
								
								
						$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Payment is posted  Successfully ! !!!</div>');
					 redirect('admin/receivepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);	
								
							}
							else
							{     
	$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Payment not posted. Please try again </div>');
				 redirect('admin/receivepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
							
							
							}
			
			
			
			
							
						
		
	
	

	}
	
  
	
	
	
	
	
	
	
	
	
	
	
	
   public function addsms()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
		 		 $contact = trim($this->input->post("contact"));

		   	  $mymessage = trim($this->input->post("message",TRUE));
			
			// htmlspecialchars($_POST['firstname'])
			 $message = htmlspecialchars($mymessage);
			 
			 
			
			 
			 
			 
			 
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("contact", "Contact", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewsms', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addsms') == "sms")

					   {
						   
				
			
				
			
			$myArray = explode(',', $contact);
foreach($myArray as $allcontacts){
			    $confirmaccount_result = $this->usermodel->confirmaccount($userid);
$totalsms=$confirmaccount_result[0]['totalsms'];
$apiid=$confirmaccount_result[0]['companyid'];
						   
						   $countmessage =strlen($message);
					 $COST="";
				 if($countmessage<=160){
				
					$COST=1;
				 }else if($countmessage<=320){
					 
					$COST=2;
				 }else if($countmessage<=480){
					$COST=3;
					
				 }
				 else if($countmessage<=640){
					$COST=4;
				
				 }
				 else if($countmessage<=800){
					 $COST=5;
					
				 }
												if($confirmaccount_result[0]['totalsms']< $COST){
			
			
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Your account has insufficient balance . Please recharge and try again</div>');
								
								 redirect('user/viewsms');
		}else{
			
			 $confirmsmsaccount_result = $this->usermodel->confirmasmsccount($apiid);
$username=$confirmsmsaccount_result[0]['username'];
$from=$confirmsmsaccount_result[0]['from'];
$password=$confirmsmsaccount_result[0]['password'];
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$allcontacts,
			
		  	'message'=>$message,
			
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
				$url = 'http://sms.robisearch.com/sendsms.jsp?';
			$xml_data ='<?xml version="1.0"?><smslist><sms><user>'.$username.'</user><password>'.$password.'</password><message>'.$message.'</message><mobiles>'.$allcontacts.'</mobiles><senderid>'.$from.'</senderid><cdmasenderid>00201009546310</cdmasenderid><group>-1</group><clientsmsid>0</clientsmsid></sms></smslist>'; 

 
			$ch = curl_init($url);			
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
			curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$output = curl_exec($ch);
			curl_close($ch);
		
				
		try{
			$xml = new SimpleXMLElement($output);
			
			$code="error-code";
			$mydescription="error-description";
			$finalcode=$xml->error->$code;
			$description=$xml->error->$mydescription;
			if($finalcode== 0) {
				$usr_result = $this->usermodel->add($data,'sms');
				
					 $countmessage =strlen($message);
				 if($countmessage<=160){
					$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=320){
					 
					$finaltotalsms=$totalsms-2;
				 }else if($countmessage<=480){
					 $finaltotalsms=$totalsms-3;
					
				 }
				 else if($countmessage<=640){
					 $finaltotalsms=$totalsms-4;
				
				 }
				 else if($countmessage<=800){
					 $finaltotalsms=$totalsms-5;
					
				 }

				$usr_result2 = $this->usermodel->updateusersms($userid,$finaltotalsms);
			}
				
						
			} catch (Exception $e) {
								//echo 'Error occurred during Sending Message: Please check on your internet connection or balance or ',  $e->getMessage(), "\n .Try again ";

				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> Please check on your internet connection or balance..Try again</div>');
							redirect('user/viewsms');		
				}
				
			
}
}
			
	if ($finalcode== 0) {
	
			
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					
			
				redirect('user/viewsms');
			}else if  ($finalcode== $finalcode) {
				
				
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Sending Message!</strong> '.$description .' .SMS  not Sent to  '.$allcontacts .' <a href=' .base_url(). 'user/viewsms> clicke here to go back  </a> </div>');
							redirect('user/viewsms');

			}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>SMS not sent!   </strong> Please check on your internet connection or balance .Try again</div>');
							redirect('user/viewsms');
			
				
			}
			
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

  public function addemail()
    {
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $subject = trim($this->input->post("subject"));

		 		 $email = trim($this->input->post("email"));

		   	  $message = trim($this->input->post("message",TRUE));
			 
		  				  		  $this->form_validation->set_rules("message", "message", "trim|required|xss_clean");

			  		  $this->form_validation->set_rules("email", "email", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      $this->load->view("template/headerpage");

		
		 $this->load->view('userdata/viewemail', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addadvancemail') == "email")

					   {
						   
				
			
				
			
			$myArray = explode(',', $email);
foreach($myArray as $allemail){
			    $confirmaccount_result = $this->usermodel->confirmaccountid($companyid);
 $fromemail=$confirmaccount_result[0]['email'];
 
	$comapany=$confirmaccount_result[0]['businessname'];					   
			
		  
		
   // echo $my_Array.'<br>';  

												$data=array(		
			'userid'=>$userid,
			
				'contact'=>$email,
			
		  	'message'=>$message,
			'subject'=>$subject,
			'companyid'=>$companyid,
			'postedtime'=>$dateposted,
				
			
								);
									
		
 
		$sendEmail=$this->sendEmail($fromemail,$comapany,$allemail,$message,$subject);
				
	
						//$sendEmail=$this->sendEmail($fromemail,$comapany,$allcontacts,$message,$subject);

			if($sendEmail) {
				$usr_result = $this->usermodel->add($data,'email');
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Email   is sent Successfully ! !!!</div>');

					redirect('user/viewemail');
				

			}else{
					$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error occurred during Email Message!</strong> Please check on your internet connection or Email configuration..Try again</div>');
							redirect('user/viewemail');	
			}
				
						
		
				
			
}
} else
					   {
							redirect('login');
					   }		
					 
			}
	    }
    
	
	
	
	
	
	
}
 ?>