<?php
ob_start();

ini_set('display_errors', 'Off');
ini_set('error_reporting', E_ALL);
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {


		function __construct() {

        parent::__construct();

        $this->load->database();
		$this->load->library('encryption');
        	$this->load->model('usermodel','',TRUE);
        	  
		$this->load->model('countymodel','',TRUE);
		$this->load->model('nationmodel','',TRUE);
			$this->load->model('accomodationmodel','',TRUE);

		$this->load->model('adminusermodel','',TRUE);
		$this->load->model("adminusermodel", "login",TRUE);
$this->load->helper('cookie');
      			

		$this->load->dbutil();
		
		$custom_key = 'KENGA';

        $encryption_config = [
            'cipher' => 'aes-256',
            'mode'   => 'cbc',
            'key'    => hash('sha256', $custom_key), 
        ];

        
        $this->encryption->initialize($encryption_config);

    }


	
  	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=".urlencode($from)."&mobile=$allcontacts";

			//$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 createRandomPasswordForLogin() {
	  	$session_data = $this->session->userdata('logged_in');

			$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];

	$chars =  $userid.time()."003232303232023232023456789453242131231425325212312353253256325213213546121425453553245352444343422323";
					  //$chars = '2342355ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-+';

	srand((double)microtime()*100000000);
	$i = 0;
	$pass = '' ;
	while ($i <= 5) {

		$num = rand() % 33;

		$tmp = substr($chars, $num, 1);

		$pass = $pass . $tmp;

		$i++;

	}
	return $pass;
}








public function addnewgatepassNEW()
    {
		
	
		
			$session_data = $this->session->userdata('logged_in');
			 $fromdate = date('Y-m-01 00:00:00');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		// $userid = $data['id'];
		
	 $companyid = 1;
		 				 		// $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");
		 				 		 $userid = $this->input->post("userid");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");

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

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
//$media = $this->input->post("media");
		 		 $phone = $this->input->post("phone");

		 		 

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

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

		    		   	    $membership = $this->input->post("membership");
											   $action = $this->input->post("action");

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

			$idno = $this->input->post("idno");
		 				 		 $name = $this->input->post("name");
		 				 		 $business = $this->input->post("business");

								$vehicleno = $this->input->post("vehicleno");
				 		 		 $vehiclecolor = $this->input->post("vehiclecolor");
				 		 		 $vehiclemodel = $this->input->post("vehiclemodel");
								$location = $this->input->post("location");
		 				 		 $checkindate = $this->input->post("checkindate");
			 				 		 $bookedby = $this->input->post("bookedby");
			 				 		 $courtesy = $this->input->post("courtesy");


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

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

		
		 $this->load->view('userdata/callcenter', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addgatepass') == "gatepass")
					   {
 
	if($membership=="Visitor"){
		
		
			if(trim($bookedby)==""){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED. Kindly enter the details of the person who booked you in. Try again</div>');
								
								 redirect('/gatepass');
				
				
			}
		
	}
 
 
 
 
 
	if($membership=="Courtesy"){
		
		
			if(trim($courtesy)==""){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED. Kindly enter the details of the person who booked you in. Try again</div>');
								
								 redirect('/gatepass');
				
				
			}
		
	}
 
 
 
 
  
	if($membership=="Reciprocating Member"){
		
	$companyid=1;
		$branchid=1;
			$verifyattendance =$this->usermodel->verifyattendance($fromdate,$dateposted,$idno,$companyid,$branchid);
	
		
			if($verifyattendance>=2){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED.You have exhausted your Reciprocating limit for this month, please contact receptionist for check-in.</div>');
								
								 redirect('/gatepass');
								 return false;
				
				
			}
		
	}
 
 
 
  
 if($courtesy !=""){
	 
	 $bookedby=$courtesy;
 }
 
 
 
 
 
 
 
 
 
 
 
 
 		 		 $homeclub = $this->input->post("homeclub");
 $homeclub2 = $this->input->post("homeclub2");
 
 if($business==""){
	 
	  if($homeclub!=""){
		  $business=$homeclub;
	  }else{
		  
		  $business=$homeclub2;
	  }
	 
	 
	 
	 
 }
 
 
 

									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				//'media'=>$media,
				'phone'=>$phone,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 	'idno'=>$idno,
				
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
				'membership'=>$membership,
				'bookedby'=>$bookedby,

			
								);
								
								
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'gatepass');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'gatepass','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
	$myview="gatepass";
								$smscode =  $userid.$this->createRandomPasswordForLogin();
								$Generaltext="Dear ".$name.", of Membership No: ".$subject.". Welcome to the Golf Club. You have checked-in at:. ".$dateposted.". Your Check-in Code is:".$smscode;
						$visitortext="Dear ".$name.", You are booked by Membership No: ".$bookedby.". Welcome to the Golf Club. You have checked-in at:. ".$dateposted.". Your Check-in Code is:".$smscode;


	if($membership=="Visitor"){

		
		

	if($bookedby!=""){
					$mytext="This is to confirm that visitor: ".$name." has checked-in using your member ID at the Golf by. ".$dateposted;
						
			$mycustomer=$this->usermodel->Getmembernumber($bookedby);
			$myphone=$mycustomer[0]['phone'];
					 $this->pushroomsmsNull($mytext,$myphone,$myview);
					  $this->pushroomsmsNull($visitortext,$phone,$myview);
					}
		







							
								
			if(($sendsm=="yes") && ($sms !="")){
												
							
		  //$this->pushroomsmsNull($sms,$phone,$myview);
			//$this->pushroomsmsNull($sms,$phone,$myview,$invoice);
					//$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");



			}				
								
								
								
								
								
								
				}else{

 $this->pushroomsmsNull($Generaltext,$phone,$myview);



				}					
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully checked-in..</div>');	
							redirect('/gatepass');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Checkin  was not completed.. Try again</div>');
								
								 redirect('/gatepass');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	








  public function startcheckinofvisitor() {
$limit=50;
		 $this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
		  $dateposted = date('Y-m-d H:i:s');
		 
		 	 $branchid = $this->input->post("branchid");
		 		 $companyid = $this->input->post("companyid");

		 		 $idno =trim($this->input->post("idno"));
if ($this->input->post('btn_startchekin') == "btn_startchekin")
		{
	
	     
		 
		 		 		 ///$membership = $this->input->post("membership");
		$data['gatepass'] = $this->usermodel->confirmvisitor($idno,$limit);


		 


				$data['idno'] = $idno;							 

								$data['companyid'] = $companyid;
		$data['branchid'] = $branchid;
    	


		
		 $this->load->view('gatepass', $data);
		$this->load->view("template/footerpage");
		
	}else if ($this->input->post('btn_startchekout') == "btn_startchekout")
		{
	
	 $limit=100;
		$mygatepass = $this->usermodel->confirmvisitor($idno,$limit);




 	 $myview="/visitor?branch='.$branchid.'&companyid='.$companyid";


		


					}
	  
	  	$mydata=array(		
			//'updatedby'=>$userid,
			
			//'updateddate'=>$dateposted,

			'status'=>"Closed",

			'checkoutdate'=>$dateposted,

			
								);
	  
	  
								$checkindata=array(		
				//'updatedby'=>$userid,
			
			//'updateddate'=>$dateposted,

			'status'=>"Closed",

			'checkoutdate'=>$dateposted,
													);
								
									 $this->usermodel->updatedatabytwo($checkindata,'checkin','idno',$idno,'status',"Active");

  

		   
  

  				//
							$usr_result = $this->usermodel->updatedata($mydata,'gatepass','idno',$idno);

					 
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
									if($mygatepass!=false){
					$mytext="This is to confirm you have checked out at . ".$dateposted;
						
		
			$myphone=$mygatepass[0]['phone'];
					 $this->pushroomsmsNull($mytext,$myphone,$myview);
				
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully checked Out..</div>');	
																		 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
															
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Visitor  was not Checked out may be because there was no pending chek-out.. Try again</div>');
								
																				 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);

							}
  
  
  
  
  
  
  
  
  
  
  
		
	
					$this->load->view('userdata/printserialcodes',$data);

		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	else{
		echo"Try again";
		
	}
  }












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

   			 $fromdate = date('Y-m-01 00:00:00');

 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		// $userid = $data['id'];
		
	
		 				 		// $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");
		 				 		 $userid = $this->input->post("userid");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");

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

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
//$media = $this->input->post("media");
		 		 $phone = $this->input->post("phone");

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

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

		    		   	    $membership = $this->input->post("membership");
											   $action = $this->input->post("action");
$officename = $this->input->post("officename");
$sendsms = $this->input->post("sendsms");
$sms = trim($this->input->post("sms"));

			$idno = $this->input->post("idno");
		 				 		 $name = $this->input->post("name");
		 				 		 $business = $this->input->post("business");
			 				 		 $courtesy = $this->input->post("courtesy");

								$vehicleno = $this->input->post("vehicleno");
				 		 		 $vehiclecolor = $this->input->post("vehiclecolor");
				 		 		 $vehiclemodel = $this->input->post("vehiclemodel");
								$location = $this->input->post("location");
		 				 		 $checkindate = $this->input->post("checkindate");
			 				 		 $bookedby = $this->input->post("bookedby");
									 	 $branchid = $this->input->post("branchid");
	 $companyid = $this->input->post("companyid");
$invoice = $userid.time()+ 1;
			  		  $this->form_validation->set_rules("checkindate", "checkindate", "trim|required");

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

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

	$verifyattendance=$this->usermodel->Confirmcheckin($branchid,$idno);
	
		
			if($verifyattendance==true){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> CHECK-IN FAILED!! .You had checked-in today and you have not Checked-out. Try check out through admin then try again.</div>');
												 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);

								/// redirect('/gatepass');
								 return false;
				
				
			}



	if($membership=="Visitor"){
		
		
			if(trim($bookedby)==""){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED. Kindly enter the details of the person who booked you in. Try again</div>');
								
												 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
				
				
			}
		
	}
 
 
 
 
 
	if($membership=="Courtesy"){
		
		
			if(trim($courtesy)==""){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED. Kindly enter the details of the person who booked you in. Try again</div>');
								
												 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
				
				
			}
		
	}
 
 
 
 
  
	if($membership=="Reciprocating Member"){
		
	$companyid=1;
		$branchid=1;
			$verifyattendance =$this->usermodel->verifyattendance($fromdate,$dateposted,$idno,$companyid,$branchid);
	
		
			if($verifyattendance>=2){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED.You have exhausted your Reciprocating limit for this month, please contact receptionist for check-in.</div>');
								
												 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
								 return false;
				
				
			}
		
	}
 
 
 
  
 if($courtesy!=""){
	 
	 $bookedby=$courtesy;
 }
 
 
 














$confirmusers=false;

	$confirmusers=$this->usermodel->Getmembedetails($subject,$phone,$idno,$vehicleno,$branchid);
$mycurrentid=$confirmusers[0]['id'];


//var_dump($confirmusers);
//exit;

 
 
 		 		 $homeclub = $this->input->post("homeclub");
 $homeclub2 = $this->input->post("homeclub2");
 
 if($business==""){
	 
	  if($homeclub!=""){
		  $business=$homeclub;
	  }else{
		  
		  $business=$homeclub2;
	  }
	 
	 
	 
	 
 }
 

 
									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				//'media'=>$media,
				'phone'=>$phone,

		  	'status'=>$status,
				 'companyid'=>$companyid,
 'branchid'=>$branchid,
				 	'idno'=>$idno,
					'messageid'=>$invoice,
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
				'membership'=>$membership,
				'bookedby'=>$bookedby,
'category'=>$category,
			
								);
								

								
								 //if($action=="insert"){
									 if($confirmusers==false){
										
	
									$usr_result = $this->usermodel->add($data,'gatepass');
					

							}else{
								
																
						$usr_result = TRUE;

								//($action=="update"){
								//$usr_result = $this->usermodel->updatedata($data,'gatepass','id',$mycurrentid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							

	$mydata = $this->usermodel->populateallarray('gatepass','messageid',$invoice);

								$myid=$mydata[0]["id"];
								
								if($mycurrentid !=""){
									$myid=$mycurrentid;
									
								}
								
								
								

										$checkindata=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				'visitorid'=>$myid,
				'phone'=>$phone,
				'membership'=>$membership,


		'status'=>"Active",
		'companyid'=>$companyid,

				 	'idno'=>$idno,
				
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,
				'branchid'=>$branchid,
				'officename'=>$officename,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
					'bookedby'=>$bookedby,
				'messageid'=>$messageid,
				'media'=>$invoice,
								);
								
								
								
			 $this->usermodel->add($checkindata,'checkin');
		






//																 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
			
								
	$myview="visitor?branch=".$branchid."&companyid=".$companyid."";
	
								$smscode =  $userid.$this->createRandomPasswordForLogin();
								$Generaltext="Dear ".$name.", of Membership No: ".$subject.". Welcome to the Golf Club. You have checked-in at:. ".$dateposted.". Your Check-in Code is:".$smscode;
						$visitortext="Dear ".$name.", You are booked by Membership No: ".$bookedby.". Welcome to the Golf Club. You have checked-in at:. ".$dateposted.". Your Check-in Code is:".$smscode;


	if($membership=="Visitor"){
		
		
		

	if($bookedby!=""){
					$mytext="This is to confirm that visitor: ".$name." has checked-in using your member ID at the Golf by. ".$dateposted;
			$mycustomer=$this->usermodel->Getmembernumber($bookedby);
			$myphone=$mycustomer[0]['phone'];
					 $this->pushroomsmsNull($mytext,$myphone,$myview);
					  $this->pushroomsmsNull($visitortext,$phone,$myview);
					}








							
								
			if(($sendsm=="yes") && ($sms !="")){
												
							
		  //$this->pushroomsmsNull($sms,$phone,$myview);
			//$this->pushroomsmsNull($sms,$phone,$myview,$invoice);
					//$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");



			}				
								
								
								
								
								
								
				}else{

 $this->pushroomsmsNull($Generaltext,$phone,$myview);



				}					
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Checked in  ..</div>');	
												 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED.. Try again</div>');
								
												 redirect('/gatepass?branch='.$branchid.'&companyid='.$companyid);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
  





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

   			 $fromdate = date('Y-m-01 00:00:00');

 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		// $userid = $data['id'];
		
	 $companyid = 1;
		 				 		// $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");
		 				 		 $userid = $this->input->post("userid");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");

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

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
//$media = $this->input->post("media");
		 		 $phone = $this->input->post("phone");


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

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

		    		   	    $membership = $this->input->post("membership");
											   $action = $this->input->post("action");
$officename = $this->input->post("officename");
$sendsms = $this->input->post("sendsms");
$sms = trim($this->input->post("sms"));

			$idno = $this->input->post("idno");
		 				 		 $name = $this->input->post("name");
		 				 		 $business = $this->input->post("business");
			 				 		 $courtesy = $this->input->post("courtesy");

								$vehicleno = $this->input->post("vehicleno");
				 		 		 $vehiclecolor = $this->input->post("vehiclecolor");
				 		 		 $vehiclemodel = $this->input->post("vehiclemodel");
								$location = $this->input->post("location");
		 				 		 $checkindate = $this->input->post("checkindate");
			 				 		 $bookedby = $this->input->post("bookedby");
									  $companyid = $this->input->post("companyid");
									 $branchid = $this->input->post("branchid");

$invoice = $userid.time()+ 1;
			  		  $this->form_validation->set_rules("checkindate", "checkindate", "trim|required");

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

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


	$verifyattendance=$this->usermodel->Confirmcheckin($branchid,$idno);
	
		
			if($verifyattendance==true){
				
				
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> CHECK-IN FAILED!! .You had checked-in today and you have not Checked-out. Try check out through admin then try again.</div>');
		redirect('/gatepass?branch='.$branchid.'&companyid='.$companyid);

								/// redirect('/gatepass');
								 return false;
				
				
			}











$confirmusers=false;

	$confirmusers=$this->usermodel->Getmembedetails($subject,$phone,$idno,$vehicleno,$branchid);
$mycurrentid=$confirmusers[0]['id'];


//var_dump($confirmusers);
//exit;

 
 
 		 		 $homeclub = $this->input->post("homeclub");
 $homeclub2 = $this->input->post("homeclub2");
 
 if($business==""){
	 
	  if($homeclub!=""){
		  $business=$homeclub;
	  }else{
		  
		  $business=$homeclub2;
	  }
	 
	 
	 
	 
 }
 

 
									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				//'media'=>$media,
				'phone'=>$phone,

		  	'status'=>$status,
				 'companyid'=>$companyid,
 'branchid'=>$branchid,
				 	'idno'=>$idno,
					'messageid'=>$invoice,
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
				'membership'=>$membership,
				'bookedby'=>$bookedby,
'category'=>$category,
			
								);
								

								
								 //if($action=="insert"){
									 if($confirmusers==false){
										
	
									$usr_result = $this->usermodel->add($data,'gatepass');
					

							}else{
								
																
						$usr_result = TRUE;

								//($action=="update"){
								//$usr_result = $this->usermodel->updatedata($data,'gatepass','id',$mycurrentid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							

	$mydata = $this->usermodel->populateallarray('gatepass','messageid',$invoice);

								$myid=$mydata[0]["id"];
								
								if($mycurrentid !=""){
									$myid=$mycurrentid;
									
								}
								
								
								

										$checkindata=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				'visitorid'=>$myid,
				'phone'=>$phone,
				'membership'=>$membership,


		'status'=>"Active",
		'companyid'=>$companyid,

				 	'idno'=>$idno,
				
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,
				'branchid'=>$branchid,
				'officename'=>$officename,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
					'bookedby'=>$bookedby,
				'messageid'=>$messageid,
				'media'=>$invoice,
								);
								
								
								
			 $this->usermodel->add($checkindata,'checkin');
		




$getcategoryname = $this->usermodel->populateallarray('services','id',$category);
$getcategorynamess=$getcategoryname[0]["name"];
//							
								
	$myview="gatepass";
								$smscode =  $userid.$this->createRandomPasswordForLogin();
								//$Generaltext="Dear ".$name.", of Membership No: ".$subject.". Welcome to the Golf Club. You have checked-in at:. ".$dateposted.". Your Check-in Code is:".$smscode;
								$Generaltext="Dear ".$name.", You have checked-in at:. ".$dateposted.".Welcome to St. Bakhita school. Learning as we grow . Your Check-in Code is:".$smscode." for ".$getcategorynamess."" ;

						
						
														$visitortext="Dear ".$name.", You have checked-in at:. ".$dateposted.".Welcome to St. Bakhita school. Learning as we grow . Your Check-in Code is:".$smscode." for ".$getcategorynamess."" ;

														//$visitortext="Dear ".$name.", You have checked-in at:. ".$dateposted.".Welcome to St. Bakhita school. Learning as we grow . Your Check-in Code is:".$smscode;

						//$visitortext="Dear ".$name.", You are booked by Membership No: ".$bookedby.". Welcome to the Golf Club. You have checked-in at:. ".$dateposted.". Your Check-in Code is:".$smscode;


	if($membership=="Visitor"){
		
		
		

	if($bookedby!=""){
					$mytext="This is to confirm that visitor: ".$name." has checked-in using your member ID at the Golf by. ".$dateposted;
			$mycustomer=$this->usermodel->Getmembernumber($bookedby);
			$myphone=$mycustomer[0]['phone'];
					 $this->pushroomsmsNull($mytext,$myphone,$myview);
					  $this->pushroomsmsNull($visitortext,$phone,$myview);
					}








							
								
			if(($sendsm=="yes") && ($sms !="")){
												
							
		  //$this->pushroomsmsNull($sms,$phone,$myview);
			//$this->pushroomsmsNull($sms,$phone,$myview,$invoice);
					//$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");



			}				
								
								
								
								
								
								
				}else{

 $this->pushroomsmsNull($Generaltext,$phone,$myview);



				}					
								
								
								
								
								
								
									
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Checked in  ..</div>');	
												 redirect('/visitor?branch='.$branchid.'&companyid='.$companyid);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> FAILED.. Try again</div>');
								
												 redirect('/gatepass?branch='.$branchid.'&companyid='.$companyid);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
  
  
  public function addnewgatepass11111()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		// $userid = $data['id'];
		 $userid = 1;
	 $companyid = 1;
		 				 		// $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");
		 				 		// $userid = $this->input->post("userid");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");

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

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
//$media = $this->input->post("media");
		 		 $phone = $this->input->post("phone");


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

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

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

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

			$idno = $this->input->post("idno");
		 				 		 $name = $this->input->post("name");
		 				 		 $business = $this->input->post("business");

								$vehicleno = $this->input->post("vehicleno");
				 		 		 $vehiclecolor = $this->input->post("vehiclecolor");
				 		 		 $vehiclemodel = $this->input->post("vehiclemodel");
								$location = $this->input->post("location");
		 				 		 $checkindate = $this->input->post("checkindate");
	

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

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

		
		 $this->load->view('userdata/callcenter', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addgatepass') == "gatepass")
					   {
 
									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				//'callername'=>$callername,
				//'media'=>$media,
				'phone'=>$phone,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 	'idno'=>$idno,
				
				'name'=>$name,
				'business'=>$business,
				'vehicleno'=>$vehicleno,
				'vehiclecolor'=>$vehiclecolor,

				'vehiclemodel'=>$vehiclemodel,
				'location'=>$location,
				'checkindate'=>$checkindate,
				
			
								);
								
								
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'gatepass');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'gatepass','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								if(trim($subject)!=""){
					$mytext="This is to confirm that visitor ".$name." has checked-in using your member Id at the Kiambu Golf at. ".$dateposted;
							$myview="gatepass";
							
			$mycustomer=$this->usermodel->Getmembernumber($subject);
			
	
			 $myphone=$mycustomer[0]['phone'];
			
			
					 $this->pushroomsmsNull($mytext,$myphone,$myview);
					}


	
								
			if(($sendsms	=="yes") && ($sms !="")){

									
													
									$myview="gatepass";
		  $this->pushroomsmsNull($sms,$phone,$myview);
			//$this->pushroomsmsNull($sms,$phone,$myview,$invoice);
					//$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");



			}				
								
								
								
								
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Checked-in  ..</div>');	
							redirect('/gatepass');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> You were not able to check-in. Try again</div>');
								
								 redirect('/gatepass');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
  
	
	
  
  public function addnewcalls()
    {
		
		
				
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		// $userid = $data['id'];
		
	 $companyid = 1;
		 				 		 $callername = $this->input->post("callername");
		 				 		 $email = $this->input->post("email");
		 				 		 $userid = $this->input->post("userid");

		 		 $category = $this->input->post("category");
				 		 		 $messageid = $this->input->post("messageid");
				 		 		 $calldate = $this->input->post("calldate");

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

												 		 		 $createddate = $this->input->post("createddate");
		 		 $description = $this->input->post("description");
		 		 $receiver = $this->input->post("receiver");
$media = $this->input->post("media");
		 		 $phone = $this->input->post("phone");


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

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

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

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



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

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

		
		 $this->load->view('userdata/callcenter', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addaddnewcalls') == "calls")
					   {
									
												$data=array(		
			'userid'=>$userid,
			
				'category'=>$category,
				
				'subject'=>$subject,
				'createdate'=>$postedtime,
				'receiver'=>$receiver,
				'email'=>$email,

				'description'=>$description,
				'callername'=>$callername,
				'calldate'=>$calldate,
	'media'=>$media,
				'phone'=>$phone,


		  	'status'=>$status,
				 'companyid'=>$companyid,

				 
				
			
								);
								 if($action=="insert"){
									
							$usr_result = $this->usermodel->add($data,'callcenter');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($data,'callcenter','id',$mycategoryid);

								}
								
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
			if(($sendsms	=="yes") && ($sms !="")){

									
													
									$myview="user/callcenter";
		  $this->pushroomsmsNull($sms,$phone,$myview);
			//$this->pushroomsmsNull($sms,$phone,$myview,$invoice);
					//$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");



			}				
								
								
								
								
								
								
								
								
								
								
								
								
								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Added a new  call details  ..</div>');	
							redirect('/digitalvisitorbook');																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Call  was not added.. Try again</div>');
								
								 redirect('/digitalvisitorbook');
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
  
  	
	public function applyjob()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		$this->load->view('applyjob');
		$this->load->view("template/footerpage");
	}
	
	
	
	public function digitalbook()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategorybox','description','DESC','companyid',1 ,'status','active');

											

													

		$this->load->view('userdata/digitalbook',$data);
		$this->load->view("template/footerpage");
	}
	

	
	public function gatepass()
	{  	
	
	    	 $companyid = 1;

$branchid="1";
	  if (isset($_GET['branch'])){
$branchid=$_GET['branch'];
    
   
    }
    else {
  $branchid="1";
	 
	}
	
	  if (isset($_GET['company'])){
$companyid=$_GET['company'];
    
   
    }
    else {
  $companyid="1";
	 
	}
	 	$data['companyid'] = $companyid;
		$data['branchid'] = $branchid;
	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategorybox','description','DESC','companyid',1 ,'status','active');

											

													

		$this->load->view('gatepass',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function visitor()
	{  	
	
	    	 $companyid = 1;

$branchid="1";
	  if (isset($_GET['branch'])){
$branchid=$_GET['branch'];
    
   
    }
    else {
  $branchid="1";
	 
	}
	
	  if (isset($_GET['company'])){
$companyid=$_GET['company'];
    
   
    }
    else {
  $companyid="1";
	 
	}
	 	$data['companyid'] = $companyid;
		$data['branchid'] = $branchid;
	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");

											

													

		$this->load->view('visitor',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
  
	
	public function box()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
	  		$data['viewsubcategory']  = $this->usermodel->populatealldatanoarrayorderby('productcategorybox','description','DESC','companyid',1 ,'status','active');

											

													

		$this->load->view('userdata/box',$data);
		$this->load->view("template/footerpage");
	}
	

	

    public function postcomments() {
   if (!isset($_GET['myproductcategory'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
			
	  $myproductcategory = trim($_GET['myproductcategory']);
		$data['myproductcategory'] =$myproductcategory;
$categoryname = trim($_GET['categoryname']);
		$data['categoryname'] =$categoryname;
			
	
		$this->load->view('userdata/postcomments',$data);
		$this->load->view("template/footerpage");	
		
	}
	
	
	}
	

		
public function menu()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
			 $postedtime = date('Y-m-d H:i:sa');
				$myip=$this->input->ip_address();

										$data=array(		
			'link'=>"About Us",
			
				'ip'=>$myip,
			
		  	'description'=>"",
			
			'postedtime'=>$postedtime,
				
			
								);
							$usr_result = $this->usermodel->add($data,'traffic');
					




		$data['products']= $this->usermodel->populateall('products','status',"active");
					
		$this->load->view('menu',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
			  public function viewmainstockreportcategory() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
     $itemid = $_GET['randomitemidentifier'];
	
  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");


   			        	
   	
   $type = $_GET['type'];
$data['itemid']=$itemid;


if( $type=="main"){
	
	$data['products']= $this->usermodel->populatealldatawhereMaincategory('products','products.name','ASC','category',$itemid);

}else{

	
	
					//$this->load->view('userdata/viewmainproductstockmain',$data);

}


					
		$this->load->view('menu',$data);
								


	

		
		$this->load->view("template/footerpage");
		
	}
  }
  
	
	
	
	
	
	
	
	
public function start()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagebox");
			 $postedtime = date('Y-m-d H:i:sa');
				$myip=$this->input->ip_address();

										$data=array(		
			'link'=>"About Us",
			
				'ip'=>$myip,
			
		  	'description'=>"",
			
			'postedtime'=>$postedtime,
				
			
								);
							$usr_result = $this->usermodel->add($data,'traffic');
						





						
		$this->load->view('start');
		$this->load->view("template/footerpage");
	}



 public function addcomplain()
    {
		$invoice = rand(100, 999900000).time();
				 $userid = 1;
		 
	 $companyid = 1;
		 		
		 		// $contact = trim($this->input->post("contact"));
				
				
				
				
				
					$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);




				$contacts=$configuration[0]["contact"];
		$automaticsms=$configuration[0]["sendfeedback"];
				$smscompany=$configuration[0]["smscompany"];

							$defualtmessage=$configuration[0]["feedback"];

		
		
		
		
		
		
		
	
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$createddate = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

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

		 		 $description = $this->input->post("description");
					$messageid = $this->input->post("messageid");
					$phone = $this->input->post("phone");
					
					 $location = $this->input->post("location");
					$itemname = $this->input->post("itemname");
					$number = $this->input->post("number");
					
					



		   	  $status = "New";

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

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

		
		 $this->load->view('userdata/postcomments', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addcomplain') == "addcomplain")
					   {
					
									
												$data=array(	


'location'=>$location,
				'number'=>$number,
				'itemname'=>$itemname,												
			'userid'=>1,
			
				'type'=>$type,
				'messageid'=>$messageid,
				'subject'=>$subject,
				'createdate'=>$createddate,

				'serial'=>$phone,
				'description'=>$description,
				'name'=>$name,


		  	//'status'=>"New",
				 'companyid'=>"1",

				  'invoice'=>$invoice,
				
			
								);
								
							$usr_result = $this->usermodel->add($data,'complain');

						
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								

								if($automaticsms=="yes"){
								

									$myview="box";

	if($defualtmessage!=""){
				//$message=$defualtmessage." ".$subject ." ".$description;

		//$message=$defualtmessage." ".$description;
	}else{
		 	//$message = "Hi,a new ". $subject ." has been posted: ". $description ."";
	}
			 	$message = "Hi,a new ". $subject ." has been posted: ". $description ."";
			
	if($smscompany=="Africaistalking"){
		
		 $this->pushsmsafricaistalking($message,$contacts,$myview,$invoice);

	} else if($smscompany=="Infobip"){
		  	  $this->pushsmsinfobip($message,$contacts,$myview,$invoice);

		
	}else{

			$this->pushroomsmsNull($message,$contacts,$myview,$invoice);

		
	}


								}
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully  Posted '.  $subject .' ..</div>');	
							redirect("box" );																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> '.  $subject .'  was not posted.. Try again</div>');
							redirect("box" );																
							
}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

	

  


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 generateLiveToken() {
     header("Content-Type:application/json");
    $accessToken = "";
    $status = 0;
    $description = "";
	
	
		$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$myconsumer_key=$configuration[0]["consumer_key"];
		$myconsumer_secret=$configuration[0]["consumer_secret"];
	
	// $consumer_key = "UYlkylGuzGjZxpMNz2rmGGYc6N5wslzp";
   // $consumer_secret = "HSGog9FsAchErCLj";
	
	
    $consumer_key =$myconsumer_key;
    $consumer_secret = $myconsumer_secret;
    if (!isset($consumer_key) || !isset($consumer_secret)) {
        die("please declare the consumer key and consumer secret as defined in the documentation");
    }
    $url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    $credentials = base64_encode($consumer_key . ':' . $consumer_secret);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $curl_response = curl_exec($curl);

    if ($curl_response != false) {
        $responseVals = json_decode($curl_response, true);

        $accessToken = $responseVals['access_token'];
        $status = 1;
    } else {
        $description = "Curl Failed: " . curl_error($curl);
    }

    $array = array('token' => $accessToken);

    return json_encode($array);
	
}

	
	
	
	
	public function generateLiveToken2() {
     header("Content-Type:application/json");
    $accessToken = "";
    $status = 0;
    $description = "";
	
	
		//$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		//$myconsumer_key=$configuration[0]["consumer_key"];
		//$myconsumer_secret=$configuration[0]["consumer_secret"];
	
	 $consumer_key = "fTCbi9OkJ3L7s7kXCxwiBdO3FE4FSESL";
    $consumer_secret = "4GixSPBH7Q2D4zBV";
	
	
    //$consumer_key =$myconsumer_key;
    //$consumer_secret = $myconsumer_secret;
    if (!isset($consumer_key) || !isset($consumer_secret)) {
        die("please declare the consumer key and consumer secret as defined in the documentation");
    }
    $url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    $credentials = base64_encode($consumer_key . ':' . $consumer_secret);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $curl_response = curl_exec($curl);

    if ($curl_response != false) {
        $responseVals = json_decode($curl_response, true);

        $accessToken = $responseVals['access_token'];
        $status = 1;
    } else {
        $description = "Curl Failed: " . curl_error($curl);
    }

    $array = array('token' => $accessToken);

    return json_encode($array);
	
}

	
	
	
	
	
	
	public function RegisterUrl2(){
		
		$ShortCode="4078237";
		
		$ConfirmationURL="https://zuritips.com/payment.php";
		$ValidationURL="https://zuritips.com/verifypayment.php";

//include('init.inc.php');

//date_default_timezone_set('Africa/Nairobi');



$accessVals = json_decode($this->generateLiveToken2(), true);

$nowRequest = date('Y-m-d H:i:s');
$accessToken = $accessVals['token'];
$url = 'https://api.safaricom.co.ke/mpesa/c2b/v1/registerurl';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization: Bearer ' . $accessToken)); //setting custom header

//
  // 'ConfirmationURL' => 'https://zuritips.com/payment.php',
   // 'ValidationURL' => 'https://zuritips.com/verifypayment.php'

$curl_post_data = array(
    'ShortCode' => $ShortCode, 
    'ResponseType' => 'application/json',
		
    'ConfirmationURL' => $ConfirmationURL,
    'ValidationURL' => $ValidationURL,
	
	
 
);

	$data_string = json_encode($curl_post_data);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

$curl_response = curl_exec($curl);
print($curl_response);
	exit;
	}
	
	
	
	
	
	
	
	
	public function RegisterUrl(){
		
		$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$ShortCode=$configuration[0]["shortcode"];
		//$ResponseType=$configuration[0]["ResponseType"];
		$ConfirmationURL=$configuration[0]["confirmationurl"];
		$ValidationURL=$configuration[0]["validationurl"];
		$ResponseType="Completed";

//include('init.inc.php');

//date_default_timezone_set('Africa/Nairobi');



$accessVals = json_decode($this->generateLiveToken(), true);

$nowRequest = date('Y-m-d H:i:s');
$accessToken = $accessVals['token'];
$url = 'https://api.safaricom.co.ke/mpesa/c2b/v2/registerurl';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization: Bearer ' . $accessToken)); //setting custom header
//"ResponseType": "[Cancelled/Completed]",



$curl_post_data = array(
    'ShortCode' => $ShortCode, 
    'ResponseType' => $ResponseType,
    'ConfirmationURL' => $ConfirmationURL,
    'ValidationURL' => $ValidationURL,
	
	
 
);

$data_string = json_encode($curl_post_data);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

$curl_response = curl_exec($curl);
print($curl_response);
	}
	
	
	
	public function RegisterUrl1(){
		
		$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$ShortCode=$configuration[0]["shortcode"];
		$ResponseType=$configuration[0]["ResponseType"];
		$ConfirmationURL=$configuration[0]["confirmationurl"];
		$ValidationURL=$configuration[0]["validationurl"];

//include('init.inc.php');

//date_default_timezone_set('Africa/Nairobi');



$accessVals = json_decode($this->generateLiveToken(), true);

$nowRequest = date('Y-m-d H:i:s');
$accessToken = $accessVals['token'];
$url = 'https://api.safaricom.co.ke/mpesa/c2b/v2/registerurl';

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization: Bearer ' . $accessToken)); //setting custom header

//
  // 'ConfirmationURL' => 'https://pos.wifimatt.com/getpayment',
   // 'ValidationURL' => 'https://pos.wifimatt.com/verifypayment'

$curl_post_data = array(
    'ShortCode' => $ShortCode, 
    'ResponseType' => 'application/json',
		
    'ConfirmationURL' => $ConfirmationURL,
    'ValidationURL' => $ValidationURL,
	
	
 
);

$data_string = json_encode($curl_post_data);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

$curl_response = curl_exec($curl);
print($curl_response);
	exit;
	}
		public function oldserialno()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		$this->load->view('userdata/pages');
		//$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
	
	
	public function getpaymentpesapal()
	{ 

	$TransTime = $jdata["transaction_date"];
		 //$correctime = date("Y-m-d H:i:s", strtotime($TransTime));
		  $correctime = Date('Y-m-d H:i:s') ;



		
		$postData = file_get_contents('php://input');
    //log file

    //Parse payload to json
    $jdata = json_decode($postData, true);

	




	
	
	//This is the data from mpesa
   $TransactionType = $jdata["payment_option"];
   $TransID = $jdata["confirmation_code"];

    $TransAmount = $jdata["amount"];
   $BusinessShortCode = "1001";
    $BillRefNumber = $jdata["merchant_reference"];
   //$InvoiceNumber = $jdata["InvoiceNumber"];
    $MSISDN = $jdata["phone"];
    $FirstName = $jdata["first_name"];
  //$MiddleName = $jdata["MiddleName"];
    $LastName = $jdata["last_name"];
       //. $OrgAccountBalance = $jdata["OrgAccountBalance"];

		



	$configuration= $this->usermodel->populateallarray('smsconfig','id',1);

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

if($restricttill=="yes"){


	$tillsdetails= $this->usermodel->populateallarray('tills','name',$BusinessShortCode);

	
	
	if($tillsdetails[0]["branchid"]==""){
		$branchid="1";	
		
	}else{
	$branchid=$tillsdetails[0]["branchid"];	
		
	}


}else{
			$branchid="1";

}


/*

			$savedataKOPOKOPO=array(	
			'transactionType'=>$jdata["type"],
			'branchid'=>$branchid,

			'amount'=>$jdata["amount"],
				//'txn_time'=>$jdata,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$jdata["reference"],
							//'OrgAccountBalance'=>$OrgAccountBalance,

				'firstname'=>$jdata["sender_first_name"],
				'middlename'=>$jdata["sender_middle_name"],
				'lastname'=>$jdata["sender_last_name"],
				'sender_number'=>$jdata["sender_phone_number"],
				//'account_number'=>$BillRefNumber,
				'business_shortcode'=>$jdata["till_number"],

		
								);



*/


  if($TransAmount > 0){


			$savedata=array(	
			'transactionType'=>$TransactionType,
			//'sms_text'=>$jdata,
			'branchid'=>$branchid,
			'amount'=>$TransAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$TransID,
						//	'OrgAccountBalance'=>$OrgAccountBalance,

				'firstname'=>$FirstName,
				//'middlename'=>$MiddleName,
			//	'lastname'=>$LastName,
				'sender_number'=>$MSISDN,
				'account_number'=>$BillRefNumber,
				'business_shortcode'=>$BusinessShortCode,

		
								);
							$usr_result = $this->usermodel->add($savedata,'sms_in');
	}
		
$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$sendfeedback=$configuration[0]["sendfeedback"];
		if($sendfeedback=="yes"){
			$this->SendFeedbacksms(1,$MSISDN,$FirstName,$TransID);
			
		}
		
	/*
		
		if($postData==""){
			
			$postData="No data sent. Direct entry.";
			
		}
		
		
			$savedata=array(	
			'documentname'=>$postData,
		'companyid'=>"1",
			'userid'=>"1",

		
								);
		
			$usr_result = $this->usermodel->add($savedata,'documents');
			echo"Welcome";
			
			*/
		
	}
	
	
	
	
	
	
	
	
	
	
	
	public function getpayment()
	{ 





		
		$postData = file_get_contents('php://input');
    //log file

    //Parse payload to json
    $jdata = json_decode($postData, true);

	
	
	
	
	//This is the data from mpesa
    $TransactionType = $jdata["TransactionType"];
    $TransID = $jdata["TransID"];
    $TransTime = $jdata["TransTime"];
    $TransAmount = $jdata["TransAmount"];
    $BusinessShortCode = $jdata["BusinessShortCode"];
    $BillRefNumber = $jdata["BillRefNumber"];
    $InvoiceNumber = $jdata["InvoiceNumber"];
    $MSISDN = $jdata["MSISDN"];
    $FirstName = $jdata["FirstName"];
  //  $MiddleName = $jdata["MiddleName"];
   // $LastName = $jdata["LastName"];
        $OrgAccountBalance = $jdata["OrgAccountBalance"];

		
		 $correctime = date("Y-m-d H:i:s", strtotime($TransTime));



	$configuration= $this->usermodel->populateallarray('smsconfig','id',1);

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

if($restricttill=="yes"){


	$tillsdetails= $this->usermodel->populateallarray('tills','name',$BusinessShortCode);

	
	
	if($tillsdetails[0]["branchid"]==""){
		$branchid="1";	
		
	}else{
	$branchid=$tillsdetails[0]["branchid"];	
		
	}


}else{
			$branchid="1";

}

/*


			$savedataKOPOKOPO=array(	
			'transactionType'=>$jdata["type"],
			'branchid'=>$branchid,

			'amount'=>$jdata["amount"],
				//'txn_time'=>$jdata,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$jdata["reference"],
							//'OrgAccountBalance'=>$OrgAccountBalance,

				'firstname'=>$jdata["sender_first_name"],
				'middlename'=>$jdata["sender_middle_name"],
				'lastname'=>$jdata["sender_last_name"],
				'sender_number'=>$jdata["sender_phone_number"],
				//'account_number'=>$BillRefNumber,
				'business_shortcode'=>$jdata["till_number"],

		
								);


*/


  if($TransAmount > 0){


			$savedata=array(	
			'transactionType'=>$TransactionType,
			//'sms_text'=>$jdata,
			'branchid'=>$branchid,
			'amount'=>$TransAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$TransID,
							'OrgAccountBalance'=>$OrgAccountBalance,

				'firstname'=>$FirstName,
				//'middlename'=>$MiddleName,
			//	'lastname'=>$LastName,
				'sender_number'=>$MSISDN,
				'account_number'=>$BillRefNumber,
				'business_shortcode'=>$BusinessShortCode,

		
								);
							$usr_result = $this->usermodel->add($savedata,'sms_in');
	}
		
$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$sendfeedback=$configuration[0]["sendfeedback"];
		if($sendfeedback=="yes"){
			$this->SendFeedbacksms(1,$MSISDN,$FirstName,$TransID);
			
		}
		
		
		
		
	}
	public function getpaymentnew()
	{ 





		
		$postData = file_get_contents('php://input');
    //log file

    //Parse payload to json
    $jdata = json_decode($postData, true);
	
	

	
	
	
	
	
	
	//This is the data from mpesa
    $TransactionType = $jdata["TransactionType"];
    $TransID = $jdata["TransID"];
    $TransTime = $jdata["TransTime"];
    $TransAmount = $jdata["TransAmount"];
    $BusinessShortCode = $jdata["BusinessShortCode"];
    $BillRefNumber = $jdata["BillRefNumber"];
    $InvoiceNumber = $jdata["InvoiceNumber"];
    $MSISDN = $jdata["MSISDN"];
    $FirstName = $jdata["FirstName"];
  //  $MiddleName = $jdata["MiddleName"];
   // $LastName = $jdata["LastName"];
        $OrgAccountBalance = $jdata["OrgAccountBalance"];

		
		 $correctime = date("Y-m-d H:i:s", strtotime($TransTime));

			$savedata=array(	
			'transactionType'=>$TransactionType,
			
			'amount'=>$TransAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$TransID,
							'OrgAccountBalance'=>$OrgAccountBalance,

				'firstname'=>$FirstName,
				//'middlename'=>$MiddleName,
			//	'lastname'=>$LastName,
				'sender_number'=>$MSISDN,
				'account_number'=>$BillRefNumber,
				'business_shortcode'=>$BusinessShortCode,

		
								);
							$usr_result = $this->usermodel->add($savedata,'sms_in');
							
		
$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$sendfeedback=$configuration[0]["sendfeedback"];
		if($sendfeedback=="yes"){
			$this->SendFeedbacksms(1,$MSISDN,$LastName,$TransID);
			
		}
		
		
		
		
	}
	
	
	
	
	public function getecitizenpayment()
	{ 

 $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
	



		
		$postData = file_get_contents('php://input');
    //log file

    //Parse payload to json
    $jdata = json_decode($postData, true);
	
	
	$secret = "1FaPNFnB6IN5TU/2zhofLtgJH1OYVias";  // Note that the secret is directly used here
	$key ="Bsn5RB7qBLEhZFXR";
  $client_invoice_ref= $jdata["client_invoice_ref"];
  $invoice_number=$jdata["invoice_number"];
  $amount=$jdata["amount_paid"];
	  $payment_date = $jdata["payment_date"];

	  $phone_number = $jdata["phone_number"];
 $payment_channel = $jdata["payment_channel"];
 $code = $jdata["payment_reference"][0]["payment_reference"];
 //$phone_number = $jdata["payment_reference"][0]["phone_number"];


		 	$getphone=explode("+",$payment_date);
$paymentdate=$getphone[0];
	$ecitizendata=array(	
						'account_number'=>$invoice_number,
						'msisdn'=>$client_invoice_ref,
						'amount'=>$amount,
						'used'=>"2",
						'code'=>$code,
						'exactime'=>$paymentdate,
						'txn_time'=>$dateposted,
						'transactionType'=>$payment_channel,
						'sender_number'=>$phone_number,

		
								);
							$usr_result = $this->usermodel->add($ecitizendata,'sms_in');
	
	
	
	
	
	exit;
	
	
	
	
	
	
	
	
	
	
	
	//This is the data from mpesa
    $TransactionType = $jdata["TransactionType"];
    $TransID = $jdata["TransID"];
    $TransTime = $jdata["TransTime"];
    $TransAmount = $jdata["TransAmount"];
    $BusinessShortCode = $jdata["BusinessShortCode"];
    $BillRefNumber = $jdata["BillRefNumber"];
    $InvoiceNumber = $jdata["InvoiceNumber"];
    $MSISDN = $jdata["MSISDN"];
    $FirstName = $jdata["FirstName"];
  //  $MiddleName = $jdata["MiddleName"];
   // $LastName = $jdata["LastName"];
        $OrgAccountBalance = $jdata["OrgAccountBalance"];

		
		 $correctime = date("Y-m-d H:i:s", strtotime($TransTime));

			$savedata=array(	
			'transactionType'=>$TransactionType,
			
			'amount'=>$TransAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$TransID,
							'OrgAccountBalance'=>$OrgAccountBalance,

				'firstname'=>$FirstName,
				//'middlename'=>$MiddleName,
			//	'lastname'=>$LastName,
				'sender_number'=>$MSISDN,
				'account_number'=>$BillRefNumber,
				'business_shortcode'=>$BusinessShortCode,

		
								);
							$usr_result = $this->usermodel->add($savedata,'sms_in');
							
		
$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$sendfeedback=$configuration[0]["sendfeedback"];
		if($sendfeedback=="yes"){
			$this->SendFeedbacksms(1,$MSISDN,$LastName,$TransID);
			
		}
		
		
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	public function getbankpaymentkcbtill()
	{ 

		
		$postData = file_get_contents('php://input');
    //log file

    //Parse payload to json
    $jdata = json_decode($postData, true);
	   if (!$jdata) {
	
	
	//This is the data from mpesa
    $TransactionType = $jdata["TransactionType"];
    $TransID = $jdata["transactionReference"];
    $TransTime = $jdata["timestamp"];
    $TransAmount = $jdata["transactionAmount"];
    $BusinessShortCode = $jdata["organizationShortCode"];
    $BillRefNumber = $jdata["customerReference"];
    //$InvoiceNumber = $jdata["InvoiceNumber"];
    $MSISDN = $jdata["customerMobileNumber"];
    $FirstName = $jdata["customerName"];
    //$MiddleName = $jdata["MiddleName"];
    //$LastName = $jdata["LastName"];
	
	   $TransactionID = $jdata["requestId"];
		    $requestId = $jdata["requestId"];
		    $channelCode = $jdata["channelCode"];
		    $timestamp = $jdata["timestamp"];
		    $currency = $jdata["currency"];
		    $balance = $jdata["balance"];
		    $narration = $jdata["narration"];
		    $creditAccountIdentifier = $jdata["creditAccountIdentifier"];

		 $correctime = date("Y-m-d H:i:s", strtotime($TransTime));

			$savedata=array(	
			'transactionType'=>$TransactionType,
						'sms_text'=>$narration,

			'amount'=>$TransAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$TransID,
			
				'firstname'=>$FirstName,
				//'middlename'=>$MiddleName,
				//'lastname'=>$LastName,
				'sender_number'=>$MSISDN,
				'account_number'=>$BillRefNumber,
				'business_shortcode'=>$BusinessShortCode,

		
								);
						
							

								
								$correctime = date('Y-m-d H:i:s');
						
								
								
							$usr_result = $this->usermodel->add($savedata,'sms_in');
	
		
		
		    ob_clean();
		echo json_encode([
        "transactionID" => $TransactionID,
        "statusCode"    => 0,
        "statusMessage" => "Notification received"
    ]);
		
		
		
	
		
		
	   }else{
		   
		     ob_clean(); // Clear any accidental output/warnings
        echo json_encode([
            "transactionID" => $kcbTransactionID,
            "statusCode"    => 1,
            "statusMessage" => "FAILED: Account Not Found"
        ]);
		   
		   
	   }
		
	}
	
	
	
	
	
	
	
	
	
	
	public function getbankpayment()
{
	
	
    // 1. Capture the raw input from the request body
    $postData = file_get_contents('php://input');

    // 2. Decode the JSON data into an associative array
    $jdata = json_decode($postData, true);

    // Basic validation: Check if we actually received data
    if (!$jdata || !isset($jdata["transactionReference"])) {
        header('Content-Type: application/json');
        echo json_encode([
            "transactionID" => "UNKNOWN",
            "statusCode"    => 1,
            "statusMessage" => "Invalid Payload"
        ]);
        return;
    }

    // 3. Map the incoming JSON keys to your local variables
    $TransID           = $jdata["transactionReference"];
    $requestId         = $jdata["requestId"];
    $channelCode       = $jdata["channelCode"];
    $TransTime         = $jdata["timestamp"];
    $TransAmount       = $jdata["transactionAmount"];
    $currency          = $jdata["currency"];
    $BillRefNumber     = $jdata["customerReference"];
    $FirstName         = $jdata["customerName"];
    $MSISDN            = $jdata["customerMobileNumber"];
    $balance           = $jdata["balance"];
    $narration         = $jdata["narration"];
    $creditAccount     = $jdata["creditAccountIdentifier"];
    $BusinessShortCode = $jdata["organizationShortCode"];
    $tillNumber        = $jdata["tillNumber"];

    // 4. Format the timestamp for the database
    $correctime = date("Y-m-d H:i:s", strtotime($TransTime));

    // 5. Prepare the data array for the database ('sms_in' table)
    $savedata = array(
        'transactionType'    => "KCB_TILL", // Or use $channelCode if preferred
        'sms_text'           => $narration,
        'amount'             => $TransAmount,
        'txn_time'           => $correctime,
        'sent_dt'            => $correctime,
        'exactime'           => date('Y-m-d H:i:s'),
        'used'               => 2,
        'code'               => $TransID,
        'firstname'          => $FirstName,
        'sender_number'      => $MSISDN,
        'account_number'     => $BillRefNumber,
        'business_shortcode' => $BusinessShortCode,
    );

    // 6. Insert data into the database
    $usr_result = $this->usermodel->add($savedata, 'sms_in');

    // 7. Send the specific JSON response back to KCB
    header('Content-Type: application/json');
    echo json_encode([
        "transactionID" => $TransID,
        "statusCode"    => 0,
        "statusMessage" => "Notification received"
    ]);
}
	
	
	public function getpayment2()
	{ 





		
		$postData = file_get_contents('php://input');
    //log file

    //Parse payload to json
    $jdata = json_decode($postData, true);
	
	
	
	//This is the data from mpesa
    $TransactionType = $jdata["TransactionType"];
    $TransID = $jdata["TransID"];
    $TransTime = $jdata["TransTime"];
    $TransAmount = $jdata["TransAmount"];
    $BusinessShortCode = $jdata["BusinessShortCode"];
    $BillRefNumber = $jdata["BillRefNumber"];
    $InvoiceNumber = $jdata["InvoiceNumber"];
    $MSISDN = $jdata["MSISDN"];
    $FirstName = $jdata["FirstName"];
    $MiddleName = $jdata["MiddleName"];
    $LastName = $jdata["LastName"];
		
		 $correctime = date("Y-m-d H:i:s", strtotime($TransTime));

			$savedata=array(	
			'transactionType'=>$TransactionType,
			
			'amount'=>$TransAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$TransID,
			
				'firstname'=>$FirstName,
				'middlename'=>$MiddleName,
				'lastname'=>$LastName,
				'sender_number'=>$MSISDN,
				'account_number'=>$BillRefNumber,
				'business_shortcode'=>$BusinessShortCode,

		
								);
							$usr_result = $this->usermodel->add($savedata,'sms_in');
							
		
$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$sendfeedback=$configuration[0]["sendfeedback"];
		if($sendfeedback=="yes"){
			$this->SendFeedbacksms(1,$MSISDN,$LastName,$TransID);
			
		}
		
		
		
		
	}
	public function getequitypayment()
	{ 

$postData = (file_get_contents('php://input'));

$handle = fopen('received_data.txt', 'w');
fwrite($handle, $postData);
fclose($handle);


$json_data = json_decode($postData);
	
//Customer Info
$customer = $json_data->customer;
$name = $customer->name;
$mobileNumber = $customer->mobileNumber;
$customer_reference = $customer->reference;

//Transaction Info
$transaction = $json_data->transaction;
$date = $transaction->date;
$transaction_reference = $transaction->reference;
$paymentMode = $transaction->paymentMode;
$amount = $transaction->amount;
$till = $transaction->till;
$billNumber = $transaction->billNumber;
$orderAmount = $transaction->orderAmount;
$serviceCharge = $transaction->serviceCharge;
$servedBy = $transaction->servedBy;
$additionalInfo = $transaction->additionalInfo;

//Bank Info
$bank = $json_data->bank;
$bank_reference = $bank->reference;
$transactionType = $bank->transactionType;
$account = $bank->account;

//Key
$api_key = $_GET['api_key'];

//Process data in local system
if (strtoupper($transactionType) === 'C') {
    $additionalInfo_array = explode(' ', $additionalInfo);

    if ($additionalInfo_array[0] === 'MPS') {
        if (count($additionalInfo_array) === 5) {
            $houseNo = $additionalInfo_array[3];
        }else {
            $houseNo = $billNumber; //We couldn't get the house number from the transaction. Probably wasn't provided by customer or payment mode
        }
    } elseif ($additionalInfo_array[0] === 'EAZZY-BILL') {
        $houseNo = $billNumber;
    }
    $reference = $transaction_reference;
	
	/*
		Pick the $date, $reference & $houseNo from above and process in your system.
		Process payment in your system below this line.		
	*/
	
	
    
}
	

	
		 $correctime = date("Y-m-d H:i:s", strtotime($date));

			$savedata=array(	
			'transactionType'=>$TransactionType,
			
			'amount'=>$orderAmount,
				'txn_time'=>$correctime,
				'sent_dt'=>$correctime,
							'exactime'=>$correctime,
							'used'=>2,

				'code'=>$reference,
			
				'firstname'=>$name,
				'middlename'=>$name,
				'lastname'=>$name,
				'sender_number'=>$mobileNumber,
				//'account_number'=>$houseNo,
								'account_number'=>$houseNo,

				'business_shortcode'=>$till,

		
								);
							$usr_result = $this->usermodel->add($savedata,'sms_in');
						$this->verifyinvoice($orderAmount,$reference,$correctime,$houseNo,"");

$configuration = $this->usermodel->populateallarray('smsconfig','id',1);
		$sendfeedback=$configuration[0]["sendfeedback"];
		if($sendfeedback=="yes"){
			//$this->SendFeedbacksms(1,$MSISDN,$LastName,$TransID);
			
		}
		
		
		
		
	}
	
	
	
	
	
	
  function verifyinvoice($originalamount,$paymentcode,$createdat,$houseno,$plotno)
    {
		
		  $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");
		   
		$mypaymentmode = "4";
	
         			//$paymentcode = $paymentcode;

	
				 $myplotdata=$this->usermodel->populatethreenoarray('bookroom','houseno', $houseno,'status', "active",'id >', "active",0);
				 				 $tenantid=trim($myplotdata[0]['tenantid']);
								 
								 
								 $mycustomer=$this->usermodel->populateallarray('people','id', $tenantid);
			$myname=$mycustomer[0]['firstname'];
			
				 				 $plotno=trim($myplotdata[0]['plotno']);

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

		$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=$myplotdata[0]["id"];
										$prvioushousebalance=$myplotdata[0]["totalamount"];
									$CURRENTOVERPAYMENTMADE=$myplotdata[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' => $myname,
								'paymentmode' => $mypaymentmode,
						'overpayment' => $finaloverpayemnt,
						'paymentcode' => $paymentcode,


								'companyid' => $companyid,

				'description' => $description
			);

				
			
					
					if($this->usermodel->add($data,'receipt')){
						
						
			$myinvoice = $this->accomodationmodel->gethouserentinvoicewithbalance($plotno,$houseno);

					if(is_array($myinvoice)) 

 {
	 
	$finaltotal=$originalamount;
 $myfinaltotal=0;
  $myfinaltotal2=-1;
  $mypayment=0;
    $finalbalnce=0;
	 $mybalnce=0;
	
   foreach($myinvoice as $invoicerows){
	   	 $invoiceid=$invoicerows->id;

	 $type=$invoicerows->type;
	 
	  $amount=$invoicerows->amount;
  $paid=$invoicerows->paid;
  $invoiced=$amount-$paid;

	  $myfinaltotal=$myfinaltotal+$invoiced;
	 
	  
$balance=$originalamount-$myfinaltotal;


$mybalnce=$originalamount-$myfinaltotal;

  if($myfinaltotal2==-1){
  if($originalamount<$invoiced){

///echo 0;


		
		$mypayment= $originalamount;
	}else {
		
		
		$mypayment= $invoiced;
		
		
	}
  }else{
	  
	 $finalbalnce=$balance- -$invoiced;
	  
	   
	 
		   
		    if($finalbalnce>=$invoiced){
		   	$mypayment= $invoiced;
			}else if(($finalbalnce<=$invoiced) && ($finalbalnce>0)){
	   	$mypayment= $finalbalnce;
		 
			}else if(($finalbalnce<=$invoiced) && ($finalbalnce<0)){
	 	$mypayment= "0"; 
		 
			}else{
				
				$mypayment= "0"; 	
			}
	
	
  }
  
  
  $myfinaltotal2=$myfinaltotal2+1;
	   
	   
	   	 $totalinvoice=$totalinvoice+$mypayment;
	   
	    
	    if(($type=="1")||($type=="6")) {
								 // $mytax=1+($vat/100); 
								 //$vatable=($amount[$i]/$mytax);
								 //$myfinaltax=($amount[$i]-$vatable);
								 $myfinalcommission=(($commission/100)*$mypayment);

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

							 }else{
								 
															 	 $finalcommission=0;


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

	  $exactinvoice=$invoicerows->amount;
	       $origalpayment=$invoicerows->paid;
	   $finalamount= $origalpayment+$mypayment;
	   
      $invoicedata=array(
			 'paid' =>$mypayment,		
	   'amount' =>$exactinvoice,
	   'plotno' =>$invoicerows->plotno,
	   'houseno' =>$invoicerows->houseno,
	   'tenantid' =>$invoicerows->tenantid,
	   'type' =>$invoicerows->type,
	   	   'companyid' =>$invoicerows->companyid,
	   'branchid' =>$invoicerows->branchid,

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

		'paymentcode' => $transactioncode,
			'paymentdate' => $createdat,
	
							
								);
								if($mypayment!=0){
										$usr_result= $this->usermodel->updatedata($paymentdata,'invoice','id',$invoiceid);
				$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 Hs No.". $houseno ." on  ". $correctime .". Your total balance is 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 pintreceipthouse() {
   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		


			$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
$data['setting'] = $this->usermodel->getsetting();
 
 $data['viewreceipt']= $this->usermodel->populateallarray('receipt','transactioncode',$refnumber);
$data['viewsales']= $this->usermodel->populateall('invoice','transactioncode',$refnumber);

 
 
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',1);

				
						$this->load->view('printinvoicehouse', $data);   
							   
		
		
	}
  }
  
	
	
		  public function printinvoicehouse() {
   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		


			$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
$data['setting'] = $this->usermodel->getsetting();
 
 $data['viewreceipt']= $this->usermodel->populateallarray('receipt','transactioncode',$refnumber);
$data['viewsales']= $this->usermodel->populateall('invoice','transactioncode',$refnumber);

 
 
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',1);

				
						$this->load->view('printinvoicehouse', $data);   
							   
		
		
	}
  }
  
	
	
		  public function oldconfigno() {
	  
	 
$session_data = $this->session->userdata('logged_in');
	 	$this->load->view("template/headerpagelogin");

$this->load->view("template/headerpagegeneral");
   
 	$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'];
	 

        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id >',0);

				
		
		$this->load->view("template/tableheader");
	
$data['userid']=$companyid;
		 $this->load->view('userdata/oldconfigno', $data);
		$this->load->view("template/footerpage");
		
	
  }
	
	
	
			public function extendserial()

	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
			 if(isset($_GET['msg'])) {
			      $msg = $_GET['msg'];

			$data['msg']=$msg;
		 $this->load->view('extendserial', $data);
			 }else{
				$this->load->view('extendserial');

			 }
		$this->load->view("template/footerpage");
	}
	

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

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $computerno = trim($this->input->post("computerno"));
								 
								 
								 
								 

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

		 		 $name = $this->input->post("name");
		 		 $duration = $this->input->post("duration");
		 		 $myurl = $this->input->post("myurl");

		   	  $description = $this->input->post("description");
 	  $fromdate = $this->input->post("fromdate");
			  		 				 		 $phone = $this->input->post("phone");

		     	$invoice = time()+ 1;
 $todate=date('Y-m-d', strtotime('+1 year', strtotime($fromdate)) );
		
				
			  		  $this->form_validation->set_rules("computerno", "Computer Key ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
     $this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
//
		
		 $this->load->view('extendserial', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_requestdate') == "Confirm")
					   {
						   
						  
						   
						   
							$confirmcode = $this->usermodel->populatealldatanorraythree('renewals','computerno', $computerno,'id > ',0,'status',"Ready");

	   
	   
			if($confirmcode !=FALSE){
						
			$data['myurl']=$myurl;
			
$data['computerno']=$computerno;
   $myfinaldate=trim($confirmcode[0]['todate']);
   $myinvoice=$confirmcode[0]['invoice'];
   
   
   
   $custom_key = 'KENGA';

        $encryption_config = [
            'cipher' => 'aes-256',
            'mode'   => 'cbc',
            'key'    => hash('sha256', $custom_key), 
        ];

        
        $this->encryption->initialize($encryption_config);



   
   
   
   
   
   
   


 //$decodedate = trim($this->encrypt->encode($myfinaldate,"KENGA")); 
$decodedate =trim($this->encryption->encrypt($myfinaldate));


		


//

		redirect($myurl.'getcompnoreadydate?deadline='.trim($decodedate)."&invoice=".$myinvoice);
	
															

					return false;
					}
					 	
						   
						   
			$confirmcodes = $this->usermodel->populatealldatanorraythree('renewals','computerno', $computerno,'id > ',0,'status',"Submitted");

		
		
			if($confirmcodes !=FALSE){
						
		$message="There is pending date extension/renewal application which has not been approved. Reach out to Robisearch on :0790962631/0716413386/0718667391  before you submit another one.";
			
			  $message2=$this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> There is pending date extension/renewal application which has not been approved. Reach out to Robisearch on :0790962631/0716413386/0718667391  before you submit another one.</div>');
				redirect($myurl."extendserial?msg=".$message);
				//redirect($myurl."extendserial",'refresh');
				
					return false;
					}   
						   
						 
  
						
						   
												$data=array(		
			'userid'=>1,
										'fromdate'=>$fromdate,
										'extensiontype'=>$extensiontype,

										'todate'=>$fromdate,

							'status'=>"Submitted",
							'phone'=>$phone,
							'invoice'=>$invoice,
			'duration'=>$duration,

				'name'=>$name,
			'computerno'=>$computerno,
		  	'description'=>$description,
				 'companyid'=>1,

				 
			'createdate'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'renewals');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							
					$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Submitted date extension to Robisearch team. Wait for activation or call :0790962631/0780655987/0716413386/0718667391 ..</div>');	
							//redirect('config');	
							
							
							
							
							
							
						  		$message="You have successfully Submitted date extension to Robisearch team. Wait for activation or call :0790962631/0780655987/0716413386/0718667391.";

						   
						  				redirect($myurl."extendserial?msg=".$message);	
							
							
							


				//redirect($myurl."config");							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The extension   was not Submitted.. Try again</div>');
								
								
								  		$message="The extension   was not Submitted.. Try again";

						   
						  				redirect($myurl."extendserial?msg=".$message);
								
				//redirect($myurl."config");							
							}
					   }
					   else
					   {
						   				redirect($myurl."login");							

						//	redirect('login');
					   }
	    }
    }

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

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		//  $dateposted = date('Y-m-d H:i:s');
						  $dateposted = date('Y-m-d H:i:s');

		 $userid = $data['id'];
		
				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 				 		 $computerno = trim($this->input->post("computerno"));
								 
								 
								 
								 

								 
								 
								 
								   
				$tin = $this->input->post("tin");
		 		 $sdcId = $this->input->post("sdcId");
		 		 $bhfid = $this->input->post("bhfid");
				$cmcKey = $this->input->post("cmcKey");
		 		 $businesskey = $this->input->post("businesskey");
		 		 $code = $this->input->post("code");	
				$phone = $this->input->post("phone");
		 		 $updatedby = $this->input->post("updatedby");
		 		 $requestdate = $this->input->post("requestdate");
				 $verification = $this->input->post("verification");
		 		 $branchid = $this->input->post("branchid");
				 $mrcNo = $this->input->post("mrcNo");
						 $invoice = $this->input->post("invoice");					 
							 $url = $this->input->post("url");
						 $onlineoffline = $this->input->post("onlineoffline");					 
								 
		 							

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

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

		
				
			  		  $this->form_validation->set_rules("computerno", "Computer Key ", "trim|required");

			  
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
     $this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
//
		
		 $this->load->view('userdata/extendetims', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_requestetimsdata') == "Confirm")
					   {
						   
						  
						   
						   
							//$confirmcode = $this->usermodel->populatealldatanorraythree('etimsactivations','mrcNo',trim($mrcNo),'id > ',0,'status',"Ready");

	   			$confirmcode = $this->usermodel->populatealldatanorraythree('etimsactivations','tin',$tin,'bhfid',$bhfid,'status',"Ready");

	   
			if($confirmcode !=FALSE){
						
			$data['myurl']=$myurl;
			
$data['computerno']=$computerno;
   $myfinaldate=trim($confirmcode[0]['todate']);
   $myinvoice=$confirmcode[0]['invoice'];
    $myverification=$confirmcode[0]['verification'];
   
	$message="There is pending ETIMS activation request which has not been approved. Reach out to Robisearch on :0790962631/0716413386/0718667391  before you submit another one.";
			
			  $message2=$this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> There is pending ETIMS activation request which has not been approved. Reach out to Robisearch on :0790962631/0716413386/0718667391  before you submit another one.</div>');
				redirect($myurl."extendserial?msg=".$message);
				//redirect($myurl."extendserial",'refresh');
				
					return false;
					
					

					}
					 	
						   
						   
			$confirmcodes = $this->usermodel->populatealldatanorraythree('etimsactivations','tin',$tin,'bhfid',$bhfid,'status',"Submitted");

		
		
			if($confirmcodes !=FALSE){
						
		$message="There is pending ETIMS activation request which has not been approved. Reach out to Robisearch on :0790962631/0716413386/0718667391  before you submit another one.";
			
			  $message2=$this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong> There is pending date extension/renewal application which has not been approved. Reach out to Robisearch on :0790962631/0716413386/0718667391  before you submit another one.</div>');
				redirect($myurl."extendserial?msg=".$message);
				//redirect($myurl."extendserial",'refresh');
				
					return false;
					}   
			


						
  
						
						   
												$data=array(		
							'tin'=>$tin,
							'sdcId'=>$sdcId,
							'bhfid'=>$bhfid,
							'cmcKey'=>$cmcKey,
							'businesskey'=>$businesskey,
							'code'=>$code,
							'phone'=>$phone,
							'name'=>$updatedby,
							'fromdate'=>$requestdate,
							'verification'=>$verification,
							'branchid'=>$branchid,
							'status'=>"Submitted",			
							'description'=>$description,
								'computerno'=>$computerno,

								'companyid'=>1,
							'createdate'=>$dateposted,
							'mrcNo'=>$mrcNo,
						'invoice'=>$invoice,
						'url'=>$url,
						'onlineoffline'=>$onlineoffline,
								'userid'=>1,
						
			
				
			
								);
							$usr_result = $this->usermodel->add($data,'etimsactivations');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
							
					$this->pushroomsmsNull("Computer with key:  $computerno has been submitted  for date extension by $name:$phone " ,"254790962631","");

								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully Submitted ETIMS  Activation request to Robisearch team. Wait for activation or call :0790962631/0780655987/0716413386/0718667391 ..</div>');	
							//redirect('config');	
							
							
							
							
							
							
						  		$message="You have successfully Submitted ETIMS  Activation request to Robisearch team. Wait for activation or call :0790962631/0780655987/0716413386/0718667391.";

						   
						  				redirect($myurl."extendserial?msg=".$message);	
							
							
							


				//redirect($myurl."config");							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The extension   was not Submitted.. Try again</div>');
								
								
								  		$message="The extension   was not Submitted.. Try again";

						   
						  				redirect($myurl."extendserial?msg=".$message);
								
				//redirect($myurl."config");							
							}
					   }
					   else
					   {
						   				redirect($myurl."login");							

						//	redirect('login');
					   }
	    }
    }

	


	function pushroomsmsNull($mainmessage,$maincontact,$myview)
	{
 
		
			//SS$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 = 1;
		 		
		 		// $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=".urlencode($from)."&mobile=$allcontacts";

			//$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 {

				
				}
				
			
}
}
			
				if($finalcode=="Success"){	
			
				
					
			
								// redirect($myview);
			}else{
				
				
				

							//redirect($myview);

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  


	
	
	
	
public function verifypayment()
	{ 

echo "welcome to verifypayment";
		
		
		
	}
	
	
	
	
	
	
public function SendFeedbacksms($COMPANYID,$phone,$lastname,$code){

//$COMPANYID=1;
			$CUSTOMER= $this->usermodel->getFeedbackmembers($COMPANYID);
//$phone="254718667391";
	//$lastname="OUKO";
		//$code="OJR2VC8KZ6";
		 $datetime = date("Y-m-d H:i:s");

if(is_array($CUSTOMER)) {

   foreach($CUSTOMER as $row)
   {
 
	
	

										
					// $totalsms=$row->totalsms;
					
					$username=$row->username;
					$from=$row->from;
				

					$password=$row->password;	
						$message="Dear ".$lastname.". ".$row->feedback;
						
	
	
									$totalsms=$row->totalsms;
									$myid=$row->myid;
										$mycompanyid=$row->companyid;
										
										
						 $countmessage =strlen($message);
					 $COST="";
					 $finaltotalsms=0;
				 if($countmessage<=150){
				$finaltotalsms=$totalsms-1;
					$COST=1;
						$finaltotalsms=$totalsms-1;
				 }else if($countmessage<=310){
					 $finaltotalsms=$totalsms-2;
					$COST=2;
				 }else if($countmessage<=470){
					$COST=3;
					$finaltotalsms=$totalsms-3;
				 }
				 else if($countmessage<=630){
					$COST=4;
					$finaltotalsms=$totalsms-4;
				 }
				 else if($countmessage<=790){
					 $COST=5;
					$finaltotalsms=$totalsms-5;
				 }
				 
				 
				 
									if(($totalsms > $COST) || ($totalsms == $COST)){
								$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=".urlencode($from)."&mobile=$phone";

							//	$finalURL = "https://sms.bulksmschapchap.com/api/services/sendsms/?apikey=" . urlencode($password) . "&partnerID=" . urlencode($username) . "&message=" . urlencode($message) . "&shortcode=$from&mobile=$phone";
$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"){
			
			
			
				$updatedata=array(		
		
							'totalsms'=>$finaltotalsms,
							);
						
							$updatesmsdata=array(		
		
							'msisdn'=>1,
							);
						
	
							   	$this->usermodel->updatedata($updatedata,'people','id',$myid);
									$this->usermodel->updatedata($updatesmsdata,'sms_in','code',$code);
									

				//mysql_query("UPDATE people SET totalsms='$finaltotalsms'  WHERE id='$userid'  ");
 		   		//mysql_query("UPDATE sms_in SET msisdn=1  WHERE code='$TransID'  ");

		$smsdata=array(		
		
								
								'contact'=>$phone,
								'message'=>htmlspecialchars($message),
								'companyid'=>$mycompanyid,
								'postedtime'=>$datetime,
								'userid'=>$myid,


							);
					$usr_result = $this->usermodel->add($smsdata,'sms');

			//$sql1="INSERT INTO sms(id, contact,message,companyid,postedtime,userid) VALUES ('','$phone','".mysql_real_escape_string($message)."','$mycompanyid','$date','$userid')";	
			//$result1= mysql_query($sql1);
			
		

echo "sms is sent  <br>";


		}else{
	
		echo"Error main!".$finalcode ." = Phone :".$phone. " <br>";

		}
			
				
				} else{

				echo "Error occurred during Sending Messag! Please check on your internet connection or balance then try again ";
							
				}


				
							
				} 						
						
						
									
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	}
	
}

}
	
	
	
	
	
	
	
	
	
	
	
	
	
		public function receipts()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		$this->load->view('receipts');
		$this->load->view("template/footerpage");
	}
	
	
			public function viewrecordings()
	{  	      $this->load->view("template/headerpagemin");

		$this->load->view("template/tableheader");

		$this->load->view('userdata/viewrecordings');
	$this->load->view("template/footerpage");
	}
			public function cartcheckout()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		$this->load->view('cartcheckout');
		$this->load->view("template/footerpage");
	}
	
	
			public function cart()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		$this->load->view('cart');
		$this->load->view("template/footerpage");
	}
	
	
		public function agent()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagecustomer");
		$this->load->view('agent');
		$this->load->view("template/footerpage");
	}
		public function customerfeedback()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagecustomer");
		$this->load->view('customerfeedback');
		$this->load->view("template/footerpage");
	}
		public function pendingorder2()
	{  //	$this->load->view("template/headerpagelogin");
			//$this->load->view("template/headerpagegeneral");
		//$this->load->view('pendingorder');
		
										 redirect('printkitchenorder');

		//$this->load->view("template/footerpage");
	}
	
		public function pendingorder()
	{  //	$this->load->view("template/headerpagelogin");
			//$this->load->view("template/headerpagegeneral");
		//$this->load->view('pendingorder');
		
										 redirect('printkitchenorder');

		//$this->load->view("template/footerpage");
	}
	
	
	
	
	
	

		
	public function openstock()
	{ 
		 if (!isset($_GET['branchid'])){

    
      show_error('No Branch select e.g Main or 1,2,3 etc', 500);
    }
    else {
      $branchid = $_GET['branchid'];
						   				


		 $userid = 1;
	 $companyid = 1;
	 
	 
	 // $branchid = $this->input->post("branchid");

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

	//  $startdate =trim($this->input->post("startdate"));
   		
$startdate=date('Y-m-d');
$postedtime=date('H:i:s');
  $mybranch="";







  $mybranch="";
				
	
		      $this->load->view("template/headerpagelogin");

		
						   
	
						//$students = $this->adminusermodel->populatestudentsponsor('gov');
		   //populatealldatanoarraythree($table,$where, $value,$where1, $value1,$where2, $value2)
		   
		   if($branchid=="Main"){
			   		   							$myproducts = $this->usermodel->populateall('products','companyid', $companyid);

		   }else{
			   
			   
			   
			   	    if($branchid=="all"){
			  				 $myproducts = $this->usermodel->populatealldatanoarraythree('productlist','status <>', 'inactive','branch >',0,'companyid', $companyid);			   

				}else{
			  				 $myproducts = $this->usermodel->populatealldatanoarraythree('productlist','status <>', 'inactive','branch', $branchid,'companyid', $companyid);			   
	
				}
				
				
			   
 
		   }  
		   
		   

		   
		   
		   $data =array();
if(is_array($myproducts)) {

   foreach($myproducts as $row)
   {



	   if($branchid=="Main"){
  $mybranch="Main";
		   }else{
     $mybranch=trim($row->branch);

		   }  
		   





   $bycode=trim($row->code);
   	   	$confirmstock = $this->usermodel->populatealldatarraythree('stock','code', $bycode,'branchid', $mybranch,'startdate', $startdate);
	
if($confirmstock==FALSE ){
	

$sellingprice=$row->sellingprice;
  $categoryid=$row->category;
   $open=$row->qty;
	$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
	        $maincategoryid=trim($maincategory[0]['maincategory']); 
 
 
 
 	$data[]=array(		
			'code'=>$bycode,
			'branchid'=>$mybranch,
		  	'startdate'=>$startdate,
		
						'type'=>$maincategoryid,

			'userid'=>$userid,
			'companyid'=>$companyid,
			'open'=>$open,
				'price'=>$sellingprice,
					'postedtime'=>$postedtime,
								);
 //	$usr_result = $this->usermodel->add($data,'stock');
   
	}
}


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


			




        if($this->db->affected_rows() > 0)
	{
		

								
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully opened stock..</div>');	
										echo "You have successfully opened stock";
													//redirect('user/viewopeningstock');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again</div>');
								
								echo "Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again";
												//redirect('user/viewopeningstock');	
	
							}
							
							
							   } else {
             
			 								echo "Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again";

			 
			 
            }
} else {
    //echo   "No student";
	
}
						   
						   
					
					   }
	
					   
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public function closestock()
	{

 if (!isset($_GET['branchid'])){

    
      show_error('No Branch select e.g Main or 1,2,3 etc', 500);
    }
    else {
      $branchid = $_GET['branchid'];
	

		 $userid = 1;
	 $companyid = 1;
	 
	
   		
$closedate=date('Y-m-d');
$postedtime=date('H:i:s');



				  $new_date=date("Y-m-d H:i");

   



  $type ="Automatic";
$ttaddded=0;
				
	
		      $this->load->view("template/headerpagelogin");

	
						   
						   				
	   
		   if($branchid=="Main"){
				 $myproducts = $this->usermodel->populatealldatanoarrayfour('stock','closedate', "",'branchid', "Main",'companyid', $companyid,'startdate', $closedate);			   

		   }else{
 
 
    	    if($branchid=="all"){
				
				 $myproducts = $this->usermodel->populatealldatanoarrayfour('stock','closedate', "",'branchid <>',"Main",'companyid', $companyid,'startdate', $closedate);			   

				}else{
				 $myproducts = $this->usermodel->populatealldatanoarrayfour('stock','closedate', "",'branchid', $branchid,'companyid', $companyid,'startdate', $closedate);			   
	
				}
 
 
 
 
 
		   }  
		

		   







if(is_array($myproducts)) {

   foreach($myproducts as $row)
   {

   $bycode=trim($row->code);
    $mybranch=trim($row->branchid);
	 $mypostedtime=trim($row->postedtime);
	 	 $myadded=trim($row->added);

	  $mystartdate=trim($row->startdate);
	  $finalstartdate=$mystartdate." ".$mypostedtime;
	  $finalclosetime= $closedate." ".$postedtime;
	  $stockid=$row->id;
	    $price=$row->price;
		   $openstock=$row->open;
		   $mytotal=$row->total;
		     $oldbalance=$row->balance;
			 

			 
   	   	$addedstock = $this->usermodel->populatealldatarraythreebydate('newstock','item_id', $bycode,'type', $mybranch,'date', $finalstartdate, $finalclosetime);
 $totaladded=$addedstock[0]['total'];

 

 


		$totalsold=0;
 
 	   	   	$soldstock = $this->usermodel->populatealldatarraythreebydatesolditems('sales_order','code', $bycode,'branch', $mybranch,'date', $finalstartdate, $finalclosetime);

  $totalqty=$soldstock[0]['qty'];
		$finalbalance=0;
	
 
if($type=="Manual"){
	
			$ttaddded=$totaladded;
	$finalbalance=$oldbalance;

		$totalsold=(($openstock+$ttaddded)-$row->balance);
//$totalsold=$totalqty;

}else if($type=="BothManual"){
		$finalbalance=$oldbalance;

		$ttaddded=$myadded;
	$totalsold=(($openstock+$ttaddded)-$row->balance);

}else{
$totalsold=$totalqty;

	
	
 
if($totaladded==null){
	
	$ttaddded=0.00;
}else{
	$ttaddded=$totaladded;
}
		$mymyclosingtotal=$openstock+$ttaddded;

$mybalance=$mymyclosingtotal-$totalsold;

	$finalbalance=$mybalance;


}


$myclosingtotal=$openstock+$ttaddded;

$totalamount=$price*$totalsold;
$balance=$myclosingtotal-$totalsold;




 	$updatedata=array(		
		'added'=>$ttaddded,
			'sold'=>$totalsold,
	'updatedby'=>$userid,
	'closedate'=>$finalclosetime,
	'total'=>$myclosingtotal,
	'totalamount'=>$totalamount,
	'balance'=>$finalbalance,
	
								);
 	//$usr_result = $this->usermodel->add($data,'stock');
   	$usr_result = $this->usermodel->updatedata($updatedata,'stock','id',$stockid);

	
}
if ($usr_result ==TRUE) //active user record is present
							{
								
						echo "saved";		 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully closed the stock..</div>');	
										
													//redirect('user/viewopeningstock');	
	
													
							}
							else if ($usr_result ==FALSE) 
							{     
						echo "Not saved";		 

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Some /ALL stock was not posted. May be because of already existing opening stock for the same date.Try again</div>');
								
												//redirect('user/viewopeningstock');	
	
							}
} else {
	
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>No stock closed since there was no change that ocurred in the stock.Try again</div>');
								
	//redirect('user/viewopeningstock');	
	
}
						   
						   
					   }
					   
	
	}
	
	
	
	
	
	
	
	
	
	
	public function Splitmpesa(){
		
 
 		$date= date("Y-m-d h:i:s");

							

										$exactime="";
	function  convertString ($date)
    {
      
        $sec = strtotime($date);
 
      
        $date = date("Y-m-d H:i", $sec);
 
        $exactime = $date . ":00";
 
       return $exactime;
    }
 
 	$getmpesa = $this->usermodel->Splitmpesa();
	

if(is_array($getmpesa)){
$updateArray = array();

 
   foreach($getmpesa as $row)
   {
	   
	
	   $smsid=$row->id;
	$message = htmlspecialchars($row->sms_text);
			
			// $message=$row['sms_text'];
				$senttime=$row->sent_dt;
		
		 $mpesadata = explode(" ",$message);
		
	$mpesamount = explode("Ksh",$message);
	 $time = explode("Ksh",$mpesadata[5]);
	
	
				$myamount = $mpesamount[1];
				
				
$finalmpesaamount = explode(" ",$myamount);
				
						   $transactioncode = $mpesadata[0]; echo"<br>";
					

						   // exit;
							//$exactime = $mpesadata[2]." ".$mpesadata[4].$time[0];
							$myydate = DateTime::createFromFormat('d/m/y', $mpesadata[2]);
							
							if (($myydate)){
								
								$finaldate=$myydate->format('Y-m-d');
							$myexactime = $finaldate." ".$mpesadata[4]." ".$time[0];

									$exactime=  convertString($myexactime);
							
							}else{
							$exactime= "";
								
								
							}


				
					 $amount=str_replace(",", "", $finalmpesaamount[0]);
					//echo $amount=formatMoney($finalmpesaamount[0], true); echo"<br>";
  $phone = $mpesadata[8]; 
      $firstname = htmlspecialchars($mpesadata[9]);

 // $firstname = $mpesadata[9];
 $lastname = ""; 
  
  if(stripos($mpesadata[10],'.')){
	  $mylastname = $mpesadata[10];
$names = explode(".",$mylastname);
 //$lastname = $names[0];
	 $lastname = htmlspecialchars($names[0]);
 
 // echo "hiko";
  }else{ 
   // $lastname = $mpesadata[10];
      $lastname = htmlspecialchars($mpesadata[10]);


  } 
  
   $transactionid=$row->id; 
$updateArray[] =array(	
	'id'=>$transactionid,
	'lastname'=>trim($lastname),													
'firstname'=>trim($firstname),
'amount'=>trim($amount),
'code'=>trim($transactioncode),
'exactime'=>trim($senttime),
'sender_number'=>trim($phone),
'used'=>2,

);	

			
	}
$RESULT =	$this->db->update_batch('sms_in',$updateArray, 'id');
							
	//return true;	

	
}else{
	
}


	}
	
	
	
	
	  public function downloadcontacts() {
  
	

							  $new_date=date("Y-m-d H:i");


        $delimiter = ",";

        $newline = "\r\n";

        $filename = 	$new_date."contacts.csv";
		
								
							
									
 									

        $query = "SELECT phone,name,createdate FROM contacts  ";

       $result = $this->db->query($query);

        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);

        force_download($filename, $data);

		
	
  }
	
	
public function uploadcontact()
        {

          if(isset($_POST["btn_uploadcontact"]))
            { 

			
		   $currenttime = date('Y-m-d H:i:sa');
		
			 $name = $this->input->post("name");

	  $usr_result=FALSE;
	  $dateposted = date('Y-m-d H:i:s');
  $file= $_FILES["file"]['name'];
            $path = 'uploads/';
            require_once APPPATH . "/third_party/PHPExcel.php";
		//$config['upload_path'] = 'uploads/';
		 $new_date=date('Y-m-d');
		$ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));

     	 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
	
          $config['upload_path'] = $path;
            $config['allowed_types'] = 'xlsx|xls|csv|xlsm|xltx|xltm|txt';
            $config['remove_spaces'] = TRUE;
            $this->load->library('upload', $config);
            $this->upload->initialize($config);            
            if (!$this->upload->do_upload('file')) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data' => $this->upload->data());
            }
            if(empty($error)){
              if (!empty($data['upload_data']['file_name'])) {
                $import_xls_file = $data['upload_data']['file_name'];
            } else {
                $import_xls_file = 0;
            }
           $inputFileName = $path . $new_name;
                        //$inputFileName =$import_xls_file;

            try {
                $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
                $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel = $objReader->load($inputFileName);
                $allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
                $flag = true;
                $i=0;
                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
				    $REFNO = $emapData['A'];
				  		

						
				
				  
				  
				  
					if($REFNO!=""){
					//$confirm = $this->usermodel->populateallarray('contacts','phone',$REFNO);

	// if($confirm==false){
						
				
                   
						
						  $new_date=	date('Y-m-d');
                            $mydata = array(
                              
                           
							     'phone' => $emapData['A'],
                                 'createdate' => $currenttime,
 							    'name' => $name,
                                );
                    
        
	
	
	
	   $i++;
	
                  	
									

              							$usr_result = $this->usermodel->add($mydata,'contacts');
//}
					}               
}
                
                   	if ($usr_result ==TRUE) //active user record is present
							{
								 //echo "datasaved";
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully uploaded contacts!</div>');
								
								 redirect('upload');
							}
							else
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Contacts were not uploaded..Try again</div>');
								
								 redirect('upload');
							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            }
          }else{
              echo $error['error'];
            }
            
            }
        }


	
	
	
	
	
	
	
		public function autoloadmpesa()
	{ 
		
	$this->Splitmpesa();
		
		//redirect("http://127.0.0.1:86/pos.robisearch.com/sms.php");
		
$mydate=date('Y-m-d');
 
	 $companyid = 1;
		
	 	$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 $currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=(double)$day-1;
		   $add=(double)$day+1;
		        if ($subtract<10){
			  $subtract="0".$subtract;
		   }else{
			   $subtract=$subtract; 
		   }
		$finalstartdate="";
		$finalendate="";
		  $myfromdate=$smsconfig[0]['fromdate'];
		 $mytodate=$smsconfig[0]['todate'];
		 $starttime=$smsconfig[0]['starttime'];
		 $duetime=$smsconfig[0]['duetime'];
		 //echo $myfromdate;
			if(($myfromdate=="Current") &&($mytodate=="Current") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }else if(($myfromdate=="Current") &&($mytodate=="Next") &&  ($currenttime>=$starttime)){
	
		  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';
		
		 }
		 
		  else if(($myfromdate=="Current") &&($mytodate=="Current") && ($currenttime<$starttime)){
					  $finalstartdate=$year.'-'.$month.'-'.$day.' '. $starttime.':00';


				//	echo $finalstartdate;
		 }
		 
		 else if(($myfromdate=="Current") &&($mytodate=="Next") && ($currenttime<$starttime)){
					 if(($day=="01") || ($day=="1")){
				 
				 $currentdate=$year.'-'.$month.'-'.$day;

 $mynewfromdate = strtotime ( '-1 month' , strtotime ( $currentdate ) ) ;
$newfromdate = date ( 'Y-m-d' , $mynewfromdate );
$finalstartdate = date("Y-m-t", strtotime($newfromdate)).' '.$starttime.':00';
			 }else{
			
								  $finalstartdate=$year.'-'.$month.'-'.$subtract.' '. $starttime.':00';

			
			 }
	
		 }


		
		 
		 
		if(($mytodate=="Next") && ($currenttime>=$duetime)){
	
		  $finalendate=$year.'-'.$month.'-'.$add.' '. $duetime.':00';
				//echo $finalstartdate;
		
		 }else if(($mytodate=="Next") && ($currenttime<$duetime)){
			
		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';
		  
				//	echo $finalstartdate;
		 }else  if(($mytodate=="Current") && ($currenttime>=$duetime)){
		 		  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		 }else  if(($mytodate=="Current") && ($currenttime<$duetime)){
					  $finalendate=$year.'-'.$month.'-'.$day.' '. $duetime.':00';

		  
				//	echo $finalstartdate;
		 }
		 
				
				$config['base_url'] = base_url('Systemusers/viewprndingmoneyreceived');
			
	//$config['total_rows'] = $this->usermodel->count_allwheredata('sms_in','used',2,'amount>',0);
									$config['total_rows'] = $this->usermodel->count_allpendingmpesasalesbydate('sms_in',$finalstartdate, $finalendate,"all");

			
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		//$data['mycategory'] = $this->usermodel->populateproductcategorybyid($userid);
		
		 			        $data["mpesareport"] = $this->usermodel->displayallmpesapendingsalesbydate($config["per_page"], $page,'sms_in',$finalstartdate, $finalendate,"all");

	
			

        //$data["mpesareport"] = $this->usermodel->displayalldata($config["per_page"], $page,'sms_in','used',2,'amount>',0);

			
			
         $this->load->view("template/headerpagelogin");
		// $this->load->view("template/tableheader");
			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
		
	
		
			$this->load->view('userdata/autoloadmpesa',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
		
 public function printmpesacode() {
	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
		
		
		 if (!isset($_GET['code'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
	   
	
    
      $code= $_GET['code'];

        	
		 //$userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();

  $data['viewreceipt'] = $this->usermodel->getmpesalesbycode($code);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


     $invoiceid =$data['viewreceipt'][0]['id'];
$data['invoiceid'] = $invoiceid;
 $data['pendingorder']=$data['viewreceipt'];

if($data['viewreceipt'] ==false){
							$this->load->view('userdata/printmpesa', $data);


											

}else{
						$this->load->view('userdata/printmpesa', $data);
	
	
}

		}
	
  }
	
	
	
	
	
 public function printmpesa() {
	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
		


        	
		 //$userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();

  $data['viewreceipt'] = $this->usermodel->getmpesales($companyid);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
 $data['pendingorder']=$data['viewreceipt'];

     $invoiceid =$data['viewreceipt'][0]['id'];
$data['invoiceid'] = $invoiceid;
if($data['viewreceipt'] ==false){
							$this->load->view('userdata/printmpesa', $data);


											

}else{
						$this->load->view('userdata/printmpesa', $data);
	
	
}

				
		
	
  }
	
	
			public function startprintkitchenorder()
	{  
				  		 		 $branch = $this->input->post("branch");

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

										 redirect('printkitchenorder?branch='.$branch.'&categoryno='.$categoryno);

		
	}
	
			public function startdisplayingkitchenorder()
	{  
				  		 		 $branch = $this->input->post("branch");

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

										 redirect('displayorders?branch='.$branch.'&categoryno='.$categoryno);

		
	}
	
	
	
	
	
	
	 public function printlpo() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 	 $companyid = "1";
	 
	
        	$data['invoiceid'] = $invoiceid;
		
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('purchaseorder','invoice',$invoiceid);
		
		$data['companyid'] = $data['viewreceipt'][0]['companyid'];
		$data[' branchid'] = $data['viewreceipt'][0]['branchid'];
			$data['userid'] = $data['viewreceipt'][0]['userid'];
		
		
						$data['viewsales']  = $this->usermodel->populatealldatanoarray('newstock','invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	 $this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
				
						$this->load->view('printlpo', $data);
		
	}
  }
  
	
	
	
	
	
	
	
	
	
	
	  public function printlpo2() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 //$session_data = $this->session->userdata('logged_in');

  
	 $companyid = "1";
	 
	
        	$data['invoiceid'] = $invoiceid;
	
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarrayorderby('purchaseorderlist','id',"asc",'invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
									$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
						$this->load->view('userdata/printpurchaseordernoprice', $data);
												$this->load->view('userdata/printlpo', $data);

		
	}
  }
  
	
	
	   public function printquotation() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $invoiceid = $_GET['invoice'];
 //$session_data = $this->session->userdata('logged_in');

  
	 $companyid = "1";
	 
	
        	$data['invoiceid'] = $invoiceid;
	
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewreceipt'] = $this->usermodel->populateallarray('quotation','invoice',$invoiceid);
						$data['viewsales']  = $this->usermodel->populatealldatanoarrayorderby('purchaseorderlist','id',"asc",'invoice', $invoiceid,'companyid', $companyid);

          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

	
									$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
						$this->load->view('userdata/printquotationclient', $data);
		
	}
  }
  
  
  
 public function displayorders() {
	 
	 
	$this->load->view("template/headerpagelogin");
		//	$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
	$maincategory="";	
$mybranch="";
	  if (isset($_GET['branch'])){
$mybranch=$_GET['branch'];
    
   
    }
    else {
  $mybranch="1";
	 
	}
	
	  if (isset($_GET['categoryno'])){
$maincategory=$_GET['categoryno'];
    
   
    }
    
	 
	
	           		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);



//$data['orders']  = $this->usermodel->populatealldatanoarrayorderby('sales','id',"asc",'ordersales',"Ready",'companyid', 1);
$data['ordersready']  = $this->usermodel->populatealldatanoarrayorderby('sales','id',"asc",'ordersales',"new",'companyid', 1);






//$data['orders']  = $this->usermodel->populatealldatanoarrayorderby('sales','id',"asc",'ordersales',"new",'companyid', 1);
//$data['ordersready']  = $this->usermodel->populatealldatanoarrayorderby('sales','id',"asc",'ordersales',"Ready",'companyid', 1);

	$data['maincategory'] = $maincategory;
			  	$data['branch'] = $mybranch;
	//

//header('Refresh: 5');

											
					$this->load->view('userdata/displayorders', $data);
	
	

		$this->load->view("template/footerpage");

				
		
	
  }
	
	
	
	
  
	
	
	
	
 public function displayorders222() {
	 
	 
	$this->load->view("template/headerpagelogin");
		//	$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
	$maincategory="";	
$mybranch="";
	  if (isset($_GET['branch'])){
$mybranch=$_GET['branch'];
    
   
    }
    else {
  $mybranch="1";
	 
	}
	
	  if (isset($_GET['categoryno'])){
$maincategory=$_GET['categoryno'];
    
   
    }
    
	 
	
	           		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

$data['orders']  = $this->usermodel->populatealldatanoarrayorderby('sales','id',"asc",'ordersales',"new",'companyid', 1);
$data['ordersready']  = $this->usermodel->populatealldatanoarrayorderby('sales','id',"asc",'ordersales',"Ready",'companyid', 1);

	$data['maincategory'] = $maincategory;
			  	$data['branch'] = $mybranch;
	//

header('Refresh: 5');

											
					$this->load->view('userdata/displayorders', $data);
	
	

		$this->load->view("template/footerpage");

				
		
	
  }
	
	
	
	
	 public function clearcontacts() {
	

	 
	 	
				
	$usr_result=  $this->usermodel->truncatemydata("contacts");		


   
  
		if ($usr_result ==TRUE) //active user record is present
							{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully cleared contacts.. ..</div>');	
										 redirect('upload');
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Contacts were not cleared. Try again</div>');
								
										 redirect('upload');
							}
	 
	 
	 
	 
	 	 
	 
	
	 }
	
	
	
	
	 public function serveorder() {
	   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	  $dateposted = date('Y-m-d H:i:s');

	$this->load->view("template/headerpagelogin");
    	 $companyid = 1;
	$maincategory="";	
$mybranch="";
	  if (isset($_GET['branch'])){
$mybranch=$_GET['branch'];
    
   
    }
    else {
  $mybranch="1";
	 
	}
	
	
    	 	  $maincategory = trim($_GET['categoryno']);

	
	   
	 	  $myid = trim($_GET['randomitemidentifier']);

	 
	 	  $data = array(
			'ordersales'=>"Served",
			'updatedat'=>$dateposted,
					//'updatedby'=>$userid,

             );	
				
	  		$usr_result = $this->usermodel->updatedata($data,'sales','id',$myid);
		
			

   
  
		if ($usr_result ==TRUE) //active user record is present
							{
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully served  the order  ..</div>');	
										 redirect('displayorders?branch='.$mybranch.'&categoryno='.$maincategory);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Order was not served.. Try again</div>');
								
										 redirect('displayorders?branch='.$mybranch.'&categoryno='.$maincategory);
							}
	 
	 
	 
	 
	 }	 
	 
	
	 }
	
	
	
	
	
 public function printkitchenorder() {
	 
	//$this->load->view("template/headerpagelogin");
		//$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
	$maincategory="";	
$mybranch="";
	  if (isset($_GET['branch'])){
$mybranch=$_GET['branch'];
    
   
    }
    else {
  $mybranch="1";
	 
	}
	
	  if (isset($_GET['categoryno'])){
$maincategory=$_GET['categoryno'];
    
   
    }
    else {
  //$mybranch="1";
	 
	}
	 
	 
	 
	 
	 
	 $pendingorder = $this->usermodel->getpendingorder($mybranch,$companyid,$maincategory);
		
     $invoiceid = $pendingorder[0]['invoice'];
	 
	 
	 
	 
	 
// $session_data = $this->session->userdata('logged_in');

    //$data['companyid'] = $session_data['companyid'];
	// $companyid = $data['companyid'];
	 

	//$data['id'] = $session_data['id'];
        	$data['maincategory'] = $maincategory;
			$data['invoiceid'] = $invoiceid;
			  	$data['branch'] = $mybranch;
		 //$userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateprintinvoice($mybranch,$invoiceid);
  $data['viewsales'] = $this->usermodel->getesalesmy_orderkitchen($invoiceid,$companyid,$mybranch,$maincategory);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$data['pendingorder']=$pendingorder;


//
//header('Refresh: 30');

if($pendingorder ==false){
							$this->load->view('userdata/printkitchenorder', $data);


											

}else{
						$this->load->view('userdata/printkitchenorder', $data);
	
	
}

				
		
	
  }
	
	
	
	
	
 public function printkitchenorder1() {
	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
	$maincategory="";	
$mybranch="";
	  if (isset($_GET['branch'])){
$mybranch=$_GET['branch'];
    
   
    }
    else {
  $mybranch="1";
	 
	}
	
	  if (isset($_GET['categoryno'])){
$maincategory=$_GET['categoryno'];
    
   
    }
    else {
  //$mybranch="1";
	 
	}
	 
	 
	
	 

        	$data['maincategory'] = $maincategory;
			//$data['invoiceid'] = $invoiceid;
			  	$data['branch'] = $mybranch;


//
//header('Refresh: 5');


							$this->load->view('userdata/printkitchenorder', $data);


											


				
		
	
  }
	
 public function mainprintkitchenorder() {
	///$this->load->view("template/headerpagelogin");
			//$this->load->view("template/headerpagegeneral");
    	 $companyid = 1;
	$maincategory="";	
$mybranch="";
	  if (isset($_GET['branch'])){
$mybranch=$_GET['branch'];
    
   
    }
    else {
  $mybranch="1";
	 
	}
	
	  if (isset($_GET['categoryno'])){
$maincategory=$_GET['categoryno'];
    
   
    }
    else {
  //$mybranch="1";
	 
	}
	 
	 
	 
	 
	 
	 $pendingorder = $this->usermodel->getpendingorder($mybranch,$companyid,$maincategory);
		
     $invoiceid = $pendingorder[0]['invoice'];
	 
	 
	 
	 
	 
// $session_data = $this->session->userdata('logged_in');

    //$data['companyid'] = $session_data['companyid'];
	// $companyid = $data['companyid'];
	 

	//$data['id'] = $session_data['id'];
        	$data['maincategory'] = $maincategory;
			$data['invoiceid'] = $invoiceid;
			  	$data['branch'] = $mybranch;
		 //$userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateprintinvoice($mybranch,$invoiceid);
  $data['viewsales'] = $this->usermodel->getesalesmy_orderkitchen($invoiceid,$companyid,$mybranch,$maincategory);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$data['pendingorder']=$pendingorder;


//
//header('Refresh: 5');

if($pendingorder ==false){
							$this->load->view('userdata/printkitchenorderload', $data);


											

}else{
						$this->load->view('userdata/printkitchenorderload', $data);
	
	
}

				
		
	
  }
	
	
	 public function getallreceipts()
    {
		
			
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 
 	 		
 $type = $this->input->post("type");
$refnumber = $this->input->post("refnumber");
	  
	  

			  		  $this->form_validation->set_rules("refnumber", "Ref number", "trim|required");

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

		
		 $this->load->view('receipts ', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_Viewreceiptsinvoice') == "receipts")
					   {
						   
						
						   	$getsales = $this->usermodel->populateallarray('sales','invoice',$refnumber);
if($getsales==false){
	
	
			 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> That Refrence Number does not exist. Kindly put the correct Refrence Number then Try again</div>');
								
								 redirect('receipts');
								 return false;
	
	
	
	
	
}
   
					   
						   if( $type =="receipt"){
					
  

  
									$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");


		
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($refnumber);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($refnumber,1);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',1);

				
						$this->load->view('printa4receipt', $data);
		
						  



						  }else{
							 
							   
									$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
$data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($refnumber);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($refnumber,1);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',1);

				
						$this->load->view('printinvoice', $data);   
							   
							   
						
							   
							   
							   
						   }
 
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
						
					   }
					   else
					   {
							//redirect('login');
					   }
	    }
    }
	
	
	
	
	
	public function pay()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		
		if(isset($_GET['msg'])) {
			      $msg = $_GET['msg'];

			$data['msg']=$msg;
		 $this->load->view('pay', $data);
			 }else{
				$this->load->view('pay');

			 }
		$this->load->view("template/footerpage");
	}
	
	
	public function upload()
	{  	$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		
		if(isset($_GET['msg'])) {
			      $msg = $_GET['msg'];

			$data['msg']=$msg;
		 $this->load->view('upload', $data);
			 }else{
				$this->load->view('upload');

			 }
		$this->load->view("template/footerpage");
	}
	
	
	     
  public function paynow() {
	     

	 $companyid = 1;
	 $branchid = 1;
	$amount = trim($this->input->post("total"));

	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
$myconsumer_key=$configuration[0]["consumer_key"];
$myconsumer_secret=$configuration[0]["consumer_secret"];
$shortcode=$configuration[0]["shortcode"];
$confirmationurl=$configuration[0]["confirmationurl"];
$passkey=$configuration[0]["responseType"];

$errors  = array();
$errmsg  = '';
/*
$config = array(

//

    "env"              => "live",
    "BusinessShortCode"=> $shortcode,
    "key"              => $myconsumer_key, //Enter your consumer key here
    "secret"           => $myconsumer_secret, //Enter your consumer secret here
    "username"         => "",
    "TransactionType"  => "CustomerPayBillOnline",
	 "code" => $shortcode, // business short code
	  "till" => responseType,
	  "initiator" => "cashier", // optional initiator name
	"credential" => "levi-cred++==" , // optional security credential

    "passkey"          => $passkey, //Enter your passkey here
    "CallBackURL"      => $confirmationurl, //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);


*/


/*
$config = array(
    "env"              => "live",
    "BusinessShortCode"=> "4956000",
    "key"              => "cUKRTIfdj4l02VSyyBsQggcFz3b4LY52BSBvCycOnyU7fAf7", //Enter your consumer key here
    "secret"           => "A4e1qzuGP1bSNooALFFSXCLL9ZDt0xJZzuPlkaJJoaiBMxIXWtwNr0tfa2bU4fyV", //Enter your consumer secret here
    "username"         => "",
    "TransactionType"  => "CustomerPayBillOnline",
	
    "passkey"          => "16acf8f91f75b4f9766eb50f7f5d686cea54e6032ab69c01f08b26fd46605fd0", //Enter your passkey here
    "CallBackURL"      => "http://erp.robisearch.com/getpayment", //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);

*/


$config = array(
    "env"              => "live",
    "BusinessShortCode"=> $shortcode,
	
	"key"              => $myconsumer_key, //Enter your consumer key here
    "secret"           => $myconsumer_secret, //Enter your consumer secret here
    "username"         => "",
  // "TransactionType"  => "CustomerPayBillOnline",
	"TransactionType"  => "CustomerBuyGoodsOnline",

    "passkey"          => $passkey, //Enter your passkey here
    "CallBackURL"      => $confirmationurl, //When using localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "POS PAYMENT" ,
);


/*

$errors  = array();
$errmsg  = '';

$config = array(
    "env"              => "live",
    "BusinessShortCode"=> "4079491",
    "key"              => "6ZTfjQGGySUWUxLnB4IUzmZy3AbD8Zkp", //Enter your consumer key here
    "secret"           => "E2fGPbNy9JzHC93N", //Enter your consumer secret here
    "username"         => "judiest",
    "TransactionType"  => "complete",
    "passkey"          => "bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919", //Enter your passkey here
    "CallBackURL"      => "http://erp.robisearch.com/getpayment", //When using Localhost, Use Ngrok to forward the response to your Localhost
    "AccountReference" => "".$_POST['invoice']."",
    "TransactionDesc"  => "Bulk SMS" ,
);

*/

if (isset($_POST['phone'])) {

    $phone = $_POST['phone'];
    $orderNo = $_POST['invoice'];
   // $amount = 5;

    $phone = (substr($phone, 0, 1) == "+") ? str_replace("+", "", $phone) : $phone;
    $phone = (substr($phone, 0, 1) == "0") ? preg_replace("/^0/", "254", $phone) : $phone;
    $phone = (substr($phone, 0, 1) == "7") ? "254{$phone}" : $phone;



    $access_token = ($config['env']  == "live") ? "https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" : "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials"; 
    $credentials = base64_encode($config['key'] . ':' . $config['secret']); 
    
    $ch = curl_init($access_token);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Basic " . $credentials]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $response = curl_exec($ch);
    curl_close($ch);



    $result = json_decode($response); 
    $token = isset($result->{'access_token'}) ? $result->{'access_token'} : "N/A";

    $timestamp = date("YmdHis");
    $password  = base64_encode($config['BusinessShortCode'] . "" . $config['passkey'] ."". $timestamp);

    $curl_post_data = array( 
        "BusinessShortCode" => $config['BusinessShortCode'],
        "Password" => $password,
        "Timestamp" => $timestamp,
        "TransactionType" => $config['TransactionType'],
        "Amount" => $amount,
        "PartyA" => $phone,
		"PartyB" => $configuration[0]["totalsms"],

        //"PartyB" => "772740",
		//"PartyB" => "5660349",
		 
        "PhoneNumber" => $phone,
        "CallBackURL" => $config['CallBackURL'],
        "AccountReference" => $config['AccountReference'],
        "TransactionDesc" => $config['TransactionDesc'],
    ); 

    $data_string = json_encode($curl_post_data);

    $endpoint = ($config['env'] == "live") ? "https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest" : "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"; 

    $ch = curl_init($endpoint );
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer '.$token,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response     = curl_exec($ch);
    curl_close($ch);

    $result = json_decode(json_encode(json_decode($response)), true);

    if(!preg_match('/^[0-9]{10}+$/', $phone) && array_key_exists('errorMessage', $result)){
        $errors['phone'] = $result["errorMessage"];
    }
	

    if($result['ResponseCode'] === "0"){
		
		
		 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Request has been sent to phone No:('.$phone.') . Kindly key in your pin to complete the sale.  </div>');
	redirect($myview,$data);
		
		
		return false;
		
		
        //STK Push request successful
        
        $MerchantRequestID = $result['MerchantRequestID'];
        $CheckoutRequestID = $result['CheckoutRequestID'];

        $conn = mysqli_connect("localhost","root","","mpesa");
       
        $sql = "INSERT INTO orders(ID, OrderNo, Amount, Phone, CheckoutRequestID, MerchantRequestID) VALUES ('','".$orderNo."','".$amount."','".$phone."','".$CheckoutRequestID."','".$MerchantRequestID."');";
        
        if ($conn->query($sql) === TRUE){
            $_SESSION["MerchantRequestID"] = $MerchantRequestID;
            $_SESSION["CheckoutRequestID"] = $CheckoutRequestID;
            $_SESSION["phone"] = $phone;
            $_SESSION["orderNo"] = $orderNo;

            header('location: confirm-payment.php');
        }else{
            $errors['database'] = "Unable to initiate your order Please contact Kemru on system@kemrut.com: ".$conn->error;;  
            foreach($errors as $error) {
                $errmsg .= $error . '<br />';
            } 
        }
        
    }else{
        $errors['mpesastk'] = $result['errorMessage'];
        foreach($errors as $error) {
            $errmsg .= $error . '<br />';
        }
    }
    
}





	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') could be wrong or there is configuration error..try again  </div>');
	redirect($myview,$data);	
		 }
   
	
	
  public function paynow2() {
	     

	 $companyid = 1;
	 $branchid = 1;
	$amount = trim($this->input->post("total"));

	$phone = trim($this->input->post("phone"));
			 //$phone = htmlspecialchars($phone);
	  		  		  $this->form_validation->set_rules("phone", "phone", "trim|required|xss_clean");

    $salesid = $this->input->post("invoice");
	    $myview = $this->input->post("myview");



	$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

$restricttill=$configuration[0]["restricttill"];
$myconsumer_key=$configuration[0]["consumer_key"];
$myconsumer_secret=$configuration[0]["consumer_secret"];
$shortcode=$configuration[0]["shortcode"];
$confirmationurl=$configuration[0]["confirmationurl"];
$passkey=$configuration[0]["responseType"];

$errors  = array();
$errmsg  = '';



	  #Callback url
	 // define('LNMO_CALLBACK_URL', 'https://abansacco.co.ke/include/callback_url.php?orderid=');

	  # access token
	 $consumerKey =$myconsumer_key; //Fill with your app Consumer Key
	 $consumerSecret = $myconsumer_secret; // Fill with your app Secret

	  # provide the following details, this part is found on your test credentials on the developer account
	  $BusinessShortCode = $shortcode; //business short code
	  $Passkey = $passkey; //live passkey
	  $phone = preg_replace('/^0/', '254', str_replace("+", "", $phone));
	  $PartyA = $phone; // This is your phone number,
	  $PartyB = $shortcode;
	  $TransactionDesc = 'Pay Order'; //Insert your own description
	  # Get the timestamp, format YYYYmmddhms -> 20181004151020
	  $Timestamp = date('YmdHis');    
	  # Get the base64 encoded string -> $password. The passkey is the M-PESA Public Key
	  $Password = base64_encode($shortcode.$passkey.$Timestamp);
	  # header for access token
	  $headers = ['Content-Type:application/json; charset=utf8'];
 





	  # M-PESA endpoint urls
	  $access_token_url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
	  $initiate_url = 'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest';  

	  $curl = curl_init($access_token_url);
	  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
	  curl_setopt($curl, CURLOPT_HEADER, FALSE);
	  curl_setopt($curl, CURLOPT_USERPWD, $consumerKey.':'.$consumerSecret);
	  $result = curl_exec($curl);
	  $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	  $result = json_decode($result);
	 // $access_token = $result->access_token;  
    $access_token = isset($result->{'access_token'}) ? $result->{'access_token'} : "N/A";




	  curl_close($curl);

	  # header for stk push
	  $stkheader = ['Content-Type:application/json','Authorization:Bearer '.$access_token];
	  # initiating the transaction

	  $curl = curl_init();
	  curl_setopt($curl, CURLOPT_URL, $initiate_url);
	  curl_setopt($curl, CURLOPT_HTTPHEADER, $stkheader); //setting custom header
	  
	  $curl_post_data = array(

		//Fill in the request parameters with valid values
		'BusinessShortCode' => $shortcode,
		'Password' => $Password,
		'Timestamp' => $Timestamp,
	 "TransactionType"  => "CustomerPayBillOnline",

		//'TransactionType' => 'CustomerBuyGoodsOnline', // 
		'Amount' => $amount,
		'PartyA' => $phone,
		'PartyB' => $shortcode,
		'PhoneNumber' => $phone,
		'CallBackURL' => $confirmationurl,
		'AccountReference' => "".$_POST['invoice']."",
		'TransactionDesc' => "pos payments"
	  );

	  $data_string = json_encode($curl_post_data);
	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	  curl_setopt($curl, CURLOPT_POST, true);
	  curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
	  $curl_response = curl_exec($curl);


		$result = json_decode(json_encode(json_decode($curl_response)), true);

	  //$ResponseCode = $result['ResponseCode'];
	 // return $ResponseCode;
var_dump($curl_response);
exit;



    //if($result['ResponseCode'] === "0"){









	 	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>That Code/Phone number('.$phone.') could be wrong or there is configuration error..try again  </div>');
	redirect($myview,$data);	

  }
 
 
	
	
	
	
	
	  public function clearfiles() {
	
$timeout = Date('Y-m-d H:i:s') ;

  $dir='qrcodes/';
	

  //$dir = "cache/"; /** define the directory **/

/*** cycle through all files in the directory ***/
foreach (glob($dir."*") as $file) {
//foreach (glob($dir.'*.*') as $file){
	//echo $file;

/*** if file is 24 hours (86400 seconds) old then delete it ***/
if (filemtime($file) < time() - 604800) {
	// 1 hour
	echo $file;
   unlink($file);
    }
}


  		 redirect('login', 'refresh');
       
    }
	
	  public function pintreceipt() {
   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		$this->load->view("template/headerpagelogin");
	//	$this->load->view("template/headerpagegeneral");


		
 $data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($refnumber);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($refnumber,1);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',1);

				
						$this->load->view('printa4receipt', $data);
		
		
	}
  }
  
	
	
		  public function printinvoice() {
   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		


			$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
$data['setting'] = $this->usermodel->getsetting();
 $data['viewreceipt'] = $this->usermodel->populateinvoice($refnumber);
  $data['viewsales'] = $this->usermodel->getesales_orderReceipt($refnumber,1);
          		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',1);

				
						$this->load->view('printinvoice', $data);   
							   
		
		
	}
  }
  
	
	
	
	
	
	
	
		
		public function deletefiles()
	{  	
		$count=0;
		   if (isset($_GET['count'])){
		
		    $count=$_GET['count'];
		   }else{
			$count=0;   
			   
		   }

		
		   for($i=1; $i< $count; $i++) {
			  
		//$file_with_path="/home/robisear/getAlerts. ".$i;
		 		//$file_with_path="/home/robisear/Alert.".$i;
		 	$file_with_path="/home/robisear/Alert.".$i.".1";
		 	//$file_with_path="/home/robisear/Alert.".$i.".2";
		 	//$file_with_path="/home/robisear/Alert.".$i.".3";

		 if (file_exists($file_with_path)) {
  if(unlink($file_with_path)){
				 //echo "removed";
			 }else{
				 echo " Not removed"; 
			 }
  
				
		 
			   }
	}
	
	}
	
		public function aboutus()
	{  	
		 $data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);

	$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
					$this->load->view('userdata/aboutus',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
			public function contact()
	{  	
	$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);


					$this->load->view('userdata/contact',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
	
	
	
	public function blog()
	{  	
	$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['blogs'] = $this->usermodel->populateall('blog','companyid',1);





					$this->load->view('userdata/blog',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
	
	
	public function career()
	{  	
	$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);






					$this->load->view('userdata/career',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
	
	
	public function whyus()
	{  	
$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);




					$this->load->view('userdata/whyus',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
	
	
	
	
	
	
	
	
		
	public function terms()
	{  	
	$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);




					$this->load->view('userdata/terms',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
		
	public function faqs()
	{  	
		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['faqs'] = $this->usermodel->populateall('faqs','companyid',1);




					$this->load->view('userdata/faqs',$data);

		
	$this->load->view("template/footerpagecommerce");



	}
		
	public function delivery()
	{  	
			$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);






					$this->load->view('userdata/delivery',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
		
	public function privacy()
	{  
	
$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['smsconfig'] = $this->usermodel->populateallarray('contactdetails','companyid',1);






					$this->load->view('userdata/privacy',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
	
	
	
	
	
	
	
	
	
	
	
		
	public function brands()
	{  	
	$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
			$data['brand'] = $this->usermodel->populateall('brands','companyid',1);


					$this->load->view('userdata/brands',$data);

		
	$this->load->view("template/footerpagecommerce");
	}
	
	
	
	
	
	
	
		public function page404()
	{  	 $this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");
		
		

	
		//$this->load->view('userdata/nopayment');

		$this->load->view('page404');


	
}





public function login()
	{  	$this->load->view("template/headerpagelogin");
		$this->load->view("template/headerpagegeneral");
	
		
			
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $view=$smsconfig[0]['view'];	


	
						

if(($view=="CompleteTouch")|| ($view=="TouchOnly")|| ($view=="Restaurant")){
		$this->load->view('index');

	
}else{
		$this->load->view('indexmain');


	
}

		$this->load->view("template/footerpage");
	}
	











	
	public function index()
	{ 

		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	

 $ecommerce=$smsconfig[0]['ecommerce'];	

 $landingpage=$smsconfig[0]['landingpage'];
 $currencysymbol=$smsconfig[0]['currencysymbol'];

 
  
  
  
  
  if($ecommerce=="activate"){
	  
	   if($landingpage=="category"){
	  								$config['base_url'] = base_url('Userpage/Viewcategory');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('productcategory','companyid',$companyid,'status',"active");

							$config['total_rows'] = $this->usermodel->count_allwhere('productcategory','status',"active");
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productcategory','status',"active");
		$data["currencysymbol"]=$currencysymbol;

				


		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/landingpagecategory',$data);
				
		$this->load->view("template/footerpagecommerce");
									 
							
	   }else{



				
				$config['base_url'] = base_url('Userpage/viewproductlist');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'status',"active");

							$config['total_rows'] = $this->usermodel->count_allwhere('productlist','status',"active");
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','status',"active");
		$data["currencysymbol"]=$currencysymbol;

				


		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/landingpage',$data);
				
		$this->load->view("template/footerpagecommerce");
		
		
	   }

  }else{
	  
	  




 	$this->load->view("template/headerpagelogin");
		
		$this->load->view("template/headerpagegeneral");
		
		
		
		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $view=$smsconfig[0]['view'];	


	
	
if(($view=="CompleteTouch")|| ($view=="TouchOnly")){					


		$this->load->view('index');

	
}else{
		$this->load->view('indexmain');


	
}

		$this->load->view("template/footerpage");
		
  }
	}
	
	
	
	
	
	
  public function searchallproduct()
	{
		

		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];

	 
	 
	 
	 
	  $codes = explode(':=',$this->input->post("searchterm"));

 
  $searchterm = htmlspecialchars(trim($codes[0]));
	 
	 

		//$searchterm = trim($this->usermodel->searchterm_handler($this->input->get_post('searchterm', TRUE)));
		
		
		$limit = ($this->uri->segment(3) > 0)?$this->uri->segment(3):0;
		
		$config['base_url'] = base_url() . 'User/searchallproduct';
		$config['total_rows'] = $this->usermodel->searchallproducts_count($searchterm);
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";
		$page = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);
				$data["currencysymbol"]=$currencysymbol;

		$data['viewproducts'] = $this->usermodel->searchallproducts($searchterm,$limit);
		
		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 	$this->load->view("template/headerpagelogin");

		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
		
$data["page"]=$page;
		 $data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
				$this->load->view('userdata/allproducts',$data);
				
				$this->load->view("template/footerpagecommerce");

	}
	

	
	 public function viewitem() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];

	 
     $itemid = $_GET['randomitemidentifier'];

   			        		$data['viewproducts'] = $this->usermodel->populateallarray('productlist','id', $itemid);


		
		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");
$data['itemid']=$itemid;
	$data['currencysymbol']=$currencysymbol;	
		 $this->load->view('userdata/viewitem', $data);
		$this->load->view("template/footerpagecommerce");
		
	}
  }
  
  
  
	
	
	
	
	
	
	public function upgrade()
	{ 
		
		


		$this->load->view("template/headerpagelogin");
			$this->load->view("template/headerpagegeneral");




	
		$this->load->view("template/tableheader");

				
				$config['base_url'] = base_url('User/upgrade');

		$config['total_rows'] = $this->usermodel->count_allwhere('upgrade','status',"active");
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		        $data["upgrade"] = $this->usermodel->displayall($config["per_page"], $page,'upgrade','status',"active");

				
     


		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
		
			$this->load->view('userdata/upgrade',$data);
				
		$this->load->view("template/footerpage");
	
	}
 
 

	
	
	
	
	
	 public function viewproductsbypreference()
	{ 
		
	   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		

		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];




				
				$config['base_url'] = base_url('User/viewproductsbypreference');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'supplier',$refnumber);

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
														
		$config['per_page'] = '200';
								$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
										        $data["viewproducts"] = $this->usermodel->viewreportbycustomedcategoryuser($config["per_page"], $page,"productsgrouping",$companyid,$refnumber) ;
$config['total_rows']=count($data["viewproducts"] );
			$config['uri_segment'] = 3;

		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
	
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
				//($config["per_page"], $page,'productlist','supplier',$refnumber);
		$data["currencysymbol"]=$currencysymbol;

				
     

		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allproducts',$data);
				
		$this->load->view("template/footerpagecommerce");
	}
	}
 
	
	
	
	
	 public function viewproductsbypreferenceandcategory()
	{ 
		
	   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		
   $category = $_GET['category'];
		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];




				
				$config['base_url'] = base_url('User/viewproductsbypreferenceandcategory');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'supplier',$refnumber);

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
														
		$config['per_page'] = '200';
								$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
										        $data["viewproducts"] = $this->usermodel->viewproductsbypreferenceandcategory($config["per_page"], $page,"productsgrouping",$companyid,$refnumber,$category) ;
$config['total_rows']=count($data["viewproducts"] );
			$config['uri_segment'] = 3;

		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
	
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
				//($config["per_page"], $page,'productlist','supplier',$refnumber);
		$data["currencysymbol"]=$currencysymbol;

				
     

		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allproducts',$data);
				
		$this->load->view("template/footerpagecommerce");
	}
	}
 
	
	 public function viewproductsbybrand()
	{ 
		
	   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		

		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];




				
				$config['base_url'] = base_url('User/viewproductsbybrand');
									$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'supplier',$refnumber);

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','supplier',$refnumber);
		$data["currencysymbol"]=$currencysymbol;

				
     

		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allproducts',$data);
				
		$this->load->view("template/footerpagecommerce");
	}
	}
 
	
	
	
	
	 public function viewproductsbycategory()
	{ 
		
	   if (!isset($_GET['refnumber'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $refnumber = $_GET['refnumber'];
		

		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];



 $landingpage=$smsconfig[0]['landingpage'];
 $currencysymbol=$smsconfig[0]['currencysymbol'];

 
  
  
  
 

				
				$config['base_url'] = base_url('User/viewproductsbycategory');
									$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'category',$refnumber);

							//$config['total_rows'] = $this->usermodel->count_allwhere('productlist','companyid',$companyid);
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','category',$refnumber);
		$data["currencysymbol"]=$currencysymbol;

			$data["landingpage"]=$landingpage;	
     			$data["refnumber"]=$refnumber;	


		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allproducts',$data);
				
		$this->load->view("template/footerpagecommerce");
	}
	}
 
	
		 public function Viewcategory()
	{ 
		
	
		

		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];




				
				$config['base_url'] = base_url('User/Viewcategory');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'status',"active");

							$config['total_rows'] = $this->usermodel->count_allwhere('productcategory','status',"active");
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productcategory','status',"active");
		$data["currencysymbol"]=$currencysymbol;

				
     

		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/landingpagecategory',$data);
				
		$this->load->view("template/footerpagecommerce");
	
	}
 
 
	
	
	 public function viewproductlist()
	{ 
		
	
		

		
		 $smsconfig = $this->usermodel->populateallarray('smsconfig','id',1);
		 	  $companyid=$smsconfig[0]['id'];	

  $companyid=$smsconfig[0]['id'];	


 $currencysymbol=$smsconfig[0]['currencysymbol'];




				
				$config['base_url'] = base_url('User/viewproductlist');
									//$config['total_rows'] = $this->usermodel->count_allwheredata('productlist','companyid',$companyid,'status',"active");

							$config['total_rows'] = $this->usermodel->count_allwhere('productlist','status',"active");
		$config['per_page'] = '20';
		$config['uri_segment'] = 3;
		$config['full_tag_open'] = "<ul class='pagination'>";
		$config['full_tag_close'] ="</ul>";
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';
		$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
		$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
		$config['next_tag_open'] = "<li>";
		$config['next_tagl_close'] = "</li>";
		$config['prev_tag_open'] = "<li>";
		$config['prev_tagl_close'] = "</li>";
		$config['first_tag_open'] = "<li>";
		$config['first_tagl_close'] = "</li>";
		$config['last_tag_open'] = "<li>";
		$config['last_tagl_close'] = "</li>";

		$this->pagination->initialize($config);
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		$data['mycategory'] = $this->usermodel->populateproductcategorybyid($companyid);
		        //$data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','companyid',$companyid);
		        $data["viewproducts"] = $this->usermodel->displayall($config["per_page"], $page,'productlist','status',"active");
		$data["currencysymbol"]=$currencysymbol;

				
     

		$this->load->view("template/headerlogincommerce");
						$this->load->view("template/usepagernave");

			//$data['total_people'] = $this->usermodel->countMembers($userid); 
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
			$this->load->view('userdata/allproducts',$data);
				
		$this->load->view("template/footerpagecommerce");
	
	}
 
 
	
	
	
	public function loginusers()
    {
          //get the posted values
          $username = $this->input->post("username");
          $password = $this->input->post("password");

          //set validations
          $this->form_validation->set_rules("username", "Username", "trim|required");
          $this->form_validation->set_rules("password", "Password", "trim|required");
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
            $this->load->view("template/adminheaderpage");
		
		$this->load->view('adminloginpage');
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_login') == "login")
					   {
								$usr_result = $this->adminusermodel->getusers($username, $password);
							//check if username and password is correct
							if ($usr_result > 0) //active user record is present
							{
								 //set the session variables
								 $sessiondata = array(
									  'username' => $usr_result[0]->username,
									  'adminid' => $usr_result[0]->id,
									 'firstname' =>  $usr_result[0]->firstname,
									 'surname' =>  $usr_result[0]->surname,
									  'name' =>  $usr_result[0]->surname." ". $usr_result[0]->firstname,
									  'type' => $usr_result[0]->type, 
									  'email' =>  $usr_result[0]->email, 
									  'status' =>  $usr_result[0]->status

								 );
								  $this->session->set_userdata('adminadminlogged_in', $sessiondata);

								 
								 redirect("administrator/home");

								  //echo "welcome";
							}
							else
							{     

								 $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Incorrect Username or Password... Try again or contact system administrator.</div>');
								
								 redirect('admin');
							}
					   }
					   else
					   {
							redirect('administrator');
					   }
	    }
    }

	
	
	
	
	
	
	
	
	
	
	
	
		public function admin()
	{ 	
		$this->load->view("template/adminheaderpage");
		$this->load->view("template/headerpagegeneral");
		$this->load->view('adminloginpage');
		$this->load->view("template/footerpage");
	}
		
	
	
	
	
	public function index1()


	{ 
		$session_data = $this->session->userdata('adminlogged_in');


		
	 $this->load->view("template/adminheaderpage");
	  $data['campus'] = $this->campusmodel->populatecampus();
$data['college'] = $this->collagemodel->populatecollage();
$data['user'] = $this->adminusermodel->populateusers();
$data['department'] = $this->departmentmodel->populatedepartment();
		$this->load->view("template/adminnave");
		 $this->load->view('admindata/user',$data);
		$this->load->view("template/footerpage");
     
	}
		
	
	
 public function addnewuser()
    {
         
		  	 $surname = $this->input->post("surname");
		  	  $firstname = $this->input->post("firstname");
		  	  	  $email = $this->input->post("email");
		  	  	  	  $username = $this->input->post("username");
		  	  	  	    $password = $this->input->post("password");
		  	  	  	  	  $phone = $this->input->post("phone");
		  	  	  	  	  	  $campus = $this->input->post("campus");
		  	  	  	  	  	  	  $college = $this->input->post("college");
		  	  	  	  	  	  	  	  $department = $this->input->post("department");
 	  $status = $this->input->post("status");


		   	

		  $this->form_validation->set_rules("username", "Pf Number", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/adminheaderpage");
		$this->load->view("template/adminnave");
		 $this->load->view('admindata/user',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_adduser') == "user")
					   {
								
								$data=array(		
			'surname'=>$surname,
		  	'firstname'=>$firstname,
				'idno'=>$idno,
		  	'email'=>$email,
		  	'username'=>$username,
		  	'phone'=>$phone,
		  	'campus'=>$campus,
		  	'college'=>$college,
		  	'department'=>$department,
			'password'=>$password,
		  		'status'=>$status,
			
								);
							$usr_result = $this->adminusermodel->sigadmin($data);
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new admin!</div>');
								
								 redirect('admin/user');
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. That pf number exist! Just login</div>');
								
								 redirect('admin/user');
							}
					   }
					   else
					   {
							redirect('admin');
					   }
	    }
    }		
	
			 


			 public function updateuser()
    {
         
		  	 $surname = $this->input->post("surname");
		  	  $firstname = $this->input->post("firstname");
		  	  	  $email = $this->input->post("email");
		  	  	  	  $username = $this->input->post("username");
		  	  	  	    $password = $this->input->post("password");
		  	  	  	  	  $phone = $this->input->post("phone");
		  	  	  	  	  	  $campus = $this->input->post("campus");
		  	  	  	  	  	  	  $college = $this->input->post("college");
		  	  	  	  	  	  	  	  $department = $this->input->post("department");
 	  $status = $this->input->post("status");


		   	

		  $this->form_validation->set_rules("username", "Pf Number", "trim|required");
		    
			
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/adminheaderpage");
		$this->load->view("template/adminnave");
		 $this->load->view('admindata/adminpage',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_adduser') == "user")
					   {
								
								$data=array(		
			'surname'=>$surname,
		  	'firstname'=>$firstname,
				'idno'=>$idno,
		  	'email'=>$email,
		  	'username'=>$username,
		  	'phone'=>$phone,
		  	'campus'=>$campus,
		  	'college'=>$college,
		  	'department'=>$department,
			'password'=>$password,
		  		'status'=>$status,
			
								);
							$usr_result = $this->adminusermodel->sigadmin($data);
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 
								 
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> You have successfully Added new admin!</div>');
								
								 redirect('admin/user');
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Data are not saved.. That pf number exist! Just login</div>');
								
								 redirect('admin/user');
							}
					   }
					   else
					   {
							redirect('admin');
					   }
	    }
    }		
	 function __destruct() {

        $this->db->close();

    }
	
	
	
	   public function logout() {
        $data = ['id', 'username'];
        $this->session->set_userdata('adminlogged_in');
		session_destroy();

  		 redirect('administrator', 'refresh');
       
    }
	
	
	
	
}
 ?>