<?php
ob_start();
//ini_set('display_errors', 'Off');
ini_set('display_errors', 'Off');
//ini_set('error_reporting', E_ALL);
defined('BASEPATH') OR exit('No direct script access allowed');
 //ini_set('error_reporting', E_ALL);
//ini_set('display_errors', 1);

class Accomodationhome extends CI_Controller
{
	
   
		function __construct() {

        parent::__construct();
	
        
    
        $this->load->database();
		$this->load->helper('date');
                $this->load->model('usermodel','',TRUE);
				 $this->load->helper('pdf_helper');
  $this->load->library('email');
  $this->load->library('encrypt');

        $this->load->model('postmodel','',TRUE);
         //$this->load->model('userprofilemodel','',TRUE);
		$this->load->model('accomodationmodel','',TRUE);
		$this->load->model("adminusermodel", "login",TRUE);
		 //  $this->load->model('studentprofilemodel','',TRUE);
		 if( !isset($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], "order/place") === -1 ) {
    $this->load->helper('url');
    redirect('/page404');
}	
	
	
	
             if(empty($this->session->userdata('logged_in'))) {
            $this->session->set_flashdata('flash_data', 'You don\'t have access!');
            redirect('login');
        }
		


    }
	
	 
public	function formatMoney($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 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;
					}
						
	
	
	
	function createRandomPassword() {
			$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()."003232303232023232023456789EFGHIJKLMNOPQRSTU4532421312314253252412312353253256325213213546121425453553245355ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					  //$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 viewallusers()
	{ 
		 $this->load->view("template/headerpagemin");

		
		 $data['allusers'] = $this->accomodationmodel->populateallusers();


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

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

    
      show_error('No identifier provided', 500);
    }
   else if (isset($_GET['status'])){
     $status = $_GET['status'];
    $data['status'] = $status;
     $category = $_GET['category'];
				 	$data['category'] = $category;
	  
	  
	  
	  $plotno = $_GET['randomitemidentifier'];
     	$data['plotno'] = $plotno;
		
	$data['landlord'] = $this->accomodationmodel->populatealllandlord();
   	
	//$data['house'] = $this->accomodationmodel->gethousebystatusid($plotno, $status);
		$data['house'] = $this->accomodationmodel->getallhousebystatusid($plotno);

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

				$this->load->view('pmsdata/allhouses',$data);
		$this->load->view("template/footerpage");
	  
	  
	  
    }
    else {
     $plotno = $_GET['randomitemidentifier'];
     	$data['plotno'] = $plotno;
				 $category = $_GET['category'];
				 	$data['category'] = $category;

	$data['landlord'] = $this->accomodationmodel->populatealllandlord();
   	
	$data['house'] = $this->accomodationmodel->gethousebyid($plotno);
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/allhouses',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  
  
  
  
		public function viewprndingmoneyreceived()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');
$mydate=date('Y-m-d');
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 	$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 $currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$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);


			
			
		$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);


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

			
			
         $this->load->view("template/headerpagemin");
		// $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/viewprndingmoneyreceived',$data);
				
		$this->load->view("template/footerpage");
	
	}
  
  
  public function posthousekeeping()
    {
		
			$session_data = $this->session->userdata('logged_in');

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

		   	  $description = $this->input->post("description");
			  		   	  $status = $this->input->post("status");
				$myhouseno = $this->input->post("houseno");
				 $user = $this->input->post("user");
				 $exactdate = $this->input->post("exactdate");
				 $mycategoryid = $this->input->post("mycategoryid");

				  $action = $this->input->post("action");
				  
 $mytype = $this->input->post("type");
 $myplotno = $this->input->post("plotno");
 $myhouseno = $this->input->post("houseno");
 $approval = $this->input->post("approval");
 $comments = $this->input->post("comments");



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

		
				
			  		  $this->form_validation->set_rules("houseno", "Room  name/Number", "trim|required");

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

		
		 $this->load->view('pmsdata/viewhousekeeping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addhousekeeping') == "house")
					   {
								   $checkhouse = $this->accomodationmodel->gethousedetails($myplotno,$myhouseno);

						//$houseno=$checkhouse[0]["houseno"];  
						//$plotno=$checkhouse[0]["plotno"];  
						$type=$checkhouse[0]["type"];  
 $myplotno = $this->input->post("plotno");
		 $houseno = $this->input->post("houseno")	;			
									

						   $data=array(		
			'userid'=>$user,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'status'=>$status,

			'createdate'=>$dateposted,
				'exactdate'=>$exactdate,
			'type'=>$type,
   									'plotno'=>$plotno,
									'houseno'=>$houseno,
			
								);
						   
												$updatedata=array(		
			'approvedby'=>$user,
			
				'name'=>$name,
							'approval'=>$approval,

		  	'description'=>$description,
				 'companyid'=>$companyid,
			'status'=>$status,
			'comments'=>$comments,

			'updatedate'=>$dateposted,
				'exactdate'=>$exactdate,
			'type'=>$mytype,
   									'plotno'=>$myplotno,
									'houseno'=>$myhouseno,
			
								);
							
							
							 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'housekeeping');

							}else 	if($action=="update"){
								$usr_result = $this->usermodel->updatedata($updatedata,'housekeeping','id',$mycategoryid);
	$mydata = array(
				
				'status' => $status,
						);
			
					
					$this->accomodationmodel->upadeteHousedata($mydata,$houseno,$myplotno);
				
								}
							//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 posted the data..</div>');	
							redirect($view);																
							}
							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  was not posted successfully.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


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

   
 	$data['id'] = $session_data['id'];
       
		 $userid = $data['id'];
									  $dateposted = Date('Y-m-d H:i:s') ;

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

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

				 $user = $this->input->post("user");
				 $exactdate = $this->input->post("exactdate");

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

 $myhouseno = $this->input->post("houseno");
 
  $method = $this->input->post("method");


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

		
				
			  		  $this->form_validation->set_rules("houseno", "Room  name/Number", "trim|required");

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

		
		 $this->load->view('pmsdata/viewhousekeeping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_asignrooms') == "clean")
					   {
						   

						   
					
						   if($method=="bulk"){
							  
  $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';
            $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;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
					$house= $this->accomodationmodel->getplothousebyallstatusid($emapData['B'],$emapData['A']);
	 $myhouseno=$house[0]['id'];
										$confirmuserdata= $this->usermodel->populatealldatanoarraythree('asignrooms','roomid', $myhouseno,'memberid', $user,'companyid', $companyid);			   

					 if($confirmuserdata==false){
				
					
					
						  $new_date=	date('Y-m-d');
						  
						  
						  	    $data[] = array(
                              
		'userid'=>$userid,
						'memberid'=>$user,

				'roomid'=>$myhouseno,
			
				 'companyid'=>$companyid,
			'status'=>"active",
			'exactdate'=>$exactdate,
			'createdat'=>$dateposted,
   			'houseno' => $emapData['A'],
			'plotno' => $emapData['B'],	
										
									
									
									
									
 									
 									
                                );
						  
						  
					 }  
	
								
								
				
		   $i++;
				}
	
	

	
                    	               
              
			  $usr_result =$this->db->insert_batch('asignrooms', $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 asigned the room to the user..</div>');	
							redirect($view);																
							}
							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 room could not be asigned. Try again</div>');
								redirect($view);																

							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            } 
							   
							   
			}
							   
							   
						   }else   if($method=="Floor"){
						   
						 $rooms= $this->usermodel->populatealldatanoarraythree('house','plotno',$myhouseno,'floor', $floor,'companyid', $companyid);			   



if(is_array($rooms)) {

   foreach($rooms as $readingsrow)
   {
	
	  
	  
	  	$alldata[]=array(	
				
			'houseno'=>$readingsrow->houseno,
			'plotno'=>$readingsrow->plotno,
			'userid'=>$userid,
						'memberid'=>$user,
				'floor'=>$floor,

				'roomid'=>$readingsrow->id,
			
				 'companyid'=>$companyid,
			'status'=>"active",
			'exactdate'=>$exactdate,

			'createdat'=>$dateposted,
			
			
								);
	  
	  
	  
	  
	  
	  
	  
   }
   
$usr_result =$this->db->insert_batch('asignrooms', $alldata); 



        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 asigned the room to the user..</div>');	
							redirect($view);																
							}
							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 room could not be asigned. Try again</div>');
								redirect($view);																

							}
			
			
			
			}
						  
						  
						  
						  
						  

						   
						   } else{
						   
						   					$confirmuserdata= $this->usermodel->populatealldatanoarraythree('asignrooms','roomid', $myhouseno,'memberid', $user,'companyid', $companyid);			   

						   	   
						   if($confirmuserdata!==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 room had already been asigned to that user selected. Try a different room or user again</div>');
								redirect($view);
							   
							 return false;  
						   }
						   
						 $checkhouse = $this->usermodel->populateallarray('house','id',$myhouseno);

						$houseno=$checkhouse[0]["houseno"];  
						$plotno=$checkhouse[0]["plotno"];  

						   
									

						   $data=array(		
			'userid'=>$userid,
						'memberid'=>$user,
				'floor'=>$floor,

				'roomid'=>$myhouseno,
			
				 'companyid'=>$companyid,
			'status'=>"active",
			'exactdate'=>$exactdate,

			'createdat'=>$dateposted,
   									'plotno'=>$plotno,
									'houseno'=>$houseno,
			
								);
						   
												
												
							
							 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'asignrooms');

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

								}
							//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 asigned the room to the user..</div>');	
							redirect($view);																
							}
							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 room could not be asigned. Try again</div>');
								redirect($view);																

							}
							
						   }
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	




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

   
 	$data['id'] = $session_data['id'];
       
		 $userid = $data['id'];
									  $dateposted = Date('Y-m-d H:i:s') ;

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

			 
				 $user = $this->input->post("user");
				 $exactdate = $this->input->post("exactdate");

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

 $myhouseno = $this->input->post("houseno");
 
    $method = $this->input->post("method");
 $name = $this->input->post("name");
   $status = $this->input->post("status");
  $description = $this->input->post("description");

		    			  		   	  $view = $this->input->post("view");
	
		
				
			  		  $this->form_validation->set_rules("view", "View", "trim|required");

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

		
		 $this->load->view('pmsdata/housekeeping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_roomscleaned') == "clean")
					   {
						 
						   
				

						  
						   if($method == "bulk"){
							  
  $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';
            $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;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
					$house= $this->accomodationmodel->getplothousebyallstatusid($plotno,$houseno);
	 $myhouseno=$house[0]['id'];
	 $type=$checkhouse[0]["type"]; 

										$confirmuserdata= $this->usermodel->populatealldatanoarraythree('asignrooms','roomid', $myhouseno,'memberid', $user,'companyid', $companyid);			   

					 if($confirmuserdata==false){
				
					
					
						  $new_date=	date('Y-m-d');
						  
						  
						  	    $data[] = array(
							
							


			'userid'=>$user,
			
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'status'=>$status,
				'approval'=>"approved",

			'createdate'=>$dateposted,
				'exactdate'=>$exactdate,
			'type'=>$type,
   				'houseno' => $emapData['A'],
			'plotno' => $emapData['B'],	
				'name' => $emapData['C'],	






							
									
									
									
 									
 									
                                );
						  
						  
					 }  
	
								
								
				
		   $i++;
				}
	
	

	
                    	               
              
			  $usr_result =$this->db->insert_batch('housekeeping', $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 uploaded cleaned rooms..</div>');	
							redirect($view);																
							}
							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 cleaned rooms could not be uploaded. Try again</div>');
								redirect($view);																

							}

                      } catch (Exception $e) {
               die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
                        . '": ' .$e->getMessage());
            } 
							   
							   
			}
							   
							   
						   }else{
				
					
						   					$confirmuserdata= $this->usermodel->populatealldatanoarraythree('asignrooms','roomid', $myhouseno,'memberid', $user,'companyid', $companyid);			   

						   	
						   if($confirmuserdata!=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 room had already been asigned to that user selected. Try a different room or user again</div>');
								redirect($view);
							   
							 return false;  
						   }
						   
						 $checkhouse = $this->usermodel->populateallarray('house','id',$myhouseno);

						$houseno=$checkhouse[0]["houseno"];  
						$plotno=$checkhouse[0]["plotno"];  
						$type=$checkhouse[0]["type"]; 
						   
									

						   $data=array(		



				'userid'=>$user,
			
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'status'=>$status,
				'approval'=>"approved",

			'createdate'=>$dateposted,
				'exactdate'=>$exactdate,
			'type'=>$type,
   				'houseno' => $houseno,
			'plotno' => $plotno,	
				'name' => $description,	












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

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

								}
							//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 asigned the room to the user..</div>');	
							redirect($view);																
							}
							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 room could not be asigned. Try again</div>');
								redirect($view);																

							}
							
						   }
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
  public function cleanhouse()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
							  $updatedat = Date('Y-m-d H:i:s') ;

				$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 		
  $myadvance = $this->usermodel->populateallarray('people','id', $userid);

	 $name=$myadvance[0]['firstname'];
		   	  $description = "Room cleaned";
			  		   	  $status = $this->input->post("status");
				 $exactdate = $dateposted;
				 $mycategoryid ="";

				  $action = "insert";
				  
 
 $plotno = $this->input->post("plotno");
 $houseno = $this->input->post("houseno");
 $approval = "new";
 $comments ="na";



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

		
				
			  		  $this->form_validation->set_rules("houseno", "Room  name/Number", "trim|required");

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

		
		 $this->load->view('pmsdata/viewhousekeeping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('cleanhouse') == "clean")
					   {
						$house= $this->accomodationmodel->getplothousebyallstatusid($plotno,$houseno);
	 $roomidentifier=$house[0]['id'];



	$booking  = $this->usermodel->populatealldatanorraythree('bookroom','plotno', $plotno,'houseno', $houseno,'status','active');



	  $itemid=$booking[0]['id'];




					 $type=$house[0]['type'];
					

						   $data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			
		  	'description'=>$description,
				 'companyid'=>$companyid,
			'status'=>$status,

			'createdate'=>$updatedat,
				'exactdate'=>$updatedat,
			'type'=>$type,
   									'plotno'=>$plotno,
									'houseno'=>$houseno,
			
								);
						   
												$updatedata=array(		
			'approvedby'=>$user,
			
				'name'=>$name,
							'approval'=>$approval,

		  	'description'=>$description,
				 'companyid'=>$companyid,
			'status'=>$status,
			'comments'=>$comments,

			'updatedate'=>$dateposted,
				'exactdate'=>$exactdate,
			'type'=>$mytype,
   									'plotno'=>$myplotno,
									'houseno'=>$myhouseno,
			
								);
							
							
							
							$usr_result = $this->usermodel->add($data,'housekeeping');

						
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
															$mydata=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
										
					 $this->usermodel->updatedata($mydata,'house','id',$roomidentifier);

								

						   
												$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								);
				$this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);
	
								
								
						 $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 Cleaned this room.</div>');	
							redirect($view);																
							}
							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> Room was not cleaned.. Try again</div>');
								redirect($view);																

							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		
		

	      $viewroomcleaned=$this->usermodel->populatuserpermissionsdataarray('accomodation','viewroomcleaned',$userid);


if($viewroomcleaned==true){
								$data['viewhousekeeping']= $this->usermodel->populateall('housekeeping','companyid',$companyid);

	
	
}else{
								$data['viewhousekeeping']= $this->usermodel->populateall('housekeeping','userid',$userid);
	
	
}




				$this->load->view('pmsdata/viewhousekeeping',$data);
		$this->load->view("template/footerpage");
	}
  
  
			public function viewassignedrooms()
	{ $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 		$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");



		      $assignrooms=$this->usermodel->populatuserpermissionsdataarray('accomodation','assignrooms',$userid);


					if( $assignrooms==true){
						
												$data['asignrooms']= $this->usermodel->populateall('asignrooms','companyid',$companyid);

					}else{
						
																		$data['asignrooms']= $this->usermodel->populateall('asignrooms','userid',$userid);

					}






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

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

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

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

	    
		  $accomodationmanager=$this->usermodel->populatuserpermissionsdataarray('accomodation','accomodationmanager',$userid);
	       $accommodationcleaner=$this->usermodel->populatuserpermissionsdataarray('accomodation','accommodationcleaner',$userid);
	      $accommodationreceiptionist=$this->usermodel->populatuserpermissionsdataarray('accomodation','accommodationreceiptionist',$userid);

	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		 
		 
		  if (isset($_POST['houseno'])){
$status = $this->input->post("status");
	$plotno = $this->input->post("plotno");
 $houseno = $this->input->post("houseno");
  $page = $this->input->post("page");

	if (($status=="none")){
				$data['house'] = $this->accomodationmodel->getplothousebystatusid($plotno,$houseno);

		}else if (($status=="all")||($status=="vacant")||($status=="occupied")||($status=="freezed")||($status=="Pending")  ||($status=="Vacant Dirty")||($status=="Occupied Dirty")||($status=="Blocked")||($status=="Reserved")){
				$data['house'] = $this->accomodationmodel->gethousebystatusid($plotno, $status);

			
		}else if ($status=="MangePlot"){
			
			$data['links']="";
		
			
					$data['plots'] = $this->usermodel->populateall('plot','id', $plotno);
						$data['total_rows']=count((array) 	$data['plots']);
									$this->load->view('pmsdata/allplots',$data);
		$this->load->view("template/footerpage");
return false;
				
		}else if ($status=="bulkInvoice"){
			
			 redirect('admin/rentinvoice?randomitemidentifier1='.$plotno);	
return false;
		}else if ($status=="bulkPenalty"){
				 redirect('admin/penaltyinvoice?randomitemidentifier1='.$plotno);	
return false;
				
		}else if ($status=="bulkCopaRent"){
				 redirect('admin/coparentinvoice?randomitemidentifier1='.$plotno);	
return false;
				
		}else if ($status=="ActivateCharges"){
					 redirect('admin/plotcharges?randomitemidentifier='.$plotno);	
return false;
				
		}else if ($status=="ManageRooms"){
					 redirect('admin/viewplot?randomitemidentifier='.$plotno.'&category=rental');	
return false;	
				
		} else if ($status=="UpdateRoom"){
			
			

	$housedetails = $this->usermodel->populatealldataarray('house','plotno', $plotno,'houseno', $houseno);

	
	$houseids=$housedetails[0]['id'];
						 redirect('admin/editroom?randomitemidentifier='.$houseids);	
		
		
			
return false;	
		//		
		} else if (($status=="reserved")|| ($status=="Reserved")){
			
			
	$data['advance'] = $this->usermodel->populatealldatanoarrayfour('advance','plotno', $plotno,'startdate >',$dateposted,'houseno',$houseno,'status',"reserved");
	$this->load->view('pmsdata/viewalladvance',$data);
		$this->load->view("template/footerpage");
		
		
			
return false;	
		//		
		}else if ($status=="reservedall"){
			
			
	$data['advance'] = $this->usermodel->populatealldatanoarraythree('advance','plotno', $plotno,'startdate >',$dateposted,'status',"reserved");
	$this->load->view('pmsdata/viewalladvance',$data);
		$this->load->view("template/footerpage");
		
		
			
return false;	
		//		
		}




   
    
    }else{
				$data['house'] = $this->usermodel->populatealldatawhere('house','id','asc','branchid', $branchid);
	
		
	}
		 
		 
		 
		 
		 
		 
		 


		if($accomodationmanager==true){
	
	$this->load->view('pmsdata/manager',$data);

	
}else if($accommodationreceiptionist==true){
	
	$this->load->view('pmsdata/searchallhousebutton',$data);

}else if($accommodationcleaner==true){
	
	
		$data['house'] = $this->usermodel->populateallroomstobecleaned('asignrooms','asignrooms.status','active','asignrooms.companyid', $companyid,'asignrooms.memberid', $userid);


				$this->load->view('pmsdata/housekeeping',$data);

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


}	
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
   public function viewpallmyroomstoclean() {
		
		$session_data = $this->session->userdata('logged_in');

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

	  
	  
	  
		
   	
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['house'] = $this->usermodel->populateallroomstobecleaned('asignrooms','asignrooms.status','active','asignrooms.companyid', $companyid,'asignrooms.memberid', $userid);


				$this->load->view('pmsdata/housekeeping',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  
    
   public function searchroomscleaned() {
		
		$session_data = $this->session->userdata('logged_in');

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

	  
	  
					 $enddate = $this->input->post("enddate");
		 		 $fromdate = $this->input->post("fromdate");
				$user = $this->input->post("user");
	  
		
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['viewhousekeeping'] = $this->accomodationmodel->searchroomscleaned($fromdate, $enddate,$companyid, $user);
	$data['fromdate'] =$fromdate;
		$data['todate'] =$enddate;
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


				$this->load->view('pmsdata/viewhousekeepingreport',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
    
   public function searchroomscleanedandsold() {
		
		$session_data = $this->session->userdata('logged_in');

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

	  
	  
					 $enddate = $this->input->post("enddate");
		 		 $fromdate = $this->input->post("fromdate");
				$user = $this->input->post("user");
	  
		
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['viewhousekeeping'] = $this->accomodationmodel->searchroomscleanedandsold($fromdate, $enddate,$companyid, $user);
	$data['fromdate'] =$fromdate;
		$data['todate'] =$enddate;
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


				$this->load->view('pmsdata/viewhousekeepingcleaningreport',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
    
   public function searchroomsallocated() {
		
		$session_data = $this->session->userdata('logged_in');

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

	  
	  
					 $enddate = $this->input->post("enddate");
		 		 $fromdate = $this->input->post("fromdate");
				$user = $this->input->post("user");
	  
		
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['asignrooms'] = $this->accomodationmodel->searchroomsallocated($fromdate, $enddate,$companyid, $user);
	$data['fromdate'] =$fromdate;
		$data['todate'] =$enddate;
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);


				$this->load->view('pmsdata/viewassignedrooms',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
    
  public function managerentals () {
		
		$session_data = $this->session->userdata('logged_in');

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

	 
	  
		
   	
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['house'] = $this->usermodel->populateall('house','companyid', $companyid);


				$this->load->view('pmsdata/managerentals',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  public function viewpallmyplotsbuttons () {
		
		$session_data = $this->session->userdata('logged_in');

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

	 
	  
		
   	
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['house'] = $this->usermodel->populateall('house','companyid', $companyid);


				$this->load->view('pmsdata/searchallhouse',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  
  
  
  
    
  public function searchrooms () {
  
		
		$session_data = $this->session->userdata('logged_in');

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

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

    	if (($status !="none")){
				$data['house'] = $this->accomodationmodel->gethousebystatusid($plotno, $status);

		}else{
				$data['house'] = $this->accomodationmodel->getplothousebystatusid($plotno,$houseno);

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

   	
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['house'] = $this->usermodel->populateall('house','companyid', $companyid);


				$this->load->view('pmsdata/searchallhousereport',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  
  
  public function rentdailypayment() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
    
	$data['payment'] = $this->usermodel->populaterentaldailypeyment($companyid);

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

						//$this->load->view('pmsdata/salesreceipts',$data);

				$this->load->view('pmsdata/rentdailypayment',$data);
		$this->load->view("template/footerpage");
	
  }
  
public function uploadmpesa()
        {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
							
								
          if(isset($_POST["btn_uploadmpesa"]))
            {
				$createdat = Date('Y-m-d H:i:s') ;

		
								 
            	
                $filename=$_FILES["file"]["tmp_name"];
             /// var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
					
					$counter = 0;  
$finaltotal=0;
 $myfinaltotal=0;
  $myfinaltotal2=-1;
  $mypayment=0;
    $finalbalnce=0;
		 $myfinalbalanace=0;			
$finaloverpayemnt=0;
 $originalamount=0;
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
					$paymentcode=$emapData[0];
					if($this->accomodationmodel->checkpayamntacode($paymentcode)==false){
						
							$originalamount=$emapData[5];
						
					
						 //$myfinaltotal2=++$counter;
 $myfinaltotal2+2;
						 	$transactioncode='RC-'.$this->createRandomPassword();
						   $paymentdetails = explode("-",$emapData[10]);
                          
						  $phone = $paymentdetails[0];
						   
						   $paidby = $paymentdetails[1];
						  
						  
						     
						$plotdetails = explode("-",$emapData[12]);
						    $mybalnce=0;	
						   $plotno = $plotdetails[0];
							$houseno = $plotdetails[1];
							if($this->accomodationmodel->tenantavailablenoarray($plotno,$houseno)!=false){
								
							
					$tenantavalable = $this->accomodationmodel->tenantavailablenoarray($plotno,$houseno); 
	$tenantid=$tenantavalable[0]['tenantid'];
								
			$mycontact = $this->usermodel->populateallarray('tenant','id',$tenantid);

	   
	       $myphone=$mycontact[0]["phone"];
		   if($myphone==""){
			   
			      $mycontactdata=array(
					
	   'phone' =>$phone,
	   

	
							
								);
		$this->usermodel->updatedata($mycontactdata,'tenant','id',$tenantid);
 
		   }
				
				
                            $data = array(
							
							'paymentcode' =>$emapData[0],
				'exactime' => $emapData[1],
					'createdat' => $emapData[13],
				'amount' =>str_replace(",", "", $emapData[5]),
					'paidby' => $paidby,
				'plotno' =>$plotno,
				'houseno' => $houseno,
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'receipt',
				
				
				'userid' => $userid,
				
								'paymentmode' => 13,
						'overpayment' => 0,


								'companyid' => $companyid,
                       	
                                );
				if($this->accomodationmodel->uploadmpesa($data)){
				
						
				if($this->accomodationmodel->gethouseinvoicewithbalance($plotno,$houseno)!=false){
					
														$mybalancerow= $this->accomodationmodel->getplotreceiptallbybalancenoarray($plotno,$houseno, $tenantid);

			$myorignalinvoiced=$mybalancerow[0]['orignalmount'];
$paidamount= $mybalancerow[0]['paid'];
  $myfinalbalanace=$originalamount-$myorignalinvoiced; 
					
					
					
					$myinvoice= $this->accomodationmodel->gethouseinvoicewithbalance($plotno,$houseno);
								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){
	
		$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"; 	
			}
			
	
  }
		
if($mybalnce>0){
						
							$finaloverpayemnt=$mybalnce;
					}else{
							$finaloverpayemnt=0;
					}
		
		
	   	$houserent = $this->accomodationmodel->gethousedetails($plotno,$houseno);
$vat=$houserent[0]['vat'];
$commission	=$houserent[0]['commission'];
	   
	   	    if(($type=="1")||($type=="6")) {
								  $mytax=1+($vat/100); 
								 $vatable=($mypayment/$mytax);
								 $myfinaltax=($mypayment-$vatable);
								 $myfinalcommission=(($commission/100)*$mypayment);

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

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

								 								$finalvat=0; 

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

	   
	       $origalpayment=$totaldata[0]["paid"];
	   $finalamount= $origalpayment+$mypayment;
	   
    
					
					
				
				
	 
	 
      $paymentdata=array(
					
	   'paid' =>$finalamount,
	   
	'commission' => $finalcommission,
	'vat' => $finalvat,
		'paymentcode' => $transactioncode,
			'paymentdate' =>  $emapData[1],
	
							
								);
								if($mypayment!=0){
										$usr_result= $this->usermodel->updatedata($paymentdata,'invoice','id',$invoiceid);
				
								}
								
			
						

				
		
		
					
       
		
			}
			
				
	 
	 
	 		
					
			
			
			
}
						
		  if($myfinalbalanace >0 ){
			  
		 
	
	 				 $overpayemntdata=array(
					
	   'overpayment' =>$myfinalbalanace,
	   
	
	
							
								);
						$myusr_result=			$this->usermodel->updatedata($overpayemntdata,'receipt','transactioncode',$transactioncode);
					
			
	   
						
				
						 }
						
						
						
						}	
						
				
						
						
                     } 
					 
					 		
					 
					 }
					 }
                    fclose($file);
					
                   		if ($myusr_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 uploaded Mpesa payments !</div>');
								
				redirect('admin/uploaddailypayment');
								 
								 
								 
								 
								 
								 
						
							}
							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> Mpesa Payment was uploaded. Try again</div>');
								
						
					redirect('admin/uploaddailypayment');
								 
							}

                  }
            }
        }

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

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

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
				
				
				$config['base_url'] = base_url('Systemusers/allpayments');
		$config['total_rows'] = $this->usermodel->count_allwhere('allpayments','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($userid);
        $data["viewexpenses"] = $this->usermodel->displayall($config["per_page"], $page,'allpayments','companyid',$companyid);
         $this->load->view("template/headerpagemin");
		// $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('pmsdata/allpayments',$data);
				
		$this->load->view("template/footerpage");
	
	}
  
	
	
   
   
    public function addallpayments()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime);
		 		//$dateposted =  ($postedtime)." ".$currenttime ;

		 $userid = $data['id'];
		 
		 		
					 $view = $this->input->post("view");
		 		 $amount = $this->input->post("amount");
				$balance = $this->input->post("balance");
			   $description = $this->input->post("description");
		    $user = $this->input->post("user");
		$createdat = $this->input->post("createdat");
				$controller = $this->input->post("controller");
				$idno = $this->input->post("idno");
				$contact = $this->input->post("contact");
				$receiptno = $this->input->post("receiptno");
				$landlord = $this->input->post("landlord");
				$month = $this->input->post("month");
				$plotno = $this->input->post("plotno");
		 							 $img_id = $this->input->post("img_id");
				$year = $this->input->post("year");



					 $advance = $this->input->post("advance");
		 		 $direct = $this->input->post("direct");
				$mpesa = $this->input->post("mpesa");
			   $cash = $this->input->post("cash");
		
		$card = $this->input->post("card");
				$cheque = $this->input->post("cheque");
				
				
				
				
				$paid=$cheque+$card+$cash+$mpesa+ $advance+$direct ;
				$balance=$amount-$cheque;
				
				
				
				
				
				
				
				
			  		  $this->form_validation->set_rules("createdat", "Date of Expenditure ", "trim|required");
			  		  $this->form_validation->set_rules("amount", "Amount ", "trim|required");

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

		
		 $this->load->view('userdata/viewexpenses', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addallpayments') == "allpayments")
					   {
												$data=array(		
			'landlord'=>$landlord,
			'amount'=>$amount,
				'balance'=>$balance,
			'user'=>$user,
		  	'description'=>$description,
		'createdat'=>$createdat,
			
			'dateposted'=>$dateposted,
			'controller' =>$controller,
				'idno' =>$idno,
				'contact'=>$contact,
				'receiptno'=>$receiptno,
								'year'=>$year,
								'paid'=>$paid,

				'userid'=>$userid,
								'plotno'=>$plotno,
				'month'=>$month,
'companyid' => $companyid,
			
				'advance'=>$advance,
			'direct'=>$direct,
				'mpesa'=>$mpesa,
		  	'cash'=>$cash,
		'card'=>$card,
			
			'dateposted'=>$dateposted,
			'cheque' =>$cheque,
								);
							$usr_result = $this->usermodel->add($data,'allpayments');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						$this->uploadimage($view, $img_id,$userid);
						
					}
						
								 
						 $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 expense  ..</div>');	
								 redirect($view);
							
							}
							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> Expense  was not created.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

   
    	public function searchatenatstatment() {
			 $tenantid = $this->input->post("tenantid");		

	 $type = $this->input->post("type");
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		  	 $todate = $this->input->post('todate',TRUE);
		 $fromdate = $this->input->post('fromdate',TRUE);
		 		 $plotno = $this->input->post('plotno',TRUE);
	 $status = $this->input->post('status',TRUE);

		 $display = $this->input->post('display',TRUE);
		 $paymentstatus = $this->input->post('paymentstatus',TRUE);
	 $data['fromdate'] =$fromdate;
	 	 $data['paymentstatus'] =$paymentstatus;
	  $data['todate'] =$todate;
	    $data['type'] =$type;
		  
		   $customer= $this->usermodel->populateallarray('people','id',$tenantid);
		   
		   $myname=$customer[0]["firstname"];
		  if($paymentstatus=="balances"){
			  
			  
			  $data['status']=$status;
			  $data['invoice'] = $this->accomodationmodel->getrentbalancesbytenant($tenantid);
				$this->load->view('pmsdata/alltenantbalances',$data);

		  } else if($paymentstatus=="all Statement"){
			  
			   $data['overpayment']="";
			  $data['status']=$status;
			    $data['myname']=$myname;
			  				$data['invoice'] = $this->accomodationmodel->getrentalutilitiestenant($fromdate,$todate,$plotno,$tenantid);
				$this->load->view('pmsdata/viewutilitiestenats',$data);

		  }
		  
		  
		  else{
			 						$data['invoice'] = $this->accomodationmodel->searchatenatstatment($fromdate,$todate,$tenantid,$paymentstatus,$plotno);
 	 				$this->load->view('pmsdata/searchforrentgeneralreport',$data);

		  }


		
		

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



	
  }
  
  
  
   	    
    	public function searchatenatllhouse() {
			 $tenantid = $this->input->post("tenantid");		


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

	$data['house'] = $this->accomodationmodel->gettenantallbookings($tenantid);


				$this->load->view('pmsdata/searchallhouse',$data);

		
		

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



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

		


				$this->load->view('pmsdata/uploaddailypayment');
		$this->load->view("template/footerpage");
	}
  
  
	
	 public function groupbycategory() {
   	if ($this->input->post('groupbycategory') == "all")
					   {
			
		$session_data = $this->session->userdata('logged_in');

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

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

			
			
			
			
			
			 $count =count((array) $memberid);

   for($i=0; $i< $count; $i++) {
       $data = array(
	   	
		  	'status'=>$categoryid,
			'updatedat'=>$dateposted,
		
             );
			 	
  		$usr_result = $this->usermodel->updatedata($data,'house','id',$memberid[$i]);

   }
		
			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 updated the rooms status  ..</div>');	
							redirect('admin/viewplot?randomitemidentifier='.$plotno);																
							}
							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> Rooms were not updated.. Try again</div>');
								
							redirect('admin/viewplot?randomitemidentifier='.$plotno);																
							}
		
		
	}else{
		
		redirect("user/viewmember");
	}
  }
	
  
     public function getpayment() {
	     
 $session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   
	$phone = $this->input->post("phone");

   // $randomitemidentifier = $this->input->post("randomitemidentifier");
	
	//   $randomitemidentifier1 = $this->input->post("randomitemidentifier1");
	     // $roomidentifier = $this->input->post("roomidentifier");
	
	
	
	
	
	  $data['payment'] = $this->usermodel->populatependingpayment($phone);
	  
	  
	  
	  

 if($data['payment']!=false){
	 $myphone = $data['payment']['0']['sender_number'];
	 $transactioncode = $data['payment']['0']['code'];
	  $lastname = $data['payment']['0']['lastname'];
	   $firstname = $data['payment']['0']['firstname'];
	      $message = $data['payment']['0']['sms_text'];
		  $mpesaamount = $data['payment']['0']['amount'];
		   $exactime = $data['payment']['0']['exactime'];
	  $data['transactioncode']=$transactioncode ;
	  $data['mpesaamount']=$mpesaamount ;
	   $data['phone']=$myphone;

  $data['salesid']=$salesid;
 $this->session->set_flashdata('msg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Success! </strong>Your Transaction Code is:' .$transactioncode.'; Amount: '.$mpesaamount.'; Name: '.$firstname." ".$lastname.'; Phone: '.$myphone.';Payment Date:' .$exactime.'  </div>');
	//redirect('user/viewsales',$data);	
		redirect('user/viewsales?transactioncode='.$transactioncode.'&mpesaamount='.$mpesaamount);	
	 redirect($view);
	 
 }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>That Code/Phone number('.$phone.') does not exist..try again  </div>');
	 redirect($view);	
		 }
   
	
  
  

	}
 
  public function viewalladvance() {
		
		 $session_data = $this->session->userdata('logged_in');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 					$data['advance'] = $this->usermodel->populateall('advance', 'companyid',$companyid);

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

				$this->load->view('pmsdata/viewalladvance',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
		public function mychangepaymentmoreguests() {
   if (!isset($_GET['myid'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['myid'];

	 if(isset($_GET['roomidentifier'])){
			      $roomidentifier = $_GET['roomidentifier'];
 
	 }else{
		      $roomidentifier ="";
	 
		 
	 }
	

	
	

			   $data['allsalesdetails']= $this->usermodel->populateallarray('bookroom','transactioncode',$itemid);
		
		$data['houseno'] = $data['allsalesdetails'][0]["houseno"];
			$data['pltono'] = $data['allsalesdetails'][0]["plotno"];
		   	$data['roomidentifier'] = $roomidentifier;
	
   	$data['randomitemidentifier1'] =$data['allsalesdetails'][0]["plotno"];
	
   	$data['randomitemidentifier'] = $data['allsalesdetails'][0]["houseno"];

   	$data['itemid'] = $itemid;
		
		
		$data['charges'] = $this->accomodationmodel->getplotcharges($data['allsalesdetails'][0]["plotno"], $roomidentifier);

    

		
		 $this->load->view('pmsdata/changepayment',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
  
  
  
  
  
	
	
		public function changepayment() {
   if (!isset($_GET['myid'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['myid'];

	 if(isset($_GET['roomidentifier'])){
			      $roomidentifier = $_GET['roomidentifier'];
 
	 }else{
		      $roomidentifier ="";
	 
		 
	 }
	

	
	

			   $data['allsalesdetails']= $this->usermodel->populateallarray('bookroom','transactioncode',$itemid);
		
		$data['houseno'] = $data['allsalesdetails'][0]["houseno"];
			$data['pltono'] = $data['allsalesdetails'][0]["plotno"];
		   	$data['roomidentifier'] = $roomidentifier;
	
   	$data['randomitemidentifier1'] =$data['allsalesdetails'][0]["plotno"];
	
   	$data['randomitemidentifier'] = $data['allsalesdetails'][0]["houseno"];

   	$data['itemid'] = $itemid;
		
		
		$data['charges'] = $this->accomodationmodel->getplotcharges($data['allsalesdetails'][0]["plotno"], $roomidentifier);

    

		
		 $this->load->view('pmsdata/changepayment',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
	
    public function viewmyadvancepayment () {
		
		if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
   else {
    
		
    
	  
	  
	  
	  $myid = $_GET['randomitemidentifier'];
    
		$data['myid'] =$myid;
$data['mypayments'] = $this->usermodel->populateall('advancepayment', 'advanceid',$myid);


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

				$this->load->view('pmsdata/viewmyadvancepayment',$data);
		$this->load->view("template/footerpage");
	  
	  
	  
    }
 
  }
  
  
  
  public function viewmyhouses () {
		
		if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
   else {
    
		
    
	  
	  
	  
	  $tenantid = $_GET['randomitemidentifier'];
    
		
	$data['landlord'] = $this->accomodationmodel->populatealllandlord();
   	
	$data['myhouse'] = $this->accomodationmodel->getbookingtenantbyid($tenantid);

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

				$this->load->view('pmsdata/searchallmyhouse',$data);
		$this->load->view("template/footerpage");
	  
	  
	  
    }
 
  }
  
  	public function searchallhouse() {
			 $houseno = $this->input->post("houseno");		

	if (($houseno=="none")){



	$plotno = $this->input->post("plotno");
 $status = $this->input->post("status");
    
	 
		 
		  
		  
   	
	$data['house'] = $this->accomodationmodel->gethousebystatusid($plotno, $status);
	$data['status']=$status;
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/searchallhouse',$data);
		$this->load->view("template/footerpage");



	}else{
		
	   $houseno = $this->input->post("houseno");	





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

  	
	$data['house'] = $this->accomodationmodel->getplothousebystatusid($plotno,$houseno);
	$data['status']=$houseno;
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/searchallhouse',$data);
		$this->load->view("template/footerpage");
	  
	  
	  
   
     
		}
  }
  
  
  
  
  
  
  
  
  
  
    	public function searchallbalance() {
				
 

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

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

		  $fromdate = $this->input->post("fromdate");
			
		$todate = $this->input->post("todate");
		
		
		
		
		
  $data['invoice'] = $this->accomodationmodel->getmyhouseinvoicepayment($plotno,$houseno,$status,$fromdate,$todate);

	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/searchallbalanace',$data);
		$this->load->view("template/footerpage");
	  
	  
   
     
		
  }
  
 
     	public function searchpaymentinvoice() {
			
 

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

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

		  $fromdate = $this->input->post("fromdate");
			
		$todate = $this->input->post("todate");
		
		
		
		
		
  
$data['invoice'] = $this->accomodationmodel->gethouseinvoicepayment($plotno,$houseno,$status,$fromdate,$todate);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/searchallpayment',$data);
		$this->load->view("template/footerpage");
	  
	  
   
     
		
  }
  
  
  
  
  
  
  public function searchroomssoldandexpenses() {
		
$session_data = $this->session->userdata('logged_in');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];		
 		$this->load->view("template/headerpagemin");

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

	

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

		  $fromdate = $this->input->post("fromdate");
			
		$todate = $this->input->post("todate");
		
			   $frotime = $this->usermodel->allterms_handler($this->input->post("frotime",TRUE),'collections');
	  	  $totime = $this->usermodel->allterms_handler($this->input->post("totime",TRUE),'totime');
				
   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;
		 
	
		
		
		
		
				$cashbanked = $this->input->post("cashbanked");
			$supplier="all";
  			$itemtype="all";
  			$daterange="yes";
  			$grouping="yes";
  			$code="all";

$data['allbookings'] = $this->accomodationmodel->viewsalesandexpenses($plotno,$companyid,$branchid,$fromdate,$todate);
$data['booking'] =false;

				$data['viewexpense'] = $this->usermodel->viewitemexpensereport($fromdate,$todate,$companyid,$supplier,$itemtype,$daterange,$code,$grouping,$branchid,"all");

	$data['fromdate'] =$fromdate;
		$data['todate'] =$todate;
		$data['cashbanked'] =$cashbanked;
				$data['plotno'] =$plotno;
			
										$this->load->view('pmsdata/salesexpensereport',$data);

	

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

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

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

			
		$plotno = $this->input->post("plotno");
	
	
		  $chargeid = $this->input->post("chargeid");

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

		$todate = $this->input->post("todate");
				$display = $this->input->post("display");
								$user = $this->input->post("user");


	   $frotime = $this->usermodel->allterms_handler($this->input->post("frotime",TRUE),'collections');
	  	  $totime = $this->usermodel->allterms_handler($this->input->post("totime",TRUE),'totime');
				
   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;
		 
	



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

  
$data['booking'] = $this->accomodationmodel->getmyhouseinvoicepaymentCombined($plotno,$houseno,$user,$fromdate,$todate,$category,$tenantid,$chargeid);


	$data['tenantid'] =$tenantid;

	$data['fromdate'] =$fromdate;
		$data['todate'] =$todate;
		$data['display'] =$display;
		if($display=="No"){
	$this->load->view('pmsdata/searchallpaymentnomoney',$data);

			
		}else if($display=="BreakFast"){
			
	$this->load->view('pmsdata/searchallpaymentnomoneybreakfast',$data);

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

		}

		//$this->load->view("template/footerpage");
	  
	  
   
     
		
  }
  
  
  
  
   public function printreceivedpayments() {
	
   if (!isset($_GET['randomitemidentifier'])){

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

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	
	$data['id'] = $session_data['id'];
        	$data['invoiceid'] = $invoiceid;
		 $userid = $data['id'];
 $data['setting'] = $this->usermodel->getsetting();
 		$data['viewbill'] = $this->usermodel->populateallarray('bookroom','transactioncode',$invoiceid);
						$data['viewcollection']  = $this->usermodel->populatealldatanoarray('roomcollection','id', $myid,'companyid', $companyid);



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

	 $this->load->view("template/headerpagemin");
				
						$this->load->view('pmsdata/printreceivedpayments', $data);
		
	}
  }
  
  
  
  
  
  
  
  
  
  
  
  
  public function addroompayment()
    {
		$session_data = $this->session->userdata('logged_in');
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
   
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		 $userid = $data['id'];
		 $bankname="";
 	 			$amount = $this->input->post("amount"); 
 $remarks = $this->input->post("remarks");
$invoice = $this->input->post("itemid");
	
$method = $this->input->post("method");
$transactioncode = $this->input->post("transactioncode");

$mybank = $this->input->post("bankname");
$paiddate = $this->input->post("paiddate");
$name = $this->input->post("name");
$baddebt = $this->input->post("baddebt");
$table = $this->input->post("table");


if($bankname!=""){
		 $bankname=$mybank;
} else if($baddebt!=""){
$bankname=$baddebt;

	
}else{
 $bankname=$mybank;

}






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

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

		
		 $this->load->view('pmsdata/viewbalance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_payment') == "payment")
					   {
						   
					$viewsales = $this->usermodel->populateallarray($table, 'transactioncode',$invoice);

						   
									//$viewsales = $this->usermodel->populateallarray('bookroom', 'transactioncode',$invoice);
									 $mainbalance=$viewsales[0]['balance'];
									  $maintotal=$viewsales[0]['total'];
									  
									  
									  if($method=="cash"){
										  									  $maincash=$viewsales[0]["amount"];
														$method="amount";
									  }else{
										  									  $maincash=$viewsales[0][$method];
$method=$method;
									  }
									   $maincredit=$viewsales[0]['credit'];
									     $mycustomer=$viewsales[0]['tenantid'];
										 $mybranchid=$viewsales[0]['branchid'];

										 
										 
										 $finalcustomerbalance=0;
										 	$people = $this->usermodel->populateallarray('people','id',$mycustomer);
									$customerbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
	
										 
										 
										 
										 
										 
     $finalcash=(double)$maincash+(double)$amount; 
 $mycollectionbalance=(((double)$amount+(double)$mainbalance)*-1);
  $mybalance=(((double)$amount+(double)$mainbalance));
			 $finalcredit=(double)$maincredit-(double)$amount;
			

			  
						   if( (-$amount)< ($mainbalance)){
							   
							   
						
						   
						   
						   
						   	 $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Warning!</strong> You can not pay  more amount ('.$amount.') than the balance  ('.(-1 *$mainbalance) .').Try again.</div>');	
																			redirect('admin/viewbalance?invoice='.$invoice);	
																			return false;
																			   }
						  
							
												
												$data=array(		
			'userid'=>$userid,
			
			
						'invoice'=>$invoice,
						'balance'=>$mycollectionbalance,
			'createdate'=>$dateposted,
			   			'paiddate'=>$paiddate,
			   			'name'=>$name,

		   
			 'remarks' => $remarks,   
			 			  			 'transactioncode' => $transactioncode,   

			  			 'companyid' => $companyid,   
			  			 'paymentmethodes' => $bankname,   
'supplier' => $mycustomer, 
'branchid' => $mybranchid,
				'amount' => $amount, 
			
			
								);
							$usr_result = $this->usermodel->add($data,'roomcollection');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								$updatedata=array(	
								'credit'=>$finalcredit,

						'balance'=>$mybalance,
						$method=>$finalcash,
								);
							$usr_result = $this->usermodel->updatedata($updatedata,$table,'transactioncode',$invoice);
						
								 
								 
								 
								 if($amount>0){

										$finalcustomerbalance=$customerbalance-$amount;
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalance,
						'lastbalancedate'=>$paiddate,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
									
								
									 
								 }
								 
								 
								 
								 
								 
								 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid,'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


$creditdata=array( 'userid'=>$userid,'account'=>1100,'credit'=>$amount,'description'=>$remarks,'code'=>$invoice,'crateddate'=>$paiddate,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid,'transactioncode'=>$transactioncode,'supplier'=>$mycustomer);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');
							
						   						   		$mpesaresult = $this->usermodel->populatependingmypayment($transactioncode);

							if($mpesaresult!=FALSE){
			
					$mpesaid=$mpesaresult[0]['id'];
				$finalamount=$mpesaresult[0]['amount'];
						   							$paymentdata=array(		
			'id'=>$mpesaid,
			
				'used'=>1,
		
						   
					  	);	

								 $this->usermodel->updatedata($paymentdata,'sms_in','id',$mpesaid);

	


						$data=array(		
			'userid'=>$userid,
			
				'code'=>$transactioncode,
			
		  	'branch'=>$branchid,
				 'companyid'=>$companyid,
				'type'=>"credit paid",
				 	'amount'=>$finalamount,
			'dateposted'=>$paiddate,
				'paymentstatus'=>"Cleared",
			
								);
							 $this->usermodel->add($data,'mpesasales');
		}
							
							
							
							
							
							
							
							
							
							
							
						 $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  payment..</div>');	
																			redirect('admin/viewbalance?invoice='.$invoice);	
															
							}
							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> Payment  was not added.. Try again</div>');
								
																			redirect('admin/viewbalance?invoice='.$invoice);	
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
 
 
 
 
 
  
   
 public function viewbalance() {
   if (!isset($_GET['invoice'])){

    
      show_error('No identifier provided', 500);
    }
    else {
			$this->load->view("template/headerpagemin");
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
         $userid = $data['id'];
		   $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $userid = $data['id'];
     $itemid = $_GET['invoice'];

   	$data['itemid'] = $itemid;
			   $data['allsales']= $this->usermodel->populateall('bookroom','transactioncode',$itemid);
			  
			 if( $data['allsales'] ==false){


 
 $data['allsales']= $this->usermodel->populateall('bulkreservation','transactioncode',$itemid);
	$data['table'] = "bulkreservation";
			 }else{
	$data['table'] = "bookroom";

			 }				 

		   $data['allcollections']= $this->usermodel->populateall('roomcollection','invoice',$itemid);

    

		
		 $this->load->view('pmsdata/viewbalance',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
	
	
  
  
  
  public function searchhousebycustomer() {
				$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
 		$this->load->view("template/headerpagemin");

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

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


		  $fromdate = $this->input->post("fromdate");
			
		$todate = $this->input->post("todate");
		
			   $frotime = $this->usermodel->allterms_handler($this->input->post("frotime",TRUE),'collections');
	  	  $totime = $this->usermodel->allterms_handler($this->input->post("totime",TRUE),'totime');
				
   $fromdate=$fromdate." ".$frotime;
	  	 $todate=$todate." ".$totime;
		 
	
		
		
		
				$tenantid = $this->input->post("tenantid");

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

		
		
  
$data['booking'] = $this->accomodationmodel->getmyhousepaymentbycustomer($plotno,$tenantid,$fromdate,$todate,$daterange,$branchid);

	$data['fromdate'] =$fromdate;
		$data['todate'] =$todate;
				$data['display'] ="";

							$this->load->view('pmsdata/dailypayment',$data);

		$this->load->view("template/footerpage");
	  
	  
   
     
		
  }
  
  
  
  
  
  
  
  public function searchplotpayment() {
			 $session_data = $this->session->userdata('logged_in');

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

			
 

		if ($this->input->post('btn_searchstatement') == "statemet")
		 {
		
	   $houseno = $this->input->post("houseno");	

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

		  $fromdate = $this->input->post("fromdate");
			
		$todate = $this->input->post("todate");
				 $display = $this->input->post("display");
				$displaytype = $this->input->post("displaytype");

				$data['houseno']= $houseno;

		$data['plotno']= $plotno;
		$data['status']=$status;
		$data['fromdate']= $fromdate;
		$data['todate']=$todate;
 	$data['display']=$display;
		$data['displaytype']=$displaytype;
$data['plotstatus']=$plotstatus;
 
$data['invoice'] = $this->accomodationmodel->getstatementtenant($plotno,$fromdate,$todate,$display);
$data['other'] = $this->accomodationmodel->getotherstatementrental($plotno,$fromdate,$todate);

$data['expenditure'] = $this->accomodationmodel->getexpenditure($plotno,$plotstatus,$fromdate,$todate);
$data['depositrefunds'] = $this->accomodationmodel->depositrefunds($plotno,$plotstatus,$fromdate,$todate);

	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['vacant'] = $this->accomodationmodel->getvacanthouse($plotno);

	
		$data['charges'] = $this->accomodationmodel->getplotchargesrental($plotno);
		$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/searchallplotpayment',$data);
		$this->load->view("template/footerpage");
	  
	  
		 }else if  ($this->input->post('btn_downloadstatement') == "statemet")
		 {
			//ob_start();
			 $houseno = $this->input->post("houseno");	

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

		  $fromdate = $this->input->post("fromdate");
			
		$todate = $this->input->post("todate");
				$display = $this->input->post("display");

				$data['plotno']= $plotno;

		$data['houseno']= $houseno;
		$data['status']=$status;
		$data['fromdate']= $fromdate;
		$data['todate']=$todate;
  	$data['display']=$display;
$data['plotstatus']=$plotstatus;


  
$data['invoice'] = $this->accomodationmodel->getstatementtenant($plotno,$fromdate,$todate,$display);
$data['other'] = $this->accomodationmodel->getotherstatementrental($plotno,$fromdate,$todate);


$data['expenditure'] = $this->accomodationmodel->getexpenditure($plotno,$plotstatus,$fromdate,$todate);

	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['vacant'] = $this->accomodationmodel->getvacanthouse($plotno);

	
		$data['charges'] = $this->accomodationmodel->getplotchargesrental($plotno);
		$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
		$this->load->view('pmsdata/downloadstatement',$data);


		 }else{
			 
    redirect("user/searchstatement");
		 }
		
  }
  
  
  
  
  
  
 
    public function viewexpenditure1() {
 
	//$data['invoice'] = $this->accomodationmodel->gethouseinvoice($plotno,$houseno);
	//$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
	//	$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	//$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$data['expenditure'] = $this->accomodationmodel->populateallexpenditure();
	

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
     $plotno = $_GET['randomitemidentifier'];
     	$data['plotno'] = $plotno;
		$data['charges'] = $this->accomodationmodel->getallcharges();
	$data['landlord'] = $this->accomodationmodel->populatealllandlord();
   	
	$data['plotcharges'] = $this->accomodationmodel->getrentplotcharges($plotno);
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/allcharges',$data);
		$this->load->view("template/footerpage");
	}
  }
	public function allocate() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
	 	 $roomidentifier = $_GET['roomidentifier'];

	    $plot = $this->usermodel->populateallarray('house','id', $roomidentifier);

	 $category=trim($plot[0]['category']);
	
	 

	 	 
     	$data['category'] = $category;
	 
	 
	 

	 
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
	$data['roomidentifier'] = $roomidentifier;
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno, $roomidentifier);
		
	//$data['tenant'] = $this->accomodationmodel->populatealltenant();
   		$data['booking'] = $this->accomodationmodel->getbookingbyhouseno($plotno,$houseno);
	$data['house'] = $this->accomodationmodel->gethousebno($houseno);
	
		$this->load->view("template/headerpagemin");
		
		// $this->load->view("template/tableheader");
		 
	
		if($category =="rental"){
			
				$this->load->view('pmsdata/allbookingrental',$data);

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


		}
		

				

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


	
		$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		 
		$data['myinvoice'] = false;

	
		//$this->load->view('pmsdata/bulkallbooking');

		$this->load->view('pmsdata/startbulkreservation',$data);

		
		

				

		$this->load->view("template/footerpage");
	
  }
  
  
    public function viewbulkreservation() {
		
		  if (isset($_GET['dateposted'])){

    $dateposted = $_GET['dateposted'];
    }
    else {
     $dateposted = date('Y-m-d H:i:s');
	}
		
		
		
	  
	  


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

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

		$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		 
		$data['myinvoice'] = false;
$data['display'] = false;
$data['booking'] = $this->usermodel->populateall('bulkreservation', 'status',"new");
	//$data['booking']  = $this->usermodel->populatealldatanoarraythree('bulkreservation','id > ', 0,'createdat < ', $dateposted,'companyid', $companyid);			   

		//$this->load->view('pmsdata/bulkallbooking');

		$this->load->view('pmsdata/viewbulkreservation',$data);

		
		

				

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


	
		$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		 
		$data['myinvoice'] = false;

	
		//$this->load->view('pmsdata/bulkallbooking');

		$this->load->view('pmsdata/startbulkcheckin',$data);
		//$this->load->view('pmsdata/startbulkreservation',$data);

		
		

				

		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  
  public function printallocate() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
	 	 $roomidentifier = $_GET['roomidentifier'];

	 
	 
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
	$data['roomidentifier'] = $roomidentifier;
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno, $roomidentifier);
		
	$data['tenant'] = $this->accomodationmodel->populatealltenant();
   		$data['booking'] = $this->accomodationmodel->getbookingbyhouseno($plotno,$houseno);
	$data['house'] = $this->accomodationmodel->gethousebno($houseno);
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/viewallbooking',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  
	public function deletebyid()
    {
			

   $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	  	  $plotno= $this->input->post("plotno");

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

	  
	  $usr_result = $this->accomodationmodel->deletebyid($itemid, $table);
															
								

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								
								if($table=="plotcharges"){
									$this->usermodel->deletedata($plotno,"plotno","roomcharges");

									
								}
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view.$plotno);

									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not deleted ..please try again</div>');
								
											redirect($view.$plotno);
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  
  
  
	public function deletebyiddailyroomsales()
    {
			
	  $dateposted = date('Y-m-d H:i:s');

   $view= $this->input->post("view");
	  $itemid= $this->input->post("itemid");
	  	  $plotno= $this->input->post("plotno");

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

	  
	  $usr_result = $this->accomodationmodel->deletebyid($itemid, $table);
															
								

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								if($table=="dailycharges"){
									
									
						$mytotal= $this->input->post("mytotal");
						$mytransactioncode= $this->input->post("mytransactioncode");

		$rooms= $this->usermodel->populateallarray('bookroom','transactioncode',$mytransactioncode);

		$previousbalance=$rooms[0]["total"];  			
					$totalbalance=	$previousbalance-$mytotal;	
		$updaterefund=array(		
		'paymentstatus'=>"Not Cleared",
		'updatedat'=>$dateposted,
		'total'=>$totalbalance,
		);
		$this->usermodel->updatedata($updaterefund,'bookroom','transactioncode',$mytransactioncode);
					



									
								}
								
								
								if($table=="plotcharges"){
									$this->usermodel->deletedata($plotno,"plotno","roomcharges");

									
								}
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view.$plotno);

									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not deleted ..please try again</div>');
								
											redirect($view.$plotno);
							}
	  
	  
	  
	  
	  
	  
	  
	  

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

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

		 		 $invoice = $this->input->post("invoice");
		 		  $mpesa = $this->input->post("mpesa");		  
	  	        $cheque = $this->input->post("cheque");		  
	            $card = $this->input->post("card");	
		    	$voucher = $this->input->post("voucher");	
		    	$cash = $this->input->post("amount");	
		    	$status = $this->input->post("status");	
		    	$tenantid = $this->input->post("tenantid");	

			  		      $points = $this->input->post("points"); 
			  			  		      $total = $this->input->post("total"); 
			  			  		      $myid = $this->input->post("myid"); 
		    		    	$cashier = $this->input->post("cashier");	
		    		    	$change = $this->input->post("change");	
		    		    	$people = $this->input->post("people");	

		    		    	$balance = $this->input->post("change");	
		    		    	$view = $this->input->post("btn_updatepaymetmode");	
		    		    	$paymentcode = $this->input->post("paymentcode");	
		    		    	$credit = $this->input->post("credit");	
		    		    	$paymentstatus = $this->input->post("paymentstatus");	
		    		    	$myview = $this->input->post("myview");	

							$houseno = $this->input->post("houseno");	
		    		    	$plotno = $this->input->post("plotno");	
		    		    //	$roomtype = $this->input->post("roomtype");	
									    		    	$discount = $this->input->post("discount");	


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

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

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

							  $myroomtype= $this->input->post("roomtype");
							
						
		 	$getroomdetails = explode("==",$myroomtype);
		
							 	$roomtype = $getroomdetails[0];		
		
		$chargeid = $getroomdetails[1];	
			  		  $this->form_validation->set_rules("myid", "Receipt Id amount", "trim|required");

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

		
		 $this->load->view('userdata/changepayment', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updatepaymetmode'))
					   {
$tax1=0;
$tax2=0;
$ttamount=0;
						
				$roomdata = $this->usermodel->populatealldatanoarraythree('dailycharges','transactioncode', $transactioncode,'amount <>',0,'companyid',$companyid);

	if(is_array($roomdata)){
	
foreach ($roomdata as $c){



	
$tax1=$tax1+$c->tax;
$tax2=$tax2+$c->tax2;
$ttamount=$ttamount+$c->amount;
		
			}
			}		
						

						$data=array(

			'tax1'=>$tax1,
			'tax2'=>$tax2,
           // 'amount'=>$ttamount,




						
			'userid'=>$userid,
		'paymentstatus' => $paymentstatus,
		'tenantid'=>$tenantid,
							 	'createdat'=>$createdat,
							 	'checkoutdate'=>$checkoutdate,
							 	'chargeid'=>$chargeid,

							 	'plotno'=>$plotno,
			 	'houseno'=>$houseno,

						 	'description'=>$description,
			 	'roomtype'=>$roomtype ,
			 	'total'=>$ttamount ,

			 	'companyid'=>$companyid,
			
		  'mpesa' => $mpesa,    
		     'cheque' => $cheque,  
		     'card' => $card, 
			   'voucher' => $voucher, 
			   'credit' => $credit, 
					   'points' => $points,
					
					'amount' => $cash,
													   'people' => $people,

								   'balance' => $change,
							 'paymentcode' => $paymentcode,
							 'status' => $status,
							 'discount' => $discount,

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


														
							//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 updated the booking..</div>');	
								 redirect($view);
								 
							}
							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 booking   was not updated.May be you have not changed any value. Try again</div>');
								
								 redirect($myview);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

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

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


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

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		//$frotime="00:00:00";
				//	$totime="23:59:59";
	  
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		   $plotno = $this->input->post("plotno");
	  	  $houseno = $this->input->post("houseno");
		  
	
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

	$data['finalfromdate']=$finalfromdate;
		$data['view']=$view;

	$data['finaltodate']=$finaltodate;
	
	$data['companyid']=$companyid;
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="ADVANCE BOOKINGS REPORT";

			
		
				$data['advance'] = $this->usermodel->getereservations($finalfromdate,$finaltodate,$status,$plotno,$houseno);



			$this->load->view('pmsdata/viewalladvanceall',$data);
		$this->load->view("template/footerpage");
	}
		
  
  
  
  
  
  
  
  
  
  public function searchbulkreservedrooms()
	{ $session_data = $this->session->userdata('logged_in');

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


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

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		//$frotime="00:00:00";
				//	$totime="23:59:59";
	  
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		   $plotno = $this->input->post("plotno");
	  	  $houseno = $this->input->post("houseno");
		  
	
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

	$data['finalfromdate']=$finalfromdate;
		$data['view']=$view;

	$data['finaltodate']=$finaltodate;
	
	$data['companyid']=$companyid;
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['display']="";

$data['reporttype']="ADVANCE BOOKINGS REPORT";

			
		
				$data['booking'] = $this->usermodel->getbulkreservations($finalfromdate,$finaltodate,$status,$plotno,$houseno);



			$this->load->view('pmsdata/viewbulkreservation',$data);
		$this->load->view("template/footerpage");
	}
		
  public function searchreservedrooms()
	{ $session_data = $this->session->userdata('logged_in');

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


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

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		//$frotime="00:00:00";
				//	$totime="23:59:59";
	  
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		   $plotno = $this->input->post("plotno");
	  	  $houseno = $this->input->post("houseno");
		  
	
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

	$data['finalfromdate']=$finalfromdate;
		$data['view']=$view;

	$data['finaltodate']=$finaltodate;
	
	$data['companyid']=$companyid;
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="ADVANCE BOOKINGS REPORT";

			
		
				$data['booking'] = $this->usermodel->geteroomsreservations($finalfromdate,$finaltodate,$status,$plotno,$houseno);



			$this->load->view('pmsdata/pendinbookings',$data);
		$this->load->view("template/footerpage");
	}
		
  
  
  
  
  
  
  public function searchmeterreadings()
	{ $session_data = $this->session->userdata('logged_in');

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


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

				$this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		
		//$frotime="00:00:00";
				//	$totime="23:59:59";
	  
			        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);

		    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		   $plotno = $this->input->post("plotno");
	  	  $houseno = $this->input->post("houseno");
		  
	
		  	  $finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	

	$data['finalfromdate']=$finalfromdate;
		$data['view']=$view;

	$data['finaltodate']=$finaltodate;
	
	$data['companyid']=$companyid;
	$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;
$data['reporttype']="METER READINGS REPORT";

			
		
				$data['readings'] = $this->usermodel->searchmeterreadings($finalfromdate,$finaltodate,$status,$plotno,$houseno);
 $data['total_rows']=count((array) $data['readings']);

//

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

  
  
  
	public function deleteallbyid()
    {
			
 $view2= $this->input->post("view2");
   $view= $this->input->post("view");

	  $itemid= $this->input->post("itemid");
	  	  $plotno= $this->input->post("plotno");
			$houseno= $this->input->post("houseno");
	  	  	  $table= $this->input->post("table");
	  $dateposted = date('Y-m-d H:i:s');
	
				
	$session_data = $this->session->userdata('logged_in');

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

		 
		 
		 
        	 $usr_result = $this->accomodationmodel->deletebyid($itemid, $table);

        
		
			 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];												
								

							if ($usr_result ==TRUE) //active user record is present
							{
								
							
								if(  $table=="invoice"){
									
									
									
									
									
																		 $transactioncode= $this->input->post("transactioncode");

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

									$getinvoices = $this->usermodel->populatealldataarray('receipt','transactioncode', $transactioncode,'id >', 0);
				$tenantid=$getinvoices[0]['tenantid'];
				$branchid=$getinvoices[0]['branchid'];

		$INVOICEBALANCE=$getinvoices[0]['amount']- $amount;
		
			    $invoicedata=array(		
												'amount'=>$INVOICEBALANCE,

						
						);
									
																 $this->usermodel->updatedata($invoicedata,'receipt','transactioncode',$transactioncode);

									
									
												$getpeople = $this->usermodel->populatealldataarray('people','id', $tenantid,'id >', 0);

		$mybalance=$getpeople[0]['balance']- $amount;
		
			    $myinvoicedata=array(		
						'balance'=>$mybalance,

						
						);
									
																 $this->usermodel->updatedata($myinvoicedata,'people','id',$tenantid);
	  	  	  $type= $this->input->post("type");
			  
			  
			  
	 $accountnames = $this->usermodel->populatealldataarray('rentalpaymentmethodes','chargeid', $type,'branchid', $branchid);

		$salesaccount= $accountnames[0]['type'];
							
if($salesaccount ==""){
$salesaccount = "4000";
}else{
$salesaccount = $salesaccount;
	
}
							
									
										
								 $creditdata=array( 'userid'=>$userid,'account'=>1100,'credit'=>$amount,'description'=>"Returned sales",'code'=>$transactioncode,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "return" ,'supplier'=>$tenantid);


							$debitdata=array( 'userid'=>$userid,'account'=>$salesaccount,'debit'=>$amount,'description'=>"Returned sales",'code'=>$transactioncode,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "return" ,'supplier'=>$tenantid);
							$this->usermodel->deletedata($transactioncode,"code","debitcredit");

							//$usr_result = $this->usermodel->add($debitdata,'debitcredit');
							//$usr_result = $this->usermodel->add($creditdata,'debitcredit');	
													
		$this->usermodel->deletedata($transactioncode,"transactioncode","invoice");
	
									
	
									
									 $table2= $this->input->post("table");
										if(  $table2=="invoice"){
																
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
																						redirect($view);

											
											//redirect($view.$houseno.$view2.$plotno);
										}else{
												 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view);
											return false;
											
										}
									

								}
								
								
						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-info fade in"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong> You have successfully deleted this item!</div>');
											redirect($view.$houseno.$view2.$plotno);

									
							
									
									
							
								
							}
							else if ($usr_result ==FALSE) 
							{     

						 $this->session->set_flashdata('deletemsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> The Item was not deleted ..please try again</div>');
								
												redirect($view.$houseno.$view2.$plotno);
							}
	  
	  
	  
	  
	  
	  
	  
	  

	}
  
    
  
   public function populatehouseidvacant()
    {
		
		
         //set selected country id from POST
       $plotno = $this->input->post('plotno',TRUE);
       $transactiontype = $this->input->post('transactiontype',TRUE);

       $plotdata['myplots']=$this->accomodationmodel->populatehouseidvacant($plotno,$transactiontype);
        

             $output = null;
			
foreach ($plotdata['myplots'] as $row)
        {
          



            $output .= "<option value='".$row->id."'>".$row->houseno."</option>";
           
 
        }
		echo  $output;
			
        

        
    }
  
  
  
  
  
    
   public function populatebediddvacant()
    {
		   $plotnoid = $this->input->post('plotnoid',TRUE);
$houseid = $this->input->post('houseid',TRUE);
	//$houserent = $this->accomodationmodel->gethousedetails($plotnoid,$houseid);

	 //$roomid=$houserent[0]['id'];

	// $plotdata['myplots'] = $this->usermodel->populatealldatanoarray('beds','roomid', $roomid,'status', "active");
	 $plotdata['myplots'] = $this->usermodel->populatealldatanoarray('beds','roomid', trim($houseid),'status', "active");

        

             $output = null;
			
foreach ($plotdata['myplots'] as $row)
        {
          

$bedsdata=$row->id."==".$row->name;

            $output .= "<option value='".$bedsdata."'>".$row->name."</option>";
           
 
        }
		echo  $output;
			
        

        
    }
  
  
  
  
  
  
  
  
  
  
   public function populatehousecharges()
    {
		
		
         //set selected country id from POST
       $plotnoid = $this->input->post('plotnoid',TRUE);
$houseid = $this->input->post('houseid',TRUE);
        $plotdata['charges'] = $this->accomodationmodel->getplotcharges($plotnoid, $houseid);


             $output = null;
			
foreach ($plotdata['charges'] as $row)
        {
          

$chargename = $this->usermodel->populateallarray('charges','id', $row->chargeid);

	 $chargename=$chargename[0]['type'];
//
$roomdata=$row->cost."==".$row->chargeid;
  $mydetails=$chargename."(".$row->cost.")";



            $output .= "<option value='".$roomdata."'>".$mydetails."</option>";

 
        }
		echo  $output;
			
        

        
    }
  
  
   public function populatehouseid()
    {
		
		
         //set selected country id from POST
       $plotno = $this->input->post('plotno',TRUE);

       $plotdata['myplots']=$this->accomodationmodel->gethousebyplotid($plotno);
        

             $output = null;
			
foreach ($plotdata['myplots'] as $row)
        {
          



            $output .= "<option value='".$row->houseno."'>".$row->houseno."</option>";
           
 
        }
		echo  $output;
			
        

        
    }
  
  
     public function populatehousebyid()
    {
		
		
         //set selected country id from POST
       $plotno = $this->input->post('plotno',TRUE);

       $plotdata['myplots']=$this->accomodationmodel->gethousebyplotbyid($plotno);
        

             $output = null;
			
foreach ($plotdata['myplots'] as $row)
        {
          



            $output .= "<option value='".$row->houseno."'>".$row->houseno."</option>";
           

        }
		
		 echo  $output;	
        

        
    }
  
  

      
  public function rentinvoicedetailsbyuser() {
 
     if (isset($_GET['transactioncode'])){
     $tenantid = $_GET['transactioncode'];
	
		  $receipt=$this->usermodel->populateallarray('receipt','tenantid', $tenantid);
			$plotno=$receipt[0]['plotno'];
$houseno=$receipt[0]['houseno'];
		 
	 
     	$data['randomitemidentifier'] = $houseno;
		$data['randomitemidentifier1'] = $plotno;
		 

	
		$data['transactioncode'] = $tenantid;
		

	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				    					$data['invoice'] = $this->usermodel->populateall('invoice', 'tenantid',$tenantid);


				$this->load->view('pmsdata/houseinvoicedetails',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
     
  public function rentinvoicedetails() {
 
     if (isset($_GET['transactioncode'])){
     $transactioncode = $_GET['transactioncode'];
	
		  $receipt=$this->usermodel->populateallarray('receipt','transactioncode', $transactioncode);
			$plotno=$receipt[0]['plotno'];
$houseno=$receipt[0]['houseno'];
		 
	 
     	$data['randomitemidentifier'] = $houseno;
		$data['randomitemidentifier1'] = $plotno;
		 

	
		$data['transactioncode'] = $transactioncode;
		

	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				    					$data['invoice'] = $this->usermodel->populateall('invoice', 'transactioncode',$transactioncode);


			$this->load->view('pmsdata/houseinvoicedetails',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  

    
  public function bulkcheckindetails() {
 
     if (isset($_GET['transactioncode'])){
     $transactioncode = $_GET['transactioncode'];
	
		
   
		 

	
		$data['transactioncode'] = $transactioncode;
		

	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['booking'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactioncode);


			$this->load->view('pmsdata/dailypaymentgroup',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
    public function transferroomdaily() {
 
     if (isset($_GET['randomid'])){
     $randomid = $_GET['randomid'];
	
	
		$data['randomid'] = $randomid;
						$data['transactioncode'] =$_GET['transactioncode'];

				$data['housno'] =$_GET['housno'];
	$data['plotno'] =$_GET['plotno'];
$data['transactioncode'] =$_GET['transactioncode'];
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['house'] = $this->usermodel->populateall('dailycharges', 'id',$randomid);


			$this->load->view('pmsdata/transferroomdaily',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  
  
      
  public function transferroom() {
 
     if (isset($_GET['randomid'])){
     $randomid = $_GET['randomid'];
	
	
		$data['randomid'] = $randomid;
						$data['transactioncode'] =$_GET['transactioncode'];

				$data['housno'] =$_GET['housno'];
	$data['plotno'] =$_GET['plotno'];
$data['transactioncode'] =$_GET['transactioncode'];
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
			$data['house'] = $this->usermodel->populateall('bookroom', 'id',$randomid);


			$this->load->view('pmsdata/transferroom',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  
  
  
  
  
  
  
    
      
  public function updatebookingdetails() {
 
     if (isset($_GET['randomid'])){
      $randomid = $_GET['randomid'];
	
	
		$data['randomid'] = $randomid;
						$data['transactioncode'] =$_GET['transactioncode'];

				$data['housno'] =$_GET['housno'];
	$data['plotno'] =$_GET['plotno'];
$data['transactioncode'] =$_GET['transactioncode'];
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");


  $data['allsalesdetails']= $this->usermodel->populateallarray('bookroom','transactioncode',$_GET['transactioncode']);

$houserent = $this->accomodationmodel->gethousedetails($data['allsalesdetails'][0]["plotno"],$data['allsalesdetails'][0]["houseno"]);
		  $roomids=$houserent[0]["id"];		
								

$data['roomids']=$roomids;
			 
		$data['charges'] = $this->accomodationmodel->getplotcharges($data['allsalesdetails'][0]["plotno"], $roomids);

			$this->load->view('pmsdata/updatebookingdetails',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  public function collections()
	{ $session_data = $this->session->userdata('logged_in');

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


		$allgroup="";

		$totime = trim($this->usermodel->allterms_handler($this->input->get_post('totime', TRUE),'totime'));
				$frotime = trim($this->usermodel->allterms_handler($this->input->get_post('frotime', TRUE),'frotime'));
		
		$fromdate = ($this->usermodel->allterms_handler($this->input->get_post('fromdate', TRUE),'fromdate'));

		$todate = trim($this->usermodel->allterms_handler($this->input->get_post('todate', TRUE),'todate'));
		$category = trim($this->usermodel->allterms_handler($this->input->get_post('category', TRUE),'type'));

		$branch = trim($this->usermodel->allterms_handler($this->input->get_post('branchname', TRUE),'branchname'));
		$mygroup = trim($this->usermodel->allterms_handler($this->input->get_post('group', TRUE),'group'));


		


	 
		$download = trim($this->usermodel->allterms_handler($this->input->get_post('download', TRUE),'download'));

			$allgroup=$mygroup;
		
		
		
		
		
						$this->load->view("template/headerpagemin");

		
		
		//$this->load->view("template/tableheader");
	$finalfromdate=$fromdate." ".$frotime;
	  	  $finaltodate=$todate." ".$totime;
	if($category =="payment"){
				$data['allcollections'] = $this->usermodel->populateroomcollectionbytype($finalfromdate,$finaltodate,$companyid,"payment",$branch,$allgroup);

		$data['reporttype']="PAYMENTS RECEIVED ";

	} else if ($category =="paid"){
					$data['allcollections'] = $this->usermodel->populateroomcollectionbytype($finalfromdate,$finaltodate,$companyid,"paid",$branch,$allgroup);

				$data['reporttype']="PURCHASES PAID ";
	}	if($category =="bill"){
						$data['allcollections'] = $this->usermodel->populateroomcollectionbytype($finalfromdate,$finaltodate,$companyid,"bill",$branch,$allgroup);

		$data['reporttype']="BILLS PAID ";
	}
	
	



/*


		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

				$config['base_url'] = base_url('Systemusers/viewgroupsalesreport');
		$config['total_rows'] = $this->usermodel->count_allsales("sales",$finalfromdate,$finaltodate,$type,$companyid,$branch,$paymentstatus,$saletypes,$download,$group,$user);
			
		
			
			$config['per_page'] = 1000;
		$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);


         $this->load->view("template/headerpagemin");
		 //$this->load->view("template/tableheader");
		//$data['searchterm'] = $searchterm;
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
		$data["page"]=$page;
$allgroup="yes";

*/
	

$data['finaltodate']=$finaltodate;
$data['finalfromdate']=$finalfromdate;

$data['finalfromdate']=$finalfromdate;
	$data['finaltodate']=$finaltodate;
	$data['category']=$category;
	$data['companyid']=$companyid;

		$data['group']=$allgroup;

		$data['branch']=$branch;




			$this->load->view('pmsdata/viewcollections',$data);
		$this->load->view("template/footerpage");
	}
	
		
		
		
  
  
  
  
  
	
  public function updatetransferrooms()
    {
		
			$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'];
		 		
		 		 $transactioncode =  trim($this->input->post("transactioncode"));

				 $oldplotno = trim($this->input->post("oldplotno"));
			  $myhouseno =  trim($this->input->post("houseno"));
				$oldhouseno = trim($this->input->post("oldhouseno"));
				$randomid =  trim($this->input->post("randomid"));
			  
	
				
			  $this->form_validation->set_rules("oldplotno", "Product name", "trim|required");

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

		
		 $this->load->view('userdata/transferroom', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_transferroom') == "transfer")
					   {
						   
						   
						  $checkhouse = $this->usermodel->populateallarray('house','id',$myhouseno);

						$houseno=$checkhouse[0]["houseno"];  
						$plotno=$checkhouse[0]["plotno"];  
  
						   
						   
						   
						   
						   
						   

						  					$newhouserent = $this->accomodationmodel->checkvacancyarray($plotno,$houseno);
 
						   if($newhouserent==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 Room No( '.$houseno.') or Plot No( '.$plotno.') does not exist or it is currently occupied .. Try again a different Room No</div>');
								
							redirect('user/mychangepayment?myid='.$transactioncode);																
						   return false;
						   }
						   		    
						   
				$bookingdailycharges  = $this->usermodel->populatealldatanorraythree('dailycharges','plotno', $oldplotno,'houseno', $oldhouseno,'ordersales','active');
				$itemiddailycharges=$bookingdailycharges[0]['id'];		   
								   
				$datadaily=array(		
		
			
				'houseno'=>$houseno,
			
		  	'plotno'=>$plotno,
				

			'updatedby'=>$userid,
			'updatedat'=>$dateposted,
				
			
								);		   
						   
				$data=array(		
		
			
				'houseno'=>$houseno,
			
		  	'plotno'=>$plotno,
				

			'updatedid'=>$userid,
			'updatedat'=>$dateposted,
				
			
								);
	$usr_result = $this->usermodel->updatedata($data,'bookroom','id',$randomid);
	$this->usermodel->updatedata($datadaily,'dailycharges','id',$itemiddailycharges);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
			$oldhouserent = $this->accomodationmodel->gethousedetails($oldplotno,$oldhouseno);
		  $oldroomid=$oldhouserent[0]["id"];		
								
								
		 $newroomid=$newhouserent[0]["id"];					
								
					$olddata=array(		
		'status'=>"vacant",
			
			);
			
		
			$this->usermodel->updatedata($olddata,'house','id',$oldroomid);
			$newdata=array(		
		'status'=>"occupied",
			
			);				
			

$this->usermodel->updatedata($newdata,'house','id',$newroomid);					
								
								 
						 $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 transferred the customer to new room :'.$houseno.' ..</div>');	
							redirect('user/mychangepayment?myid='.$transactioncode);																
							}
							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 room  was not transferred.. Try again</div>');
								
							redirect('user/mychangepayment?myid='.$transactioncode);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
  
  
  
  
  	
  public function updatetransferroomsdaily()
    {
		
			$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'];
		 		
		 		 $transactioncode =  trim($this->input->post("transactioncode"));

				 $oldplotno = trim($this->input->post("oldplotno"));
			  $myhouseno =  trim($this->input->post("houseno"));
				$oldhouseno = trim($this->input->post("oldhouseno"));
				$randomid =  trim($this->input->post("randomid"));
			  
		    
	
				
			  $this->form_validation->set_rules("oldplotno", "Product name", "trim|required");

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

		
		 $this->load->view('userdata/transferroom', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_transferroom') == "transfer")
					   {
						   
						   
						  $checkhouse = $this->usermodel->populateallarray('house','id',$myhouseno);

						$houseno=$checkhouse[0]["houseno"];  
						$plotno=$checkhouse[0]["plotno"];  
  
						   
						   
						   
						   
						   
						   

						  					$newhouserent = $this->accomodationmodel->checkvacancyarray($plotno,$houseno);
 
						   if($newhouserent==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 Room No( '.$houseno.') or Plot No( '.$plotno.') does not exist or it is currently occupied .. Try again a different Room No</div>');
								
							redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode);																
						   return false;
						   }
						   
						   
						   
						   
						   
						   
						   
				$data=array(		
		
			
				'houseno'=>$houseno,
			
		  	'plotno'=>$plotno,
				

			'updatedby'=>$userid,
			'updatedat'=>$dateposted,
				
			
								);
	$usr_result = $this->usermodel->updatedata($data,'dailycharges','id',$randomid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
			$oldhouserent = $this->accomodationmodel->gethousedetails($oldplotno,$oldhouseno);
		  $oldroomid=$oldhouserent[0]["id"];		
								
								
		 $newroomid=$newhouserent[0]["id"];					
								
					$olddata=array(		
		'status'=>"vacant",
			
			);
			
		
			$this->usermodel->updatedata($olddata,'house','id',$oldroomid);
			$newdata=array(		
		'status'=>"occupied",
			
			);				
			

$this->usermodel->updatedata($newdata,'house','id',$newroomid);					
								
								 
						 $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 transferred the customer to new room :'.$houseno.' ..</div>');	
							redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode);																
							}
							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 room  was not transferred.. Try again</div>');
								
							redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
  
  
  
  
    
	
  public function updatelatestroomdetails()
    {
		
			$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'];
		 		
				
				$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		 		
				
		 		 $transactioncode =  trim($this->input->post("transactioncode"));

				 $oldplotno = trim($this->input->post("oldplotno"));
			
				$oldhouseno = trim($this->input->post("oldhouseno"));
				$randomid =  trim($this->input->post("randomid"));
			
		  $myroomtype =  trim($this->input->post("roomtype"));
		     $total =  trim($this->input->post("total"));
		     $type =  trim($this->input->post("type"));

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


				$checkintime =  trim($this->input->post("checkintime"));
				$checkouttime =  trim($this->input->post("checkouttime"));
				$createdat =  trim($this->input->post("createdat"));
			    $checkoutdate =  trim($this->input->post("checkoutdate"));



			$createdat=$createdat." ".$checkintime;

			$checkoutdate =$checkoutdate." ".$checkouttime;	 








				
			  $this->form_validation->set_rules("oldplotno", "Product name", "trim|required");

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

		
		 $this->load->view('userdata/transferroom', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_updateroomdetails') == "updateroom")
					   {
						   
						   
						  $checkhouse = $this->usermodel->populateallarray('house','id',$oldhouseno);

						$houseno=$checkhouse[0]["houseno"];  
						$plotno=$checkhouse[0]["plotno"];  
  
						   if((trim($type) != "Credit") ){
												
											$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 booking is not on the correct mode of payment ( '.$type.'). You can only change booking that are done on invoice / credit or invoice... Try again or change payment mode to credit</div>');
								
							//redirect('user/mychangepayment?myid='.$transactioncode);																
						  // return false;
											}
						   
						   
						    
						  					//$newhouserent = $this->accomodationmodel->checkvacancyarray($plotno,$houseno);
 			$newhouserent = $this->accomodationmodel->gethousedetails($oldplotno,$oldhouseno);

						   if($newhouserent ==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 Room No( '.$oldhouseno.') or Plot No( '.$oldplotno.') does not exist or it is currently occupied .. Try again a different Room No</div>');
								
							redirect('user/mychangepayment?myid='.$transactioncode);																
						   return false;
						   }
						   
						   
						   $number=1;
						   
						   
						   
						   				   $finaldate = strtotime(date($checkoutdate));
									$mycurrentdate = strtotime(date($createdat));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
				 
if($days< 1){
	
	$number=1;
}else{
		$number=$days;

}
$number=round($number,0);

						   
		 	$getroomdetails = explode("==",$myroomtype);
		
								$roomtype = $getroomdetails[0];		
		
		$chargeid = $getroomdetails[1];	
  
						   
						   
						   
						   
					
					$finalamount=($roomtype* $number);
				//	var_dump($getroomdetails);

//exit;
	 								$finalamount= $this->formatMoney($finalamount, true);

						  


$checkhouse = $this->usermodel->populateallarray('bookroom','transactioncode',$transactioncode);

						$oldbalance=$checkhouse[0]["balance"];  
						$oldcredit=$checkhouse[0]["credit"];
						
						$currentamount=$finalamount-$checkhouse[0]["total"];
$currentcredit=	$oldcredit+$currentamount;					
						//echo $finalamount;
//exit;						
						



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


	 $vatable=0;
		$myfinaltax=0;
		
			 $display1=$configuration[0]["display1"]; 
			$display2=$configuration[0]["display2"]; 
			
//$roomid=$houserents[0]['id'];

 $tax1rate=	$newhouserent[0]['vat'];	
$tax2rate=$newhouserent[0]['vat2'];
$vattype="";
	if($display1=="yes"){
		$vattype="VATABLE";
			
	if($display2=="yes"){
//echo $tax_included
	$tax_included=$newhouserent[0]['vat'];

	
	$tax2rate=$configuration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 //$ttoltaxable=(($sellingprice*$latestqty)/ $mytax2);
	 $ttoltaxable=(($finalamount)/ $mytax2);

	 
	 $myfinaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$vatable= $this->formatMoney($ttoltaxable, true);

	
	
	
	
	
	
	
	

	}else{
	 		 


	$mytax=1+($tax1rate/100); 
	$vatable=($finalamount/$mytax);
	$myfinaltax=(($finalamount-$vatable));
	$finaltax2=0;							
								
								
		
	}
	}else{
	 $vatable=0;
		$myfinaltax=0;
		$finaltax2=0;
			$vattype="ZERO RATED";
	}
			
			//








						
						   
				$data=array(		
		
			
				'createdat'=>$createdat,
			
		  	'checkoutdate'=>$checkoutdate,
				'total'=>$finalamount,
				//'amount'=>$finalamount,
				'credit'=>$currentcredit,
				'balance'=> -$currentcredit,
				'roomtype'=>$finalamount,
				//'vatable'=>$finalamount,
				'chargeid'=>$chargeid,
				'number'=>$number,

			'updatedid'=>$userid,
			'updatedat'=>$dateposted,
				'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
			
								);
	$usr_result = $this->usermodel->updatedata($data,'bookroom','id',$randomid);

							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
			$oldhouserent = $this->accomodationmodel->gethousedetails($oldplotno,$oldhouseno);
		  $oldroomid=$oldhouserent[0]["id"];		
								
								
		 $newroomid=$newhouserent[0]["id"];					
								
					$olddata=array(		
		
				'createdat'=>$createdat,
							'checkin'=>$createdat,

					'checkout'=>$checkoutdate,
					'taxable'=>$vatable,

				'amount'=>$finalamount,
				'code'=>$chargeid,
				'sprice'=>$roomtype,
				'cost'=>$roomtype,
				'qty'=>$number,
				'roomtype'=>$finalamount,
				
				
					//'taxable' => $vatable,
				'tax' => $myfinaltax,
				'tax2' => $finaltax2,
				
				
			//'updatedid'=>$userid,
			//'updatedat'=>$dateposted,
			
			);
			
		
			$this->usermodel->updatedata($olddata,'dailycharges','myinvoice',$transactioncode);
				
			
			
			
							$this->usermodel->deletedata($transactioncode,"code","debitcredit");
			
			
				if(($type=="Credit")|| ($type=="Invoice")|| ($type=="Creditnote")){
												
												$accountname=1100;
											}else{
											$accountname=1000;	
											}
				
				
				 $accountnames = $this->usermodel->populatealldataarray('rentalpaymentmethodes','chargeid', $chargeid,'branchid', $branchid);
if(	 $accountnames ==false){
			$myaccountnos= "1000";

}else{
		$myaccountnos= $accountnames[0]['type'];
	
}
//1000

		//$myaccountnos= $accountnames[0]['type'];
	
				if($description==""){
					
					$description="Room sold";
				}else{
					
					$description=$description;
				}
				//
			
			
						$creditdata=array( 'userid'=>$userid,'account'=>$myaccountnos,'credit'=>$finalamount,'description'=>$description,'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $tenantid);
						$this->usermodel->add($creditdata,'debitcredit');

							$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$finalamount,'description'=>"Room  sold",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
	//
										
									
								//$this->usermodel->updatedatabytwo($closedata,'sales_order','invoice',$invoice,'status<>','returned');
							$this->usermodel->add($debitdata,'debitcredit');

			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			

///$this->usermodel->updatedata($newdata,'house','id',$newroomid);					
								
								 
						 $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 updated room booking details for House No :'.$houseno.' ..</div>');	
							redirect('user/mychangepayment?myid='.$transactioncode);																
							}
							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 room booking info was not updated.. Try again</div>');
								
							redirect('user/mychangepayment?myid='.$transactioncode);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
  
  
  
  
  
  
  
  
  
  
  
  
   public function rentreceiptdetails() {
 
     if (isset($_GET['transactioncode'])){
     $transactioncode = $_GET['transactioncode'];
	
	 
     	$data['randomitemidentifier'] = "";
		$data['randomitemidentifier1'] = "";
		 

	
		$data['transactioncode'] = $transactioncode;
		

	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				    					$data['invoice'] = $this->usermodel->populateall('utilityinvoice', 'paymentcode',$transactioncode);


				$this->load->view('pmsdata/reeiptinvoicedetails',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  
  
  
  
  
  
    public function allrentinvoice() {
 
     if (isset($_GET['randomitemidentifier'])){
     $tenantid = $_GET['randomitemidentifier'];

	 
	 
	 
		 
		 
		 
		 
		 
		 				    					$data['invoice'] = $this->usermodel->populateall('receipt', 'tenantid',$tenantid);

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

				$this->load->view('pmsdata/houseinvoiceold',$data);
		$this->load->view("template/footerpage");
	}   else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
  
  
  
  
  
  
  
  
  
  
  
  
  public function rentinvoice() {
 
     if (isset($_GET['randomitemidentifier']) && isset($_GET['randomitemidentifier1'])){
     $houseno = htmlspecialchars($_GET['randomitemidentifier']);
	 $plotno = htmlspecialchars($_GET['randomitemidentifier1']);
	 
	 
	 		 
		 $plotdata=$this->usermodel->populateallarray('plot','id', $plotno);
	 $category=trim($plotdata[0]['category']);

  $invoicedate=($plotdata[0]['invoicedate']);
	$penaltydate=($plotdata[0]['penaltydate']);		 
		 
		 
		 $data['invoicedate'] = $invoicedate;
		$data['penaltydate'] = $penaltydate;
		 
		 
		 	$data['category'] = $category;
	 
	 
	 
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		
		$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		  $tenantid=($data['tenant'][0]['tenantid']);
	
		 
		 
											$data['invoice'] = $this->accomodationmodel->getrentalhouseinvoice($plotno,$houseno,$tenantid);
	$data['otherinvoice'] = $this->accomodationmodel->gethouseinvoice($plotno,$houseno,$tenantid);
	
			$data['plotcharges'] = $this->accomodationmodel->getrentplotcharges($plotno);

	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,trim($houseno));
		 $roomid=$data['houserent'][0]["id"];
				//$data['charges'] = $this->accomodationmodel->getrentplotcharges($plotno);
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno, $roomid);

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

				$this->load->view('pmsdata/houseinvoice',$data);
		$this->load->view("template/footerpage");
	}   else if (isset($_GET['randomitemidentifier1'])){
$plotno = $_GET['randomitemidentifier1'];
    $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
   	$data['plotno'] = $plotno;
	$data['invoice'] = $this->accomodationmodel->getbulkhouseinvoice($plotno);
	$data['otherinvoice'] = $this->accomodationmodel->getbulkhouseentalinvoice($plotno);
			$data['plotcharges'] = $this->accomodationmodel->getrentplotcharges($plotno);

	//$data['tenant'] = $this->adminusermodel->gettenantid($plotno,$houseno);
		//$data['charges'] = $this->adminusermodel->getplotcharges($plotno);
	//$data['houserent'] = $this->adminusermodel->getbulkhousedetails($plotno);
		
		

				$this->load->view('pmsdata/bulkhouse',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  
  
  
    public function invoice() {
 
     if (isset($_GET['randomitemidentifier']) && isset($_GET['randomitemidentifier1'])){
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
	$data['invoice'] = $this->accomodationmodel->gethouseinvoice($plotno,$houseno);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/houseinvoice',$data);
		$this->load->view("template/footerpage");
	}   else if (isset($_GET['randomitemidentifier1'])){
$plotno = $_GET['randomitemidentifier1'];
    
   	$data['plotno'] = $plotno;
	$data['invoice'] = $this->accomodationmodel->getbulkhouseinvoice($plotno);
	//$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	//$data['houserent'] = $this->accomodationmodel->getbulkhousedetails($plotno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/bulkhouse',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
	
	
	  public function newcoparentapplication() {
   
    
	
	$data['payment'] = $this->accomodationmodel->getnewcoparent();
		$data['allpayment'] = $this->accomodationmodel->getallcoparent();
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/newcoparent',$data);
		$this->load->view("template/footerpage");
	
  }
	
	
	 public function coparentapproval() {
   if (!isset($_GET['randomitemidentifier'])){

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

     

	$data['tenant'] = $this->accomodationmodel->getcoparentapproval($id);
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/approvecoparent',$data);
		$this->load->view("template/footerpage");
	}
  }
	
	
	
	 public function invoicecoparent() {
   if (!isset($_GET['randomitemidentifier'])){

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

     

	$data['tenant'] = $this->accomodationmodel->getcoparentapproval($id);
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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


	
	 
	
	
	
	
	
	
	
	
	
	
	
	
    public function housepaymentbyno() {
   if (!($this->input->post('btn_housepaymentbyno'))){

    
      show_error('No identifier provided', 500);
    }
    else {
		$houseno = $this->input->post("houseno");
		$plotno = $this->input->post("plotno");

    
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
		$data['allpayment'] = $this->accomodationmodel->getallplotreceiptbyno($plotno,$houseno);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/housepaymentbyno',$data);
		$this->load->view("template/footerpage");
	}
  }
	
	
	
	
	
    public function printhouseinvoice() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier'];
			        		$houses = $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

		
		
		
     $houseno = $houses[0]['houseno'];
	 $plotno = $houses[0]['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
//
$data['viewreceipt']= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

		$data['viewsales'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);

	
		
   
   
   
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier'];
			        		$houses = $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

			$status = $_GET['status'];
		
		
     $houseno = $houses[0]['houseno'];
	 $plotno = $houses[0]['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
//
$data['viewreceipt']= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

		//$data['viewsales'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);
	$data['viewsales'] = $this->usermodel->populatealldatanoarray('dailycharges','transactioncode',$transactionid,'sales',$status);

	
		
   
   
   
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier'];
			        		$houses = $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

		
		
		
     $houseno = $houses[0]['houseno'];
	 $plotno = $houses[0]['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
//

$rooms= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

	
		
		$data['roomcharges'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);
   
   
   
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier'];
			        		$houses = $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

		
		
		
     $houseno = $houses[0]['houseno'];
	 $plotno = $houses[0]['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
//

//$data['rooms']= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);
$data['viewreceipt']= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

	
			//$data['viewsales'] = $this->usermodel->populatealldatanoarray('dailycharges','transactioncode',$transactionid,'sales',$status);
		$data['viewsales'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);

		//$data['roomcharges'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);
   
   
   
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
//
				$this->load->view('pmsdata/housreceipttbynoold',$data);
		$this->load->view("template/footerpage");
	}
  }

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

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier'];
			        		$houses = $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

		
		
		
     $houseno = $houses[0]['houseno'];
	 $plotno = $houses[0]['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
//

//$data['rooms']= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);
$data['viewreceipt']= $this->usermodel->populateallarray('bookroom','transactioncode',$transactionid);

	
			//$data['viewsales'] = $this->usermodel->populatealldatanoarray('dailycharges','transactioncode',$transactionid,'sales',$status);
		$data['viewsales'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);

		//$data['roomcharges'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$transactionid);
   
   
   
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
//
				$this->load->view('pmsdata/housreceipttbyno',$data);
		$this->load->view("template/footerpage");
	}
  }

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

    
      show_error('No identifier provided', 500);
    }
    else {
		
		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier'];
     $houseno = $_GET['houseno'];
	 $plotno = $_GET['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
		    					$data['roomcharges'] = $this->usermodel->populateall('dailycharges', 'chargeid',$transactionid);

	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

  

  
  
  
  
    public function allhousereceiptbyno() {
   if (!isset($_GET['randomitemidentifier1'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		$transactionid = $_GET['randomitemidentifier1'];
     $houseno = $_GET['houseno'];
	 $plotno = $_GET['plotno'];
	 $tenantid = $_GET['nyumbaid'];
	 $month = $_GET['month'];
	 $year = $_GET['year'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
		$data['allpayment'] = $this->accomodationmodel->getplotreceiptallbyype($plotno,$houseno,$month,$year, $tenantid);
		$data['balance'] = $this->accomodationmodel->getplotreceiptallbybalance($plotno,$houseno,$month,$year, $tenantid);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptallbyno($plotno,$houseno,$month,$year, $tenantid);
				//$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);

		
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);

	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
	  $roomidentifier = $_GET['roomidentifier'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		$data['roomidentifier'] = $roomidentifier;
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno, $roomidentifier);
		
	$data['payment'] = $this->accomodationmodel->gethousepayment($plotno,$houseno);
		$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/housepayment',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  
  
  
  
  public function dailypayment() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 	 $display = "No";	
    	$data['display']= $display ;	
	$data['booking'] = $this->usermodel->populatedailypeyment($companyid);

		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				//$this->load->view('pmsdata/rentdailypayment',$data);

		
				$this->load->view('pmsdata/salesreceipts',$data);
		$this->load->view("template/footerpage");
	
  }
  
   public function viewmeterreadings() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
    $data['readings']  = $this->usermodel->populatealldatarraythreeWater('meterreading','branchid', $branchid,'status',"open",'id >',0 );
    //$data['readings']  = $this->usermodel->populatealldatarraythree('meterreading','branchid', $branchid,'status',"open",'id >',0 );
 $data['total_rows']=count((array) $data['readings']);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

		
				$this->load->view('pmsdata/viewmeterreadings',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  
  	public function updatemeterreading() {
 
  if ($this->input->post('btn_updatemeterreading') == "editreading")
					   {
			
		
					   	$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	
	$userid=$data['id'] ;
	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
	 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:s');
 		  $dateposted = date('Y-m-d H:i:s');
		
		  $mydate=date("Y-m-d H:i:s");
		  
	
		  							 $mybranch = trim($this->input->post("mybranch"));

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

						
							  $myid = trim($this->input->post("myid"));
							
							
						$opening = trim($this->input->post("opening"));
						$closing = trim($this->input->post("closing"));
						$roomid = trim($this->input->post("roomid"));
						$roomchargeid = trim($this->input->post("roomchargeid"));

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

											// $houseno = trim($this->input->post("houseno"));
											
											 
											 
				$data=array(		'closing'=>$closing,
												'opening'=>$opening,
													'updatedby'=>$userid,
													'updatedat'=>$postedtime,
													);
		
											
										$usr_result = $this->usermodel->updatedata($data,'meterreading','id',$myid);

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

	 if($roomchargeid !=""){
		 
		 
				$roomdata=array(		
												'cost'=>$closing,
													'userid'=>$userid,
													'updatedat'=>$postedtime,
				);
		
											
					 $this->usermodel->updatedata($roomdata,'roomcharges','id',$roomchargeid);

		 
	 }
								
								
								
						 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
						<strong>Success!</strong> Updated successfully. </div>');
							redirect($view);						   
					

							
					
							
								
							}
							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> Data not  updated! May be because  you have not edited any price or No delivery No Entered. try again </div>');
							redirect($view);
							}
  
  
  
  
  
  
  
  
  
  
  
  }else{

		redirect("login");
  
  
    }
    
	}
	
    
  
  public function pendingsalesreceipts() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
    
	//$data['booking'] = $this->usermodel->populatedailypeyment($companyid);
	$data['booking'] = $this->usermodel->populatedailypeymentpending($companyid,$branchid);

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

		
				$this->load->view('pmsdata/salesreceipts',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  public function salesreceipts() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
$smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$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;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
	
		$data['booking'] =  $this->usermodel->populatedailypeymentOccupied($companyid,$branchid,$finalstartdate,$finalendate);
	
	//
	
	
	//
	//$data['booking'] = $this->usermodel->populatedailypeyment($companyid);

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

		
				$this->load->view('pmsdata/salesreceipts',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  public function customerregister() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $data['branchid'] = $session_data['branchid'];
	$branchid = $data['branchid'];
    $smsconfig = $this->usermodel->populateallarray('smsconfig','id',$companyid);
		 		$currenttime = date('H:i');

		 
		  $year=date("Y");
		  $month=date("m");
		   $day=date("d");
		   
		   $subtract=$day-1;
		   $add=$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;
		 }
		 
		 
		  	 $finalendatechecker = htmlspecialchars(trim(explode('-',date("Y-m-d", strtotime($finalendate)))[0]));	
		
					
		 if($finalendatechecker=="1970"){
			 
			 

		$mynew_date = date("Y-m-d", strtotime("+1 day"));
			 
			 
		 $finalendate=$mynew_date.' '. $duetime.':00';	 
		 }
		
		
		
		
	$data['booking'] = $this->usermodel->populatedailypeyment($companyid,$branchid,$finalstartdate,$finalendate);

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

		
				$this->load->view('pmsdata/customerregister',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  
  
  
  
  
  
    
  public function searchforrentgeneralreport() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
    
	$data['booking'] = $this->accomodationmodel->populatedailypeyment($companyid);

		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		 $todate = $this->input->post('todate',TRUE);
		 $fromdate = $this->input->post('fromdate',TRUE);
		 		 $plotno = $this->input->post('plotno',TRUE);
	 $status = $this->input->post('status',TRUE);
	 $charges = $this->input->post('charges',TRUE);

		 $display = $this->input->post('display',TRUE);
		 $paymentstatus = $this->input->post('paymentstatus',TRUE);
	 $data['fromdate'] =$fromdate;
	 	 $data['paymentstatus'] =$paymentstatus;
	  $data['todate'] =$todate;
	    $data['status'] =$status;
			    $data['charges'] =$charges;
 if($paymentstatus=="balances"){
		  		$data['invoice'] = $this->accomodationmodel->getrentbalances($fromdate,$todate,$plotno,$status,$paymentstatus);
				$this->load->view('pmsdata/alltenantbalances',$data);

	  }else  if($paymentstatus=="overpayment"){
		  		$data['invoice'] = $this->accomodationmodel->getrentbalances($fromdate,$todate,$plotno,$status,$paymentstatus);
				$this->load->view('pmsdata/alltenantbalances',$data);

	  }else  if($paymentstatus=="deposit"){
		  		$data['invoice'] = $this->accomodationmodel->getrentbalances($fromdate,$todate,$plotno,$status,$paymentstatus);
				$this->load->view('pmsdata/alltenantbalances',$data);

	  }else  if($paymentstatus=="utilities"){
		  
//
				$data['invoice'] = $this->accomodationmodel->getrentalutilities($fromdate,$todate,$plotno,$paymentstatus,$charges);
				$this->load->view('pmsdata/viewutilities',$data);

	  } else  if($paymentstatus=="receiptutility"){
		  
//
  	$data['randomitemidentifier'] = "";
		$data['randomitemidentifier1'] = "";
		 
				$data['invoice'] = $this->accomodationmodel->getrentalutilitiespaymets($fromdate,$todate,$plotno,$paymentstatus,$charges);
				$this->load->view('pmsdata/reeiptinvoicedetails',$data);

	  } else{
		    	$data['randomitemidentifier'] = "";
		$data['randomitemidentifier1'] = "";
		 
				$data['invoice'] = $this->accomodationmodel->getrentalleinvoice($fromdate,$todate,$plotno,$paymentstatus);
 				$this->load->view('pmsdata/searchforrentgeneralreport',$data);

	  }

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

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

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

		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		 $todate = $this->input->post('todate',TRUE);
		 $fromdate = $this->input->post('fromdate',TRUE);
		 		 $plotno = $this->input->post('plotno',TRUE);
	 $paymenttype = $this->input->post('paymenttype',TRUE);
	
	 $data['fromdate'] =$fromdate;
	 	 $data['paymenttype'] =$paymenttype;
	  $data['todate'] =$todate;
	  

				$data['invoice'] = $this->accomodationmodel->searchfordepositreport($fromdate,$todate,$plotno,$paymenttype);
 				$this->load->view('pmsdata/searchfordepositreport',$data);

	

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

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
    					$data['booking'] = $this->usermodel->populateall('dailycharges', 'companyid',$companyid);

	

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

		
				$this->load->view('pmsdata/dailychargespayment',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
	   public function populatestudent()
    {
		
		
		
         //set selected country id from POST
       $campusidcampusid = $this->input->post('campusid',TRUE);
		 $programid = $this->input->post('programid',TRUE);
        //run the query for the cities we specified earlier
       $campusdata['mycampuscourse']=$this->coursemodel->getothercost($campusid,$programid);
        
       

        foreach ($campusdata['mycampuscourse'] as $row)
        {
        	       $coursedata['mycourse']=$this->coursemodel->getcoursebyid($row->courseid);

             $output = null;
foreach ($coursedata['mycourse'] as $row1)
        {
          



            $output .= "<option value='".$row1->id."'>".$row1->name."</option>";
            //var_dump($row);

        }
            echo  $output;
        }

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

    
      show_error('No identifier provided', 500);
    }
    else {
     $landlordid = $_GET['randomitemidentifier'];
	
     	$data['landlordid'] = $landlordid;
		
	
   		$data['landlord'] = $this->accomodationmodel->getlandlordbyid($landlordid);

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

				$this->load->view('pmsdata/viewlandlord',$data);
		$this->load->view("template/footerpage");
	}
  }
public function edicharge() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $chargeid = $_GET['randomitemidentifier'];
	
     	$data['chargeid'] = $chargeid;
		
	
   		$data['charge'] = $this->accomodationmodel->getplotchargebyid($chargeid);

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

				$this->load->view('pmsdata/viewcharge',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  
  
  public function edituser() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $userid = $_GET['randomitemidentifier'];
	
     	$data['userid'] = $userid;
		
	
	 $data['admin'] = $this->accomodationmodel->populatepmsdata($userid);

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

				$this->load->view('adminpage',$data);
		$this->load->view("template/footerpage");
		
		
	}
  }
  
  
public function editagent() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $agentid = $_GET['randomitemidentifier'];
	
     	$data['agentid'] = $agentid;
		
	
   		$data['agent'] = $this->accomodationmodel->getagentbyid($agentid);

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

				$this->load->view('pmsdata/viewagents',$data);
		$this->load->view("template/footerpage");
	}
  }
public function edittenant() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $tenantid = $_GET['randomitemidentifier'];
	
     	$data['tenantid'] = $tenantid;
		
	
   		$data['tenant'] = $this->accomodationmodel->gettenantallid($tenantid);

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

				$this->load->view('pmsdata/viewtenants',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  public function editadvance() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $myid = $_GET['randomitemidentifier'];
	
     	$data['myid'] = $myid;
		
	
					$data['advance'] = $this->usermodel->populateallarray('advance', 'id',$myid);

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

				$this->load->view('pmsdata/editadvance',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  
  
  
  public function editplot() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $plotid = $_GET['randomitemidentifier'];
	
     	$data['plotid'] = $plotid;
		
	
   		$data['plot'] = $this->accomodationmodel->getplotid($plotid);

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

				$this->load->view('pmsdata/viewplots',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  public function editcountry() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $countryid = $_GET['randomitemidentifier'];
	
     	$data['countryid'] = $countryid;
		
	
   		$data['country'] = $this->accomodationmodel->getcountryid($countryid);

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

				$this->load->view('pmsdata/viewcountry',$data);
		$this->load->view("template/footerpage");
	}
  }
  
public function editpaymentmethod() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $methodid = $_GET['randomitemidentifier'];
	
     	$data['methodid'] = $methodid;
		
	
   		$data['paymentmethod'] = $this->accomodationmodel->getpaymentmethodid($methodid);

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

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
     $houseid = $_GET['randomitemidentifier'];
	
     	$data['houseid'] = $houseid;
		
	
   		$data['house'] = $this->accomodationmodel->gethouseid($houseid);

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

				$this->load->view('pmsdata/editallhouses',$data);
		$this->load->view("template/footerpage");
	}
  }
  
  
  
  
  
  
  
  
  	public function startmeterreading()
	{ $session_data = $this->session->userdata('logged_in');

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

	  $postedtime = $this->input->post("postedtime");
	  $startdate =$this->input->post("startdate");
	  $type =$this->input->post("type");
	  $plotno =$this->input->post("plotno");
	  $year =$this->input->post("year");
	  $month =($this->input->post("month"));
	  $metername =$this->input->post("metername");
		  $createdat = Date('Y-m-d H:i:s') ;
	  $readingtype =$this->input->post("readingtype");
	  $roomno =$this->input->post("roomno");
$month = sprintf("%02d", $month);

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

		 if ($this->input->post('openmeter') == "meter")
					   {
						   
						   				
if($metername=="waterno"){
			  				 $myproducts = $this->usermodel->populatealldatanoarrayFIVEReadings('house','waterno <>', '','plotno', $plotno,'companyid', $companyid,$readingtype,$roomno);			   

	
}else if($metername=="electricityno"){
			  				 $myproducts = $this->usermodel->populatealldatanoarrayFIVEReadings('house','electricityno <>', '','plotno', $plotno,'companyid', $companyid,$readingtype,$roomno);			   

	
}else if($metername=="bowholeno"){
			  				 $myproducts = $this->usermodel->populatealldatanoarrayFIVEReadings('house','bowholeno <>', '','plotno', $plotno,'companyid', $companyid,$readingtype,$roomno);			   
	
	
	
}

		 
 
	
		   
		   

		   $tenantid="0";
		   
		   $data =array();
if(is_array($myproducts)) {

   foreach($myproducts as $row)
   {
	$tenants = $this->accomodationmodel->gettenantid($row->plotno,$row->houseno);

if($tenants[0]['tenantid']!=""){
						$tenantid=($tenants[0]['tenantid']);

}else{
	  $tenantid="";
}

$roomcharges = $this->usermodel->populatethreenoarray('roomcharges','plotno', $row->plotno,'roomid', $row->id,'chargeid', $type);

if($roomcharges[0]['chargeid']!=""){
						$chargeid=($roomcharges[0]['chargeid']);
						$roomchargeid=($roomcharges[0]['id']);

}else{
	  $chargeid="";
	  	  $roomchargeid="";

}



if($metername=="waterno"){
	$data[]=array(	
			'status'=>"open",		
			'tenantid'=>$tenantid,
						'chargeid'=>$chargeid,
			'roomchargeid'=>$roomchargeid,

			'roomid'=>$row->id,
			'category'=>$metername,

			'createdat'=>$createdat,
			'branchid'=>$mybranch,
		  	'entrydate'=>$startdate,
			'type'=>$type,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'year'=>$year,
		  	'month'=>$month,
				'houseno'=>$row->houseno,
			'plotno'=>$row->plotno,
				'meternumber'=>$row->waterno,
				'rate'=>$row->waterrate,
				'charge'=>$row->watercharge,
		 
			
								);
	
	
}else if($metername=="electricityno"){
	$data[]=array(	
			'status'=>"open",
	'roomid'=>$row->id,
						'chargeid'=>$chargeid,
			'roomchargeid'=>$roomchargeid,

							'tenantid'=>$tenantid,
						'category'=>$metername,

			'createdat'=>$createdat,
			'branchid'=>$mybranch,
		  	'entrydate'=>$startdate,
			'type'=>$type,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'year'=>$year,
		  	'month'=>$month,
				'houseno'=>$row->houseno,
			'plotno'=>$row->plotno,
			'meternumber'=>$row->electricityno,
			'rate'=>$row->electricityrate,

			'charge'=>$row->electricitycharge,
		
		  
								);
	
}else if($metername=="bowholeno"){
$data[]=array(
			'status'=>"open",
				'roomid'=>$row->id,
			'chargeid'=>$chargeid,
			'roomchargeid'=>$roomchargeid,

						'tenantid'=>$tenantid,
									'category'=>$metername,

			'createdat'=>$createdat,
			'branchid'=>$mybranch,
		  	'entrydate'=>$startdate,
			'type'=>$type,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'year'=>$year,
		  	'month'=>$month,
				'houseno'=>$row->houseno,
			'plotno'=>$row->plotno,
				'meternumber'=>$row->bowholeno,
				'rate'=>$row->bowholerate,
				'charge'=>$row->bowholecharge,

			
								);	
	
	
}
 	
   
	
}


$usr_result =$this->db->insert_batch('meterreading', $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 meter reading..</div>');	
										
													redirect('admin/viewmeterreadings');	
	
													
							}
							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 meter readings was not opened. May be because of already existing opening stock for the same date.Try again</div>');
								
												redirect('admin/viewmeterreadings');	
	
							}
} else {
    //echo   "No student";
	
}
						   
						   
					   }else{
						   
						  redirect("admin/viewmeterreadings") ;
					   }
	
					   
	
	}
	

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

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

	  $postedtime = $this->input->post("postedtime");
	  $startdate =$this->input->post("startdate");
	  $type =$this->input->post("type");
	  $plotno =$this->input->post("plotno");
	  $year =$this->input->post("year");
	  $month =$this->input->post("month");
	
	 $month = sprintf("%02d", $month);

	  $metername =$this->input->post("metername");
		  $createdat = Date('Y-m-d H:i:s') ;
	  $method =$this->input->post("method");
	  $totalconsumed =$this->input->post("totalconsumed");
   $nextmonth =$this->input->post("nextmonth");
	  $nextyear =$this->input->post("nextyear");
	  $closetype =$this->input->post("closetype");
 $readingtype =$this->input->post("readingtype");
	  $roomno =$this->input->post("roomno");
	  $category =$this->input->post("category");

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

		 if ($this->input->post('closemeter') == "meter")
					   {
						   
			$data['readings']= $this->usermodel->populatealldatanoarraySEVENReadings('meterreading','category',$metername,'plotno', $plotno,'status', "open",$readingtype,$roomno,'year', $year,'month', $month);			   
				  


			  
//$data['readings']= $this->usermodel->populatealldatanoarrayFIVEReadings('meterreading','category',$metername,'plotno', $plotno,'status', "open",$readingtype,$roomno);			   
 $data['total_rows']=count((array) $data['readings']);

		// $this->load->view("template/tableheader");
		$data['method']=$method;
		$data['totalconsumed']=$totalconsumed;
	
		
		
		$data['month2']=$month;
		
		
		$data['month']=$month;
		$data['year']=$year;
		$data['type']=$type;
			$data['plotno']=$plotno;
		$data['metername']=$metername;
		$data['nextmonth']=$nextmonth;
		$data['nextyear']=$nextyear;
		$data['closetype']=$closetype;
	$data['readingtype']=$readingtype;
		$data['category']=$category;

			$data['roomno']=$roomno;
				$this->load->view('pmsdata/closemeterreading',$data);
		$this->load->view("template/footerpage");

				///		   
						   
					   }else{
						   
						  redirect("admin/viewmeterreadings") ;
					   }
	
					   
	
	}
	
	
	
  	  public function bulkclosingofreadingsonebyone() {
   if (!isset($_GET['plotno'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		    	$this->load->view("template/headerpagemin");

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		
			$method= $_GET['method'];
		$totalconsumed= $_GET['totalconsumed'];
		$month2= $_GET['month'];
		$year= $_GET['year'];
		$type= $_GET['type'];
			$plotno= $_GET['plotno'];
		$metername= $_GET['metername'];
		$nextmonth= $_GET['nextmonth'];
		$nextyear= $_GET['nextyear'];
		$closetype= $_GET['closetype'];
	$readingtype= $_GET['readingtype'];
		$category= $_GET['category'];
	 $month2 = sprintf("%02d", $month2);

			$roomno= $_GET['roomno'];
			
	
	
	$data['readings']= $this->usermodel->populatealldatanoarraySEVENReadings('meterreading','category',$metername,'plotno', $plotno,'status', "open",$readingtype,$roomno,'year', $year,'month', $month2);			   
 $data['total_rows']=count((array) $data['readings']);

   		

							
			$data['method']=$method;
		$data['totalconsumed']=$totalconsumed;
		$data['month2']=$month2;
		$data['month']=$month2;
		$data['year']=$year;
		$data['type']=$type;
			$data['plotno']=$plotno;
		$data['metername']=$metername;
		$data['nextmonth']=$nextmonth;
		$data['nextyear']=$nextyear;
		$data['closetype']=$closetype;
	$data['readingtype']=$readingtype;
		$data['category']=$category;

			$data['roomno']=$roomno;

				$this->load->view('pmsdata/closemeterreading',$data);
		$this->load->view("template/footerpage");
		
	}
  }
  
  
  
  
  public function bulkclosingofreadingsingle() {
	 
	$session_data = $this->session->userdata('logged_in');
//
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");

	  $postedtime = $this->input->post("postedtime");
	  $startdate =$this->input->post("startdate");
	  $type =$this->input->post("type");
	  $plotno =$this->input->post("plotno");
	   $houseno =$this->input->post("houseno");
	   $year =$this->input->post("year");
	  $month =$this->input->post("month");
	  $metername =$this->input->post("metername");

 $month = sprintf("%02d", $month);


	   $rate =$this->input->post("rate");
	  $charge =$this->input->post("charge");
	  $tenatid =$this->input->post("tenatid");
	  	  $myid =$this->input->post("myid");
	  $closing =$this->input->post("closing");
	  $opening =$this->input->post("opening");
	  $roomid =$this->input->post("roomid");
	  $tenantid =$this->input->post("tenantid");

	  $method =$this->input->post("method");
	  $totalconsumed =$this->input->post("totalconsumed");



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

  $month2 =$this->input->post("month2");
	  $metername2 =$this->input->post("metername2");
	  $plotno2 =$this->input->post("plotno2");
	  $type2 =$this->input->post("type2");

	  $year2 =$this->input->post("year2");
	  $nextmonth =$this->input->post("nextmonth");
	  $nextyear =$this->input->post("nextyear");
	  $category =$this->input->post("category");

	  $readingtype =$this->input->post("readingtype");
	  $roomno =$this->input->post("roomno");
 $month2 = sprintf("%02d", $month2);






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

		  $createdat = Date('Y-m-d H:i:s') ;
$createdatmonth = Date('Y-m-d') ;
 //if (trim($this->input->post('btn_bulkclosereadings'))=="closereadingsNOW"){
				


			  	$this->form_validation->set_rules("roomno", "Roomno No", "trim|required");

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

		
		 $this->load->view('pmsdata/closemeterreading', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 





				
			// if ($this->input->post('btn_bulkclosereadings') =="closereadings")
					   //{			   
					
			$mytotalconsumed=0;
			if($method=="manual"){
				
							 $counter =count((array) $closing);

				 	 
					//$counter =count((array) $closing);
					
		
				   
	   	 $mytotalconsumed=(double)$mytotalconsumed+((double)$closing-(double)$opening);	
		
			  
				
				
				
				
			}

			
				 //$counter =count((array) $closing);
				
				 //for($b=0; $b< $counter; $b++) {
				   
	   		
		//echo$houseno[$b]."<br>";
			  // }
				
			
			
				 $myidsss =count((array) $opening);
			
			
			
			
			
			$count =count((array) $closing);
			//exit;
			 

  
	   
	   
	   if($metername=="waterno"){
	$bill_name="Water";

	
}else if($metername=="electricityno"){
	$bill_name="Electricity";

	
}else if($metername=="bowholeno"){
	$bill_name="Bowhole";
	
	
	
}

	   
	

	   
//
//var_dump($roomid[$i]);


//exit;

	   $usedqty=((double)$closing-(double)$opening);
	   
	   	if($method=="manual"){
			$scharge=(double)(($usedqty/$mytotalconsumed)*$totalconsumed) ;
	   $totalamount=(double)((($closing-$opening[$i])*$rate)+$scharge);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing,
'usedqty'=>$usedqty,
'charge'=>$scharge,
'totalamount'=>$totalamount,
             
			 );
		} else if($method=="automatic"){ 
		
		
	   
	   
  $totalamount=((((double)$closing-(double)$opening)*(double)$rate)+(double)$charge);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing,
'usedqty'=>$usedqty,
'totalamount'=>$totalamount,
             
			 );

		

	} else if($method=="Tariff"){ 

	 

		$GETWATER = $this->usermodel->populatealldatanoarraythreeAsc('waterrates','category', $category,'start <',$usedqty,'companyid',$companyid);


$totalamount=0;
if(is_array($GETWATER)){
	
foreach ($GETWATER as $row){
	$total=0;
	$start=(double)$row->start;
	$end=(double)$row->end;
	$rate=(double)$row->amount;
	$flatrate=(double)$row->flatrate;
	if($flatrate=="yes"){
			$total=$rate;

		
	}else{
		if($usedqty  >=  $end ){
		$total=(($end-$start)*$rate);
		}else{
			$total=(($usedqty-$start)*$rate);
		}
		
		
	}
	
	
$totalamount=(double)$totalamount+(double)$total;
}
								
					//echo"</br>". $totalamount;			
								
								}
$totalamount=(double)$totalamount+(double)$charge;

	//
	
 // $totalamount=((($closing[$i]-$opening[$i])*$rate[$i])+$charge[$i]);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing,
'usedqty'=>$usedqty,
'totalamount'=>($totalamount),
             
			 );

//
//


		}			
  		$usr_result = $this->usermodel->updatedata($data,'meterreading','id',$myid);
   	   	 
		 $charges = $this->accomodationmodel->getplotchargesarray($plotno,$roomid,$type);
$chargeid= $charges[0]['id'];
      $chargedata = array(
	  

		'cost'=>$totalamount,
       'name'=>$myid,
      
			 );
			 	
  		$this->usermodel->updatedata($chargedata,'roomcharges','id',$chargeid);
			if($totalamount > 0){
						
$month_name = date("F", mktime(0, 0, 0, $month, 10));
  
		
$users = $this->usermodel->populateallarray('people','id', $tenantid);
$contact=$users[0]['phone'];

								
			  
				$taskmessage = "Dear ". $users[0]['firstname'] .",your ".$month_name." ".$bill_name." bill is ".$totalamount." current reading is ".$closing." , previous reading is  ".$opening.",units consumed  ".$usedqty.", totaling to ". $totalamount ." for Hs No.". $houseno.".";


  
			
									$myview="admin/viewmeterreadings";

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

								



		
			if ($usr_result ==TRUE) //active user record is present
							{
								
		
								
						if ($closetype=="closeopen"){
							
							
							
									$readings= $this->usermodel->populatealldatanoarraysix('meterreading','category',$metername2,'plotno', $plotno2,'houseno', $houseno,'month', $month2,'status', "closed",'year', $year2);			   
	
					if($readingtype=="all"){
						///	$readings= $this->usermodel->populatealldatanoarraysix('meterreading','category',$metername2,'plotno', $plotno2,'companyid', $companyid,'month', $month2,'status', "closed",'year', $year2);			   

					}else{
			///$readings= $this->usermodel->populatealldatanoarraysix('meterreading','category',$metername2,'plotno', $plotno2,'houseno', $roomno,'month', $month2,'status', "closed",'year', $year2);			   

					}						


if(is_array($readings)) {

   foreach($readings as $readingsrow)
   {
	
	  
	  
	  	$alldata[]=array(	
			'status'=>"open",		
			'tenantid'=>$readingsrow->tenantid,
						'chargeid'=>$readingsrow->chargeid,
			'roomchargeid'=>$readingsrow->roomchargeid,
'opening'=>$readingsrow->closing,
			'roomid'=>$readingsrow->roomid,
			'category'=>$readingsrow->category,
//
			'createdat'=>$createdat,
			'branchid'=>$readingsrow->branchid,
		  	'entrydate'=>$createdat,
			'type'=>$readingsrow->type,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'year'=>$nextyear,
		  	'month'=>$nextmonth,
				'houseno'=>$readingsrow->houseno,
			'plotno'=>$readingsrow->plotno,
				'meternumber'=>$readingsrow->meternumber,
				'rate'=>$readingsrow->rate,
				'charge'=>$readingsrow->charge,
		 
			
								);
	  
	  
	  
	  
	  
	  
	  
   }
   
$usr_result =$this->db->insert_batch('meterreading', $alldata); 



        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 meter reading..</div>');	
										
													//redirect('admin/viewmeterreadings');	
				redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month2.'&year='.$year2.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																

													
							}
							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 meter readings was not opened. May be because of already existing opening stock for the same date.Try again</div>');
								
												//redirect('admin/viewmeterreadings');	
				redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month2.'&year='.$year2.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																

							}
} else {
	echo"Not save";
   
}

	

						
						
						}else{
							
							
						 $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 updated the products   ..</div>');	
							//redirect($view);	
										redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month2.'&year='.$year2.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																
	return false;
							
							
						}


		   	   	 

							//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 updated the products   ..</div>');	
							//redirect($view);	
										redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month2.'&year='.$year2.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																

							}
							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> Products were not updated into the system.. Try again</div>');
										redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month2.'&year='.$year2.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																
	
							//redirect($view);																
							}
		
//}else{
	//echo "TRY AGAIN";
//}
	
  }
 }

  
  public function bulkclosingofreadings() {
	 
	$session_data = $this->session->userdata('logged_in');
//
   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  $branchid = $this->input->post("branchid");

	  $postedtime = $this->input->post("postedtime");
	  $startdate =$this->input->post("startdate");
	  $type =$this->input->post("type");
	  $plotno =$this->input->post("plotno");
	   $houseno =$this->input->post("houseno");
	  $year =$this->input->post("year");
	  $month =$this->input->post("month");
	  $metername =$this->input->post("metername");
	  
	   $rate =$this->input->post("rate");
	  $charge =$this->input->post("charge");
	  $tenatid =$this->input->post("tenatid");
	  	  $myid =$this->input->post("myid");
	  $closing =$this->input->post("closing");
	  $opening =$this->input->post("opening");
	  $roomid =$this->input->post("roomid");
	  $tenantid =$this->input->post("tenantid");

	  $method =$this->input->post("method");
	  $totalconsumed =$this->input->post("totalconsumed");



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

  $month2 =$this->input->post("month2");
	  $metername2 =$this->input->post("metername2");
	  $plotno2 =$this->input->post("plotno2");
	  $type2 =$this->input->post("type2");

	  $year2 =$this->input->post("year2");
	  $nextmonth =$this->input->post("nextmonth");
	  $nextyear =$this->input->post("nextyear");
	  $category =$this->input->post("category");

	  $readingtype =$this->input->post("readingtype");
	  $roomno =$this->input->post("roomno");







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

		  $createdat = Date('Y-m-d H:i:s') ;
$createdatmonth = Date('Y-m-d') ;
 //if (trim($this->input->post('btn_bulkclosereadings'))=="closereadingsNOW"){
				


	
			  	$this->form_validation->set_rules("roomno", "Roomno No", "trim|required");

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

		
		 $this->load->view('pmsdata/closemeterreading', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 





				
			// if ($this->input->post('btn_bulkclosereadings') =="closereadings")
					   //{			   
					
			$mytotalconsumed=0;
			if($method=="manual"){
				
							 $counter =count((array) $closing);

				 	 
					//$counter =count((array) $closing);
					
			   for($b=0; $b< $counter; $b++) {
				   
	   	 $mytotalconsumed=$mytotalconsumed+($closing[$b]-$opening[$b]);;	
		
			   }
				
				
				
				
			}
			
			
				 //$counter =count((array) $closing);
				
				 //for($b=0; $b< $counter; $b++) {
				   
	   		
		//echo$houseno[$b]."<br>";
			  // }
				
			
			
				 $myidsss =count((array) $opening);
			
			
			
			
			
			$count =count((array) $closing);
			//exit;
			 

   for($i=0; $i< $count; $i++) {
	   
	   
	   if($metername[$i]=="waterno"){
	$bill_name="Water";

	
}else if($metername[$i]=="electricityno"){
	$bill_name="Electricity";

	
}else if($metername[$i]=="bowholeno"){
	$bill_name="Bowhole";
	
	
	
}

	   
	   
	   
	   
	   
//
//var_dump($roomid[$i]);


//exit;

	   $usedqty=($closing[$i]-$opening[$i]);
	   
	   	if($method=="manual"){
			$scharge=(($usedqty/$mytotalconsumed)*$totalconsumed) ;
	   $totalamount=((($closing[$i]-$opening[$i])*$rate[$i])+$scharge);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing[$i],
'usedqty'=>$usedqty,
'charge'=>$scharge,
'totalamount'=>$totalamount,
             
			 );
		} else if($method=="automatic"){ 
  $totalamount=((($closing[$i]-$opening[$i])*$rate[$i])+$charge[$i]);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing[$i],
'usedqty'=>$usedqty,
'totalamount'=>$totalamount,
             
			 );


	} else if($method=="Tariff"){ 


		
		$GETWATER = $this->usermodel->populatealldatanoarraythreeAsc('waterrates','category', $category,'start <',$usedqty,'companyid',$companyid);


$totalamount=0;
if(is_array($GETWATER)){
	
foreach ($GETWATER as $row){
	$total=0;
	$start=$row->start;
	$end=$row->end;
	$rate=$row->amount;
	$flatrate=$row->flatrate;
	if($flatrate=="yes"){
			$total=$rate;

		
	}else{
		if($usedqty  >=  $end ){
		$total=(($end-$start)*$rate);
		}else{
			$total=(($usedqty-$start)*$rate);
		}
		
		
	}
	
	
$totalamount=$totalamount+$total;
}
								
					//echo"</br>". $totalamount;			
								
								}
$totalamount=$totalamount+$charge[$i];


 // $totalamount=((($closing[$i]-$opening[$i])*$rate[$i])+$charge[$i]);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing[$i],
'usedqty'=>$usedqty,
'totalamount'=>($totalamount),
             
			 );

//
//


		}			
  		$usr_result = $this->usermodel->updatedata($data,'meterreading','id',$myid[$i]);
   	   	 
		 $charges = $this->accomodationmodel->getplotchargesarray($plotno[$i],$roomid[$i],$type[$i]);
$chargeid= $charges[0]['id'];
      $chargedata = array(
	  

		'cost'=>$totalamount,
       'name'=>$myid[$i],
      
			 );
			 	
  		$this->usermodel->updatedata($chargedata,'roomcharges','id',$chargeid);
   	   	 
 

					if($totalamount > 0){
						
$month_name = date("F", mktime(0, 0, 0, $month[$i], 10));
  
		
$users = $this->usermodel->populateallarray('people','id', $tenantid[$i]);
$contact=$users[0]['phone'];

								
			  
				$taskmessage = "Dear ". $users[0]['firstname'] .",your ".$month_name." ".$bill_name." bill is ".$totalamount." current reading is ".$closing[$i]." , previous reading is  ".$opening[$i].",units consumed  ".$usedqty.", totaling to ". $totalamount ." for Hs No.". $houseno[$i] .".";


  
			
									$myview="admin/viewmeterreadings";

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

								


		
   }
		
			if ($usr_result ==TRUE) //active user record is present
							{
								
			
								
						if ($closetype =="closeopen"){
							
							
					if($readingtype=="all"){
							$readings= $this->usermodel->populatealldatanoarraysix('meterreading','category',$metername2,'plotno', $plotno2,'companyid', $companyid,'month', $month2,'status', "closed",'year', $year2);			   

					}else{
			$readings= $this->usermodel->populatealldatanoarraysix('meterreading','category',$metername2,'plotno', $plotno2,'houseno', $roomno,'month', $month2,'status', "closed",'year', $year2);			   

					}						
							
			

if(is_array($readings)) {

   foreach($readings as $readingsrow)
   {
	
	  
	  
	  	$alldata[]=array(	
			'status'=>"open",		
			'tenantid'=>$readingsrow->tenantid,
						'chargeid'=>$readingsrow->chargeid,
			'roomchargeid'=>$readingsrow->roomchargeid,
'opening'=>$readingsrow->closing,
			'roomid'=>$readingsrow->roomid,
			'category'=>$readingsrow->category,
//
			'createdat'=>$createdat,
			'branchid'=>$readingsrow->branchid,
		  	'entrydate'=>$createdat,
			'type'=>$readingsrow->type,
			'userid'=>$userid,
			'companyid'=>$companyid,
				'year'=>$nextyear,
		  	'month'=>$nextmonth,
				'houseno'=>$readingsrow->houseno,
			'plotno'=>$readingsrow->plotno,
				'meternumber'=>$readingsrow->meternumber,
				'rate'=>$readingsrow->rate,
				'charge'=>$readingsrow->charge,
		 
			
								);
	  
	  
	  
	  
	  
	  
	  
   }
   
$usr_result =$this->db->insert_batch('meterreading', $alldata); 



        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 meter reading..</div>');	
										
												redirect('admin/viewmeterreadings');	
				//redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month.'&year='.$year.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																

													
							}
							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 meter readings was not opened. May be because of already existing opening stock for the same date.Try again</div>');
								
											redirect('admin/viewmeterreadings');	
				//redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month.'&year='.$year.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																

							}
} else {
	echo"Not save";
   
}

	

						
						
						}



							//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 updated the products   ..</div>');	
						redirect($view);	
										//redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month.'&year='.$year.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																

							}
							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> Products were not updated into the system.. Try again</div>');
										//redirect('admin/bulkclosingofreadingsonebyone?method='.$method.'&totalconsumed='.$totalconsumed.'&month='.$month.'&year='.$year.'&type='.$type.'&plotno='.$plotno.'&metername='.$metername.'&nextmonth='.$nextmonth.'&nextyear='.$nextyear.'&closetype='.$closetype.'&readingtype='.$readingtype.'&category='.$category.'&roomno='.$roomno);																
	
							redirect($view);																
							}
		
//}else{
	//echo "TRY AGAIN";
//}
	
  }
 }

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

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

	  $postedtime = $this->input->post("postedtime");
	  $startdate =$this->input->post("startdate");
	  $type =$this->input->post("type");
	  $plotno =$this->input->post("plotno");
	   $houseno =$this->input->post("houseno");
	  $year =$this->input->post("year");
	  $month =$this->input->post("month");
	  $metername =$this->input->post("metername");
	  
	   $rate =$this->input->post("rate");
	  $charge =$this->input->post("charge");
	  $tenatid =$this->input->post("tenatid");
	  	  $myid =$this->input->post("myid");
	  $closing =$this->input->post("closing");
	  $opening =$this->input->post("opening");
	  $roomid =$this->input->post("roomid");
	  $tenantid =$this->input->post("tenantid");

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

		  $createdat = Date('Y-m-d H:i:s') ;


 if ($this->input->post('btn_bulkclosereadings1') == "closereadings1")
					   {
			
			
			
			
			
			 $count =count((array) $myid);

   for($i=0; $i< $count; $i++) {
	   
	   
	   if($metername[$i]=="waterno"){
	$bill_name="Water";

	
}else if($metername[$i]=="electricityno"){
	$bill_name="Electricity";

	
}else if($metername[$i]=="bowholeno"){
	$bill_name="Bowhole";
	
	
	
}

	   
	   
	   
	   
	   
//
//var_dump($roomid[$i]);


//exit;

	   $usedqty=($closing[$i]-$opening[$i]);
	   $totalamount=((($closing[$i]-$opening[$i])*$rate[$i])+$charge[$i]);
       $data = array(
	  
'status'=>"closed",
'closing'=>$closing[$i],
'usedqty'=>$usedqty,
'totalamount'=>$totalamount,
             
			 );
			 	
  		$usr_result = $this->usermodel->updatedata($data,'meterreading','id',$myid[$i]);
   	   	 
		 $charges = $this->accomodationmodel->getplotchargesarray($plotno[$i],$roomid[$i],$type[$i]);
$chargeid= $charges[0]['id'];
      $chargedata = array(
	  

'cost'=>$totalamount,
             
			 );
			 	
  		$this->usermodel->updatedata($chargedata,'roomcharges','id',$chargeid);
   	   	 
 

					if($totalamount>0){
						
$month_name = date("F", mktime(0, 0, 0, $month[$i], 10));
  
		
						$users = $this->usermodel->populateallarray('people','id', $tenantid[$i]);
$contact=$users[0]['phone'];

								
			  
				$taskmessage = "Dear ". $users[0]['firstname'] .",your ".$month_name." ".$bill_name." bill is ".$totalamount." current reading is ".$closing[$i]." , previous reading is  ".$opening[$i].",units consumed  ".$usedqty.", totaling to ". $totalamount ." for Hs No.". $houseno[$i] .".";


  
			
									$myview="admin/viewmeterreadings";

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

								


		
   }
		
			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 updated the products   ..</div>');	
							redirect($view);																
							}
							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> Products were not updated into the system.. Try again</div>');
								
							redirect($view);																
							}
		
		
	}
  }
  
  
  
   public function addadvancepayment()
    {
		
$session_data = $this->session->userdata('logged_in');

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


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

		   	  $amount = $this->input->post("amount");
			  
		    		   	  $itemid = $this->input->post("itemid");
		    		   	  $view = $this->input->post("view");

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



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

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






		 
						










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

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

		
		 $this->load->view('userdata/viewalladvance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('addadvancepayment') == "advance")
					   {
						   
						   
						   
						   
						   
						   $myadvance = $this->usermodel->populateallarray('advance','id', $itemid);

	 $mybalance=$myadvance[0]['balance'];
	 $customer=$myadvance[0]['tenantid'];
 $invoice=$myadvance[0]['houseno'];

	
	
		 $myamount=$myadvance[0]['amount'];
		  $mypaid=$myadvance[0]['paid'];

		 			   $balance = $mybalance+$amount;
							$finalpaid = $myamount+$amount;
	
								
													

								
						    $productdata=array(		
						'balance'=>$balance,
						'amount'=>$finalpaid,
												'status'=>$status,

						
						);
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
			'description'=>"Deducted",

		  	'balance'=>$balance,
			
			'companyid' => $companyid,
				'amount' => $amount,
			'createdat'=>$dateposted,
							'advanceid'=>$itemid,

			
								);
							$usr_result = $this->usermodel->add($data,'advancepayment');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							 $this->usermodel->updatedata($productdata,'advance','id',$itemid);
								 
								 
								 
								 
								 	$people = $this->usermodel->populateallarray('people','id',$customer);
									$supplierbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
				

			
								$finalcustomerbalance=$supplierbalance+$amount;
	
			
				
				
				
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalance,
							'lastbalancedate'=>$dateposted,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			
								 
								 
								 
								 
								 
								 
								 		 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid);


								$creditdata=array( 'userid'=>$userid,'account'=>$baddebt,'credit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');		 
								 
								 
								 
								 
								 
								 
								 
								 
								 
						 $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 payment on existing one..</div>');	
							redirect($view);																
							}
							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>Payment   was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }


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

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


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

		   	  $amount = $this->input->post("amount");
			  
		    		   	  $itemid = $this->input->post("itemid");
		    		   	  $view = $this->input->post("view");

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

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

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

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

		
		 $this->load->view('userdata/viewalladvance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('updateadvance') == "advance")
					   {
						   
						   
						   
						//   
						   
						   $myadvance = $this->usermodel->populateallarray('advance','id', $itemid);

	 $mybalance=$myadvance[0]['amount']-$myadvance[0]['paid'];
	 $customer=$myadvance[0]['tenantid'];
 $invoice=$myadvance[0]['houseno'];
	
	
		 $myamount=$myadvance[0]['amount'];
		  $mypaid=$myadvance[0]['paid'];

		 			   $balance = $mybalance-$amount;
							$finalpaid = $mypaid+$amount;
	
								
								if ($balance<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> The balance ('.$balance.')can not be less zero(0). The balance can only be equal or more  then zero. Try again</div>');
								
							//redirect($view);
									//return false;
								}						

								
						    $productdata=array(		
						'balance'=>$balance,
						'paid'=>$finalpaid,
												'status'=>$status,

						
						);
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
			'description'=>"Deducted",

		  	'balance'=>$balance,
			
			'companyid' => $companyid,
				'amount' => $amount,
			'createdat'=>$dateposted,
							'advanceid'=>$itemid,

			
								);
							$usr_result = $this->usermodel->add($data,'advancepayment');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
							 $this->usermodel->updatedata($productdata,'advance','id',$itemid);
								 
								 
								 
								 
								 	$people = $this->usermodel->populateallarray('people','id',$customer);
									$supplierbalance=$people[0]["balance"];
									$peopleid=$people[0]["id"];
				

			
								$finalcustomerbalance=$supplierbalance-$amount;
	
			
				
				
				
						$customerbalance=array(		
			
				'balance'=>$finalcustomerbalance,
							'lastbalancedate'=>$dateposted,

								);
		 $this->usermodel->updatedata($customerbalance,'people','id',$peopleid);
				
			
								 
								 
								 
								 
								 		  
						 
						  
						  
										 
								 
								 $debitdata=array( 'userid'=>$userid,'account'=>$bankname,'debit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid);


$creditdata=array( 'userid'=>$userid,'account'=>$baddebt,'credit'=>$amount,'description'=>$description,'code'=>$invoice,'crateddate'=>$dateposted,'branch' => $branchid,'companyid'=> $companyid,'type'=> "payment",'supplier'=>$peopleid);


							$usr_result = $this->usermodel->add($creditdata,'debitcredit');
							$usr_result = $this->usermodel->add($debitdata,'debitcredit');		 
								 
								 
								 
								 
								 
								 
								 
								 
						 $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 payment deduction..</div>');	
							redirect($view);																
							}
							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>Payment deduction  was not added.. Try again</div>');
								
							redirect($view);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }






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

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

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

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

				
			  	$this->form_validation->set_rules("type", "Charge name", "trim|required");

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

		
		 $this->load->view('pmsdata/searchallhousebutton', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('savenewservices') == "services")
					   {
												$data=array(		
			'userid'=>$userid,
			
			//	'name'=>$name,
		//	'roomid'=>$roomid,
	//'chargeid'=>$chargeid,
		  	'transactioncode'=>$transactioncode,
							'paymentmode' =>$type,
	'category' =>"Service Only",
			'companyid' => $companyid,
				//'cost' => $cost,
			'createdat'=>$createdat,
						'checkoutdate'=>$createdat,
						
			  'mpesa' => "0.00",    
		     'cheque' => "0.00", 
		     'card' => "0.00",
			   'voucher' => "0.00", 
			   'credit' => "0.00", 
					   'points' => "0.00",
						'amount' => "0.00",		  
						'total' => "0.00",		  
		'paymentstatus'=>"Not Cleared",
						'discount' => "0.00",		  

			//'createdat' => $dateposted,

			
								);
							$usr_result = $this->usermodel->add($data,'bookroom');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('roommsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully started posting services ..</div>');	
							redirect('/user/mychangepayment?myid='.$transactioncode);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Services  was not added.. Try again</div>');
								
							redirect('/user/mychangepayment?myid='.$transactioncode);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }






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

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

		   	  $roomid = $this->input->post("roomid");
			   $name = $this->input->post("name");
		   	  $chargeid = $this->input->post("chargeid");

		   	  $cost = $this->input->post("cost");
			  
		    
					  		  $this->form_validation->set_rules("cost", "Cost price", "trim|required");

				
			  	$this->form_validation->set_rules("chargeid", "Charge name", "trim|required");

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

		
		 $this->load->view('pmsdata/editallhouse', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addroomcharges') == "charges")
					   {
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			'roomid'=>$roomid,
	'chargeid'=>$chargeid,
		  	'plotno'=>$plotno,
			
			'companyid' => $companyid,
				'cost' => $cost,
			'createdat'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'roomcharges');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('roommsg', '<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  charge..</div>');	
							redirect('admin/editroom?randomitemidentifier='.$roomid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not added.. Try again</div>');
								
							redirect('admin/editroom?randomitemidentifier='.$roomid);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 





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

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

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

		   	  $houseno = $this->input->post("houseno");
			    $beds = $this->input->post("beds");
		    
					  		  $this->form_validation->set_rules("roomid", "Room Id", "trim|required");

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

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

		
		 $this->load->view('pmsdata/editallhouse', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addbeds') == "beds")
					   {
						   
						   		 $confirmrooms = $this->usermodel->Gettatalbeds($roomid);

						   //$confirmlevel= $this->accomodationmodel->confirmsmsconfig($companyid);
			//$tplot=$confirmlevel[0]['plot'];
			
			
			if(($confirmrooms!="" )&& ($confirmrooms  >=  trim($beds))){
				
				//echo"You have reach a maximum of ".$tplot."plots which was assigned to you. Please contact robiseach ltd";
				
				$this->session->set_flashdata('roommsg','<div class="alert alert-danger text-center">Warning!! Bed / Section could not be added!. You have reached a maximum of '.$beds.' beds which was assigned to this house. Adjust the number to add more beds '.$tplot.'. Please try again. </div>');
							redirect('admin/editroom?randomitemidentifier='.$roomid);																
				 return false;
			}
						   
						   
												$data=array(		
			'userid'=>$userid,
			
				'name'=>$name,
			'roomid'=>$roomid,
	'description'=>$description,
		  	'plotno'=>$plotno,
			
			'companyid' => $companyid,
				'houseno' => $houseno,
			'createdat'=>$dateposted,
				
			
								);
							$usr_result = $this->usermodel->add($data,'beds');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('roommsg', '<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  bed..</div>');	
							redirect('admin/editroom?randomitemidentifier='.$roomid);																
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bed  was not added.. Try again</div>');
								
							redirect('admin/editroom?randomitemidentifier='.$roomid);																
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

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

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

		   	  $transactioncode = $this->input->post("transactioncode");
			   $view = $this->input->post("view");
			   
		   	  $itemid = $this->input->post("itemid");

			  
		    
			 $this->form_validation->set_rules("transactioncode", "transaction code", "trim|required");

				
			  	$this->form_validation->set_rules("invoice", "Receipt No", "trim|required");

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

		
		 $this->load->view('pmsdata/changepayment', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_mergesales') == "merge")
					   {
						   
						   


$mydebitcred= $this->usermodel->geteallsales_orderoriginal($invoice);


		$costofgoodsold="";		
	if(is_array($mydebitcred)){
	$insertdata = array();
	$insertinventorydata = array();

			   	$enabled="";


	$salesaccount="";

		   $totalamount="";

	$inventoryaccount="";
	   foreach($mydebitcred as $row)
	   {
		   $mystatus=$row->status;
		   if($mystatus !="returned"){
	   $transactionid=$row->id; $itemid=$row->code;$totalqty=$row->qty;$mybranch=$row->branch;$mytotal=$row->amount;
		  $producttype=$row->producttype;
		
		$sprice=$row->sprice;

			 $mybprice=$row->bprice;
			  $correctqty=$row->qty;
			  $finalbprice=($sprice*$correctqty);
			 $totalamount= (double)$totalamount+(double)$row->amount;

		$salesaccount=$row->salesaccount;
		  $costofgoodsold=$row->expenseaccount;
		   $inventoryaccount=$row->assetaccount;
	 if($salesaccount!=""){ $salesaccount=$row->salesaccount;}else{ $salesaccount=4000; }
	  if($costofgoodsold!=""){ $costofgoodsold=$row->expenseaccount;}else{ $costofgoodsold=5500; }
	 if($inventoryaccount!=""){ $inventoryaccount=$row->assetaccount;}else{ $inventoryaccount=1110; }

	   
	      $myid=trim($row->id);
				
				
				
						$assetaccount=$row->assetaccount;
		$salesaccount=$row->salesaccount;
		$expenseaccount=$row->expenseaccount;
			$producttype=$row->producttype;	
			$mode=$row->mode;	

		$code=$row->code;
		$myqty=$row->qty;
		$invoice=$row->invoice;
				$dateposted=$row->dateposted;
	 $ordersales=$row->ordersales;

	 $status=$row->status;
	 
	 
	 		$myinvoice=$row->myinvoice;

	 $branch=$row->branch;
	$salestype=$row->salestype;
	
	 $address=$row->address;
		$vattype=$row->vattype;
	$mytype=$row->type;
	 $myqty=$row->qty;

	$taxable=$row->taxable;
		$taxindicator=$row->taxindicator;
				$updatedby=$row->updatedby;

		 $uom=$row->uom;
		$bprice=$row->bprice;
	$taxable=$row->taxable;
	$amount=$row->amount;
	$tax=$row->tax;
	$discount=$row->discount;

	 $tax2=$row->tax2;
		$maincategory=$row->maincategory;
	$category=$row->category;
		$stockafter=$row->stockafter;
		 	$uomqty=$row->uomqty;
		 	$serial=$row->serial;

		 	$stockbefore=$row->stockbefore;



$sales_orderdata[]=array(	

	'salesaccount'=>$salesaccount,
				'assetaccount'=>$assetaccount,
				'start'=>$enabled,
			'mode'=>$mode,
				'expenseaccount'=>$expenseaccount,
				'producttype'=>$producttype,
				
			'userid'=>$userid,
				//'id'=>$myid,
				'code'=>$code,
								'uomqty'=>$uomqty,
			'myinvoice'=> $myinvoice,
			'transactioncode'=> $transactioncode,

			'qty'=> $myqty,
					  	'serial'=>$serial,

		  	'discount'=>$discount,
			'companyid'=>$companyid,
						'companyid'=>$companyid,
			'createdat'=>$createdat,
			'dateposted'=>$dateposted,
					 'branch'=>$branch, 
		  'type' => $mytype,    
		  		   'address' => $address, 
		  		   'vattype' => $vattype, 
		   'updatedby' => $updatedby, 

		   'salestype' => $salestype, 
		     'invoice' => $invoice,  
		    'sprice' => $sprice,
			'cost' => $sprice, 	
			'name' => $code, 	
			      'amount' => $amount, 
				  			      'taxable' => $taxable, 

				  			      'taxindicator' => $taxindicator, 

				  			   			      'uom' => $uom, 
				  			   			      'status' => $status, 
											  				  			   			      'stockbefore' => $stockbefore, 

				  			   			      'stockafter' => $stockafter, 

      'ordersales' => $ordersales, 
			   			      'bprice' => $bprice, 
						'tax' => $tax,
						'tax2' => $tax2,

				'maincategory' => $maincategory, 
							'category' => $category, 

			
			
								);
	   
	   //
		}
		}
		
		
		$usr_result =$this->db->insert_batch('dailycharges', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
							$this->usermodel->deletedata($invoice,"invoice","sales_order");
							 	// $this->usermodel->deletedata($invoice,"invoice","roomsales");


			$salessdata = array(
			'total' => 0,
			'cash'=>0,
				'cheque' =>0,
				'points' =>0,
				'card' =>0,
				'voucher' =>0,
				'amount' => 0,
				'mpesa' =>0,
				'credit' =>0,
				'balance' => 0,
			
			
			
		
		
			
			'paymentstatus'=>"merged",
				'updatedat'=>$createdat,
			'updatedby'=>$userid,
			
             );
		
		
		$this->usermodel->updatedata($salessdata,'sales','invoice',$invoice);
			













							 	// $this->usermodel->deletedata($invoice,"invoice","sales");
						$roomsalesdata = array(
			'total'=>0,
			'status'=>"merged",
				'updatedat'=>$createdat,
			'updatedby'=>$userid,
			
             );
		
		
		$this->usermodel->updatedata($roomsalesdata,'roomsales','invoice',$invoice);
			
			
			
			
			
			$debitcreditdata = array(
			'code'=>$transactioncode,

             );
		
		
		$this->usermodel->updatedata($debitcreditdata,'debitcredit','code',$invoice);

			
		}
		
		
		}
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						  
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
										$rooms= $this->usermodel->populateallarray('bookroom','transactioncode',$transactioncode);

		$previousbalance=$rooms[0]["total"];  			
					$totalbalance=	$previousbalance+$totalamount;	
		$updaterefund=array(		
		'paymentstatus'=>"Not Cleared",
		'updatedat'=>$dateposted,
		'total'=>$totalbalance,
			'credit'=>($rooms[0]["credit"]+$totalamount),
		'balance'=>"-".($rooms[0]["credit"]+$totalamount),
		
		);
		$this->usermodel->updatedata($updaterefund,'bookroom','transactioncode',$transactioncode);
					
					
					
								 
						 $this->session->set_flashdata('roommsg', '<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  charge..</div>');	
			redirect('user/mychangepayment?myid='.$transactioncode);
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not added.. Try again</div>');
								
			redirect('user/mychangepayment?myid='.$transactioncode);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

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

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

		 		 $plotno = $this->input->post("plotno");
		 		 $houseno = $this->input->post("houseno");
		 		 $transactioncode = $this->input->post("transactioncode");

		   	  $roomid = $this->input->post("roomid");
			   //$name = $this->input->post("name");
			   $customer = $this->input->post("customer");
		   	  $idno = $this->input->post("idno");
		   	  $phone = $this->input->post("phone");
		   	  $description = $this->input->post("description");


				
			  		  $this->form_validation->set_rules("customer", "Guest name", "trim|required");

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

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

				'customer'=>$customer,
		  	'plotno'=>$plotno,
				'idno'=>$idno,
					'phone'=>$phone,
									'chargeid'=>$myid,

						'houseno' => $houseno,
												'description' => $description,

						'invoice' => $transactioncode,
						'myinvoice' => $userid.time(),
	

						'transactioncode' => $transactioncode,
			'companyid' => $companyid,

			'createdat'=>$dateposted,
									'type'=>"service",

			
								);
							$usr_result = $this->usermodel->add($data,'dailycharges');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
						
							
						 $this->session->set_flashdata('roommsg', '<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  charge..</div>');	
								
	redirect('user/mychangepayment?myid='.$myid);							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not added.. Try again</div>');
								
	redirect('user/mychangepayment?myid='.$myid);							}
						   
						   
					   }
					   
					   
					   
		}
	}
	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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

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

		   	  $roomid = $this->input->post("roomid");
			   //$name = $this->input->post("name");
			   $myroomtype = $this->input->post("name");
		   	  $qty = $this->input->post("qty");
		   	  $pax = $this->input->post("pax");
		   	  $ttamount = $this->input->post("totalamount");
		   	  $description = $this->input->post("description");

		   	  $sellingprice = $this->input->post("cost");
			  		   	  $myid = $this->input->post("myid");

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

					  		  $this->form_validation->set_rules("cost", "Cost price", "trim|required");

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

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

		
		 $this->load->view('userdata/changepayment', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_addroomdailycharges') == "charges")
					   {
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						  
$getroomdetails = explode("==",$myroomtype);
		
$name = $getroomdetails[0];		
				   $code = $getroomdetails[0];	
	
		//echo$chargeid = $getroomdetails[1];	



//
  $myconfiguration = $this->usermodel->populateallarray('smsconfig','id',$companyid);
$salesmethod=$myconfiguration[0]["salesmethod"];
$display1=$myconfiguration[0]["display1"]; 

$display2=$myconfiguration[0]["display2"]; 

     $productname = $this->usermodel->geteproductlistbyid($code,$branchid);
				
						  if ($productname ==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 Service/ product code does not exist. Try again.</div>');
							 
			redirect('user/mychangepayment?myid='.$myid);

							     return false;
						   }else{
							   
		$buyingprice=$productname[0]['buyingprice']; 
        $oldsellingprice=trim($productname[0]['sellingprice']); 		   
		$taxtype=$productname[0]['taxtype'];  
		$productid=$productname[0]['id'];				   
		$uom=trim($productname[0]['uom']);				   
		$categoryid=trim($productname[0]['category']); 
		$maincategory = $this->usermodel->populateallarray('productcategory','id',$categoryid);
		$maincategoryid=trim($maincategory[0]['maincategory']); 
		 $available=trim($productname[0]['qty']); 
    $itemtype=trim($productname[0]['orderamount']); 
	 $inventorytype=trim($productname[0]['producttype']); 
       $tax_included=trim($productname[0]['tax_included']);
		$vattype=$productname[0]['vattype'];  





if( $inventorytype != "Service"){
   	 $myfinalqty=($available-$qty); 

	  if(( $inventorytype=="Inventory")  && ($itemtype !="production")&& ($itemtype !="subitem") && ($itemtype !="Sub-Single-item") && ( $available<$qty)){
		  						
  $this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Warning!</strong>The available quantity is less than what you want sell('.$qty.').  Try again.</div>');
						  
						 
			redirect('user/mychangepayment?myid='.$myid);

							     return false;




	  }
		 }



			 $latestqty=$qty*$pax;
						$finaltax = 0.00;
						$finaltax2 = 0.00;
						//$vattype = "";
	 						$taxable = "";
							
							if(	$display1=="yes"){
								
							
							 if(($tax_included=="")|| ($tax_included==0)){
							$finaltax=0; 
							$finaltax2=0;
							$vattype = $vattype;
	 						$taxable = 0.00;

							 }else{
				
									if($taxtype=="Exclusive"){
									
								$mytax=1+($tax_included/100); 
								$vatable=($sellingprice);	

								$getvatable=($sellingprice*$mytax);	
								$myfinaltax=(($getvatable-$sellingprice)*$latestqty);
							
								$sellingprice= $this->formatMoney($getvatable, true);

									}else{
								
								$mytax=1+($tax_included/100); 
								$vatable=($sellingprice/$mytax);
								$myfinaltax=(($sellingprice-$vatable)*$latestqty);

									}


			$houserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
//$roomid=$houserents[0]['id'];

$tax1rate=	$houserents[0]['vat'];	
$tax2rate=$houserents[0]['vat2'];
$tax_included=$houserents[0]['vat2'];						
								
								
								$finaltax= $this->formatMoney($myfinaltax, true);

$display2=$myconfiguration[0]["display2"]; 

	if($display2=="yes"){
//echo $tax_included

	$tax2rate=$myconfiguration[0]["tax2rate"]; 
	
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 $ttoltaxable=(($sellingprice*$latestqty)/ $mytax2);
	 
	 $finaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$taxable= $this->formatMoney($ttoltaxable, true);

	}else{
	 $finaltax2=0;
	$taxable= $this->formatMoney($vatable, true);


	}	
							 
	}
		}
						   }







						  
	//$rooms= $this->usermodel->populateallarray('total','transactioncode',$myid);

		//$transactioncode=$rooms[0]["transactioncode"];   
						   
						   			//	'pax'=>$pax,

												$data=array(



'code'=>$code,
			'vattype'=>$vattype,
			'tax2'=>$finaltax2,
			'taxable'=>$taxable,
			'tax' => $finaltax,

												
			'userid'=>$userid,
			'code'=>$name,
			'sprice' => $sellingprice,
							'uomqty' => $pax,
'branch'=>$branchid,
				'amount' => $ttamount,
				'name'=>$name,
				'qty'=>$qty,
				'chargeid'=>$myid,
		  	'plotno'=>$plotno,
						'houseno' => $houseno,
												'description' => $description,

						'invoice' => $transactioncode,
						'myinvoice' => $userid.time(),
	

						'transactioncode' => $transactioncode,
			'companyid' => $companyid,
				'cost' => $sellingprice,
							'dateposted'=>$dateposted,

			'createdat'=>$dateposted,
									'type'=>"service",

			
								);
							$usr_result = $this->usermodel->add($data,'dailycharges');
							
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
						$rooms= $this->usermodel->populateallarray('bookroom','transactioncode',$transactioncode);

		$previousbalance=$rooms[0]["total"];  			
		$totalbalance=	$previousbalance+$ttamount;	
					
					
					
					
		$updaterefund=array(		
		'paymentstatus'=>"Not Cleared",
		'updatedat'=>$dateposted,
		'total'=>$totalbalance,
		'credit'=>($rooms[0]["credit"]+$ttamount),
		'balance'=>"-".($rooms[0]["credit"]+$ttamount),
		);
		$this->usermodel->updatedata($updaterefund,'bookroom','transactioncode',$transactioncode);
							

if( $inventorytype != "Service"){
 $productlistdata=array(	

'qty'=>$myfinalqty,	 
						);
							
					 $this->usermodel->updatedatabytwo($productlistdata,'productlist','code',$code,'branch',$branchid);

}




							
						 $this->session->set_flashdata('roommsg', '<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  charge..</div>');	
								
				 	 redirect('user/mychangepayment?myid='.$myid.'&randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
							
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not added.. Try again</div>');
								
				 	 redirect('user/mychangepayment?myid='.$myid.'&randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }

 
public function uploadhousedata()
        {

          if(isset($_POST["btn_uploadhouse"]))
            { $createdat = Date('Y-m-d H:i:s') ;
 $plotno = $this->input->post("plotno");

		
								$houseno = $this->input->post("houseno");
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
                            $data = array(
                            	 'houseno' => $emapData[0],
                               'type' => $emapData[1],
							    'description' => $emapData[2],

								 'plotno' => $emapData[3],
								  'cost' => $emapData[4],
								'status' => $emapData[5],
								'createdat' => $createdat,
                       	
                                );
                    
                        $usr_result = $this->accomodationmodel->uploadhouse($data);
                     }
                    fclose($file);
                    $plotno = $this->input->post("plotno");
                   	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 uploaded Houses !</div>');
								
						redirect('admin/viewplot?randomitemidentifier='.$plotno,$data);
								 
								 
								 
								 
								 
								 
						
							}
							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 House uploaded. Try again</div>');
								
						
						redirect('admin/viewplot?randomitemidentifier='.$plotno,$data);
								 
							}

                  }
            }
        }











      

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

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

     	$data['bookingid'] = $bookingid;

	$data['tenant'] = $this->accomodationmodel->populatealltenant();
   		$data['booking'] = $this->accomodationmodel->getbookingbyid($bookingid);
	
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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



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

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

     	$data['bookingid'] = $bookingid;

	$data['tenant'] = $this->accomodationmodel->populatealltenant();
   		$data['booking'] = $this->accomodationmodel->getbookingbyid($bookingid);
	
	
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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




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

    
      show_error('No identifier provided', 500);
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
     $data['advert'] = $this->postmodel->populateadvert();
        		$data['category'] = $this->postmodel->populatelostfoundcategory();
   	$data['postid'] = $itemid;
	
	$data['post'] = $this->postmodel->getlostfoundbyid($itemid);

    	$this->load->view("template/headerpagemin", $data);

		
		 $this->load->view('admin/viewlostfound', $data);
		$this->load->view("template/footerpage");
		
	}
  }
	
function addrentbooking()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
		  $createdat = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		
		
			$houseno = $this->input->post("houseno");
		$plotno = $this->input->post("plotno");
		$status = $this->input->post("status");
		 $entrydate = $this->input->post("entrydate");
		     
		  
          				$transactioncode = $userid.time();

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

			$overpayment = $this->input->post("overpayment");	
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('status', 'status  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allbookingrental',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_booking') == "booking")
		 {
			
			$data = array(
				'houseno' => $houseno,
				'plotno' => $plotno,

		 				'transactioncode' =>$transactioncode,
				'tenantid' => $tenantid,
				'entrydate' => $entrydate,
								'overpayment' => $overpayment,
						'totalamount' => $totalamount,
				'createdat' => $createdat,
				'status' => $status,
								'deposite' => $deposite,

				'category' =>"rental",

				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
			);
			
			if($action=="insert"){
				
			if (($this->accomodationmodel->checkrentvacancy($plotno,$houseno))==FALSE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error!Room cant be Allocated! . The room is still occupied.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$id);
			}
			if (($this->accomodationmodel->checkbookingvacancy($plotno,$houseno))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room cant be Allocated! . The previous tenant is still active. Please deactivate the previous tenant first.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$id);
					 return false;
			}
			// insert form data into database
			if ($this->accomodationmodel->insertBooking($data))
			{
				$this->accomodationmodel->occupyHouse($plotno,$houseno,"occpied");
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$id);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not added. Please try again </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$id);
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				
				
					$mystatus="";
					if($status=="inactive"){
							$mystatus="vacant";
					}else{
							$mystatus="occupied";
					}
					$mydata = array(
				
				'status' => $mystatus,
						);
			
					
					$this->accomodationmodel->upadeteHousedata($mydata,$houseno,$plotno);
				
				
				
				
				
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is updated Successfully ! !!!</div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$id);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not updated. Please try again </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$id);
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
function addrefund()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
		  $createdat = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		
		
			$houseno = $this->input->post("houseno");
		$plotno = $this->input->post("plotno");
		$amount = $this->input->post("amount");
		 $entrydate = $this->input->post("entrydate");
		     		 $deposite = $this->input->post("deposite");

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

 			    $tenantid = $this->input->post("tenantid");
				    			    $bookingid = $this->input->post("bookingid");

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

			$receiptno = $this->input->post("receiptno");	
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/refundmoney',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_addrefund') == "refund")
		 {
			
			$data = array(
				'houseno' => $houseno,
				'plotno' => $plotno,

		 				'transactioncode' =>$transactioncode,
				'tenantid' => $tenantid,
				'createdat' => $entrydate,
								'amount' => $amount,
	'mode' => $mode,
				'createdat' => $createdat,
				'receiptno' => $receiptno,

				

				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
								'bookingid' => $bookingid,

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


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								
								   $finaldeposite =  $deposite-$amount;
									$updaterefund=array(		
		
			
				
			
		  	'deposite'=>$finaldeposite,
			
			 	
			
			'updatedat'=>$entrydate,
				
			
								);
										
								
								
								
								
								
								
								
		$this->usermodel->updatedata($updaterefund,'bookroom','id',$bookingid);

								
								
								
								
								
								 
						 $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 done refund..</div>');	
								 redirect("admin/allocate?randomitemidentifier=$houseno&randomitemidentifier1=$plotno&roomidentifier=4&category=rental");
							}
							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 refund  was not successful.. Try again</div>');
								
								 redirect("admin/allocate?randomitemidentifier=$houseno&randomitemidentifier1=$plotno&roomidentifier=4&category=rental");
							}
				
				
			
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
  public function allpaymentsection() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
     $methodid = $_GET['randomitemidentifier'];
    
   	$data['methodid'] = $methodid;
	
	$data['paymentsection'] = $this->accomodationmodel->getpaymentsectionbyid($methodid);
 		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");


	$this->load->view('pmsdata/managepaymentsection',$data);
		$this->load->view("template/footerpage");
		
	}
  }
  public function viewsearchposts()
	{ 

		 $this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		 $data['posts'] = $this->postmodel->populateallposts();

				$this->load->view('pmsdata/allposts',$data);
		$this->load->view("template/footerpage");
	}
	  public function viewcontact()
	{ 

		 $this->load->view("template/headerpagemin");
		
		$this->load->view("template/tableheader");
		 $data['contact'] = $this->accomodationmodel->populateallcontact();

				$this->load->view('pmsdata/allcontact',$data);
		$this->load->view("template/footerpage");
	}
	public function index()
	{ 
		$this->load->view("template/headerpagemin");
		$this->load->view('adminloginpage');
		$this->load->view("template/footerpage");
	}
	public function viewallandlord()
	{ 
	 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
				
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		//$data['landlord'] = $this->accomodationmodel->populatealllandlord();
					$data['landlord'] = $this->usermodel->populateall('landlord', 'companyid',$companyid);


				$this->load->view('pmsdata/allandlord',$data);
		$this->load->view("template/footerpage");
	}
		public function landlord()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewlandlord');
		$this->load->view("template/footerpage");
	}
    public function profile() {
	$session_data = $this->session->userdata('adminlogged_in');

     $data['surname'] = $session_data['surname'];
      $data['surname'] = $session_data['surname'];
       $data['email'] = $session_data['email'];
         $data['status'] = $session_data['status'];
 	$data['id'] = $session_data['id'];

	$id= $data['id'] ;
	 $data['admin'] = $this->accomodationmodel->populateadmindata($id);
	 $this->load->view("template/adminheaderpagemin");

		$this->load->view("template/adminnave");
		 $this->load->view('adminpage',$data);
		$this->load->view("template/footerpage");
     
    }
  public function viewallagents()
	{ 
	 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 					$data['agent'] = $this->usermodel->populateall('agent', 'companyid',$companyid);

				
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		//$data['agent'] = $this->accomodationmodel->populateallagent();

				$this->load->view('pmsdata/allagents',$data);
		$this->load->view("template/footerpage");
	}
		 public function agents()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/viewagents');
		$this->load->view("template/footerpage");
	}
	
	
	
	public function roomcustomers()
	{ 
	  	 $session_data = $this->session->userdata('logged_in');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 //$usertype = $data['branchid'];	
	//  $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];	
	 					//$data['tenant'] = $this->usermodel->populateall('people', 'companyid',$companyid);
						
				$data['tenant']= $this->usermodel->populatealldaTENANTS('people','category', 'accommodation','id >', 0,'companyid', $companyid);			   

		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		//$data['tenant'] = $this->accomodationmodel->populatealltenant();


				$this->load->view('pmsdata/alltenantsrooms',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	public function viewalltenant()
	{ 
	  	 $session_data = $this->session->userdata('logged_in');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 //$usertype = $data['branchid'];	
	//  $data['branchid'] = $session_data['branchid'];
	// $branchid = $data['branchid'];	
	 					//$data['tenant'] = $this->usermodel->populateall('people', 'companyid',$companyid);
						
				$data['tenant']= $this->usermodel->populatealldaTENANTS('people','category', 'accommodation','id >', 0,'companyid', $companyid);			   

		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		//$data['tenant'] = $this->accomodationmodel->populatealltenant();


				$this->load->view('pmsdata/alltenants',$data);
		$this->load->view("template/footerpage");
	}
		 public function tenant()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

		$this->load->view('pmsdata/viewtenants');
		$this->load->view("template/footerpage");
	}
	
		public function viewallplots2()
	{ $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
	
	 $session_data = $this->session->userdata('logged_in');
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 $data['plots'] = $this->usermodel->populateall('plot', 'companyid',$companyid);
$data['landlord'] = $this->usermodel->populateall('landlord', 'companyid',$companyid);

	$data['agent'] = $this->usermodel->populateall('agent', 'companyid',$companyid);

	
	
	
	
	
	
		
		//$data['plots'] = $this->accomodationmodel->populateallplots();
	//$data['landlord'] = $this->accomodationmodel->populatealllandlord();
	//$data['agent'] = $this->accomodationmodel->populateallagent();
				$this->load->view('pmsdata/allplots',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	public function viewallplots()
	{ 
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
				 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
				
				
				$config['base_url'] = base_url('Accomodationhome/viewallplots');
		$config['total_rows'] = $this->usermodel->count_allwheredata('plot','companyid',$companyid,'branchid',$branchid);
		$config['per_page'] = '50';
		$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->populatecategory($companyid);
			// $data['plots'] = $this->usermodel->populateall('plot', 'companyid',$companyid);
$data['landlord'] = $this->usermodel->populateall('landlord', 'companyid',$companyid);

	$data['agent'] = $this->usermodel->populateall('agent', 'companyid',$companyid);

		
	
        $data["plots"] = $this->usermodel->displayalldata($config["per_page"], $page,'plot','companyid',$companyid,'branchid',$branchid);

			
		
		
		
		 $this->load->view("template/headerpagemin");
		
		// $this->load->view("template/tableheader");
	
		$data["total_rows"] =$config['total_rows'];
		$data["links"] = $this->pagination->create_links();
			$this->load->view('pmsdata/allplots',$data);
				
		$this->load->view("template/footerpage");
	
	}
	
	
	
	
	
	
	
			public function searchallplots()
	{
			 $session_data = $this->session->userdata('logged_in');

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

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
		$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() . 'Systemusers/searchallplots';
		$query = $this->usermodel->searchallplots($searchterm,$companyid,$limit);

		$config['total_rows'] = $query['records'];
		$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>";
		$choice = $config['total_rows']/$config['per_page'];
		//$config['num_links'] = round($choice);		
		$this->pagination->initialize($config);

			

		$data['links'] = $this->pagination->create_links();
		$data['searchterm'] = $searchterm;
		 $this->load->view("template/headerpagemin");
			$data['plots'] = $query['data'];

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

public function uploadhouse()
        {

          if(isset($_POST["btn_uploadhouse"]))
            { $createdat = Date('Y-m-d H:i:s') ;

	$category = $this->input->post("category");
			$data = array();
								$houseno = $this->input->post("houseno");
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						  $plotno = $emapData[0];
                            $data[] = array(
							
							'plotno' => $emapData[0],
                            	 'houseno' => $emapData[1],
                               'type' => $emapData[2],
							    
								'status' => "vacant",
								  'cost' => $emapData[3],
								  	'floor' => $emapData[7],

								      // 'totalamount' => $emapData[4],
							    
								//'deposite' => $emapData[5],
								
								// 'overpayment' => $emapData[6],
								  
								  
									'category' => $category,
								'createdat' => $createdat,
                       	
                                );

                       // $usr_result = $this->adminusermodel->uploadhouse($data);
                     }
					  $usr_result =$this->db->insert_batch('house', $data); 

					 
                    fclose($file);
                    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 uploaded Houseses !</div>');
								
				redirect('admin/viewallplots');
								 
								 
								 
								 
								 
								 
						
							}
							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 House was uploaded. Try again</div>');
								
						
					redirect('admin/viewallplots');
								 
							}

                  }
            }
        }
		
			public function uploadhousesales________()
        {
												$checksales= $this->usermodel->populateallarraysales('bookroom','id >',0);

if(is_array($checksales)){

   foreach($checksales as $row)
   {
	   
//$codes1 = explode(' ',$row->entrydate);
//$tenantid = (trim($codes1[0]));
//$codes2 = explode(' ',$row->checkoutdate);
//$tenantid2 = (trim($codes2[0]));
	   
	   //$old_date1 = explode('/', $row->entrydate); 
	      //$old_date2 = explode('/', $row->checkoutdate);
//echo$new_data1 = $old_date1[2].'-'.$old_date1[1].'-'.$old_date1[0];
//echo "<br>";
	//echo$new_data2 = $old_date2[2].'-'.$old_date2[1].'-'.$old_date2[0]." ".$old_date2[0];
   

 
 // $tenantid = htmlspecialchars(trim($codes[0]));
	   
	     $entrydate = date("Y-m-d H:i:s", strtotime($row->entrydate.":00"));
	
	    $checkoutdate = date("Y-m-d H:i:s", strtotime($row->checkoutdate.":00"));
	   
	   
   $transactionid=$row->id; 
$updateArray[] =array(	
	'id'=>$transactionid,													
'entrydate'=>$entrydate,
'checkoutdate'=>$checkoutdate,

);	

			
	}
$RESULT =	$this->db->update_batch('bookroom',$updateArray, 'id');
							
		
			

		}
		
		
		}
		
		
		
		
		
		
		
		
		
		public function uploaddoorlocks()
        {

        if(isset($_POST["btn_uploaddoorlockdata"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		  $data['branchid'] = $session_data['branchid'];
		 	$branchid= $data['branchid'];
	 
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
 		     $createdat = $this->input->post("createdat");

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

  $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';
            $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;
				$data = array();

                foreach ($allDataInSheet as $emapData) {
                  if($flag){
                    $flag =false;
                    continue;
                  }
					
				
					
					
						  $new_date=	date('Y-m-d');
						  
						  
						  	    $data[] = array(
                              

								    'createdat' => $createdat,	

					 
									'description' => $description,
									'name' => $name,
									'branchid' => $branchid,	 

									'userid' => $userid,
 									'companyid' => $companyid,
									
									
									
										'guest' => $emapData['A'],
										'roomtype' => $emapData['B'],	
										'roomno' => $emapData['C'],	
										'guesttype' => $emapData['D'],	
										'chargetype' => $emapData['E'],	
										'issuedqty' => $emapData['F'],	
										'recycledcardqty' => $emapData['G'],	
										'state' => $emapData['H'],	
										'checkintime' => $emapData['I'],	
										'departuretime' => $emapData['J'],	
										'vouchertype' => $emapData['K'],	
										'voucherno' => $emapData['L'],
										'checkouttime' => $emapData['N'],	
										'area1' => $emapData['M'],	
										'area2' => $emapData['O'],	
										'operator' => $emapData['P'],	
										'remark' => $emapData['Q'],	
										'familyroom' => $emapData['R'], 
									
									
									
									
									
 									
 									
                                );
						  
						  
						  
	
								
								
				
		   $i++;
				}
	
	

	
                    	               
              
			  $usr_result =$this->db->insert_batch('doorlock', $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 uploaded door lock/card data !</div>');
								
								 redirect($view);
							}
							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>  Door lock/card data were not uploaded.Try again</div>');
						 redirect($view);
							}

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

	public function uploadhousesales()
        {

          if(isset($_POST["btn_uploadsales"]))
            { $createdat = Date('Y-m-d H:i:s') ;


	
            	set_time_limit(1000000000000);
                $filename=$_FILES["file"]["tmp_name"];
            //  var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000000, ",")) !== FALSE)
                     {
						  
						  
						  
						  
						  		  
			 $updateArray[]=array(	
						  
                       
							
							'id' => $emapData[0],
                            	 'houseno' => $emapData[1],
                              'plotno' => $emapData[2],
							    'idno' => $emapData[3],
								'tenantid' => $emapData[4],
								'entrydate' => $emapData[5],
								'description' => $emapData[6],
							'checkoutdate' => $emapData[7],
                            	 'status' => $emapData[8],
                              'userid' => $emapData[9],
							    'entrydate' => $emapData[10],
								//'' => $emapData[11],
								'companyid' => $emapData[12],
								'amount' => $emapData[13],
							'paymentstatus' => $emapData[14],
                            	 'paymentmode' => $emapData[15],
                              'paymentcode' => $emapData[16],
							    'totalamount' => $emapData[17],
								'overpayment' => $emapData[18],
								'discount' => $emapData[19],
								'transactioncode' => $emapData[20],
                       			'total' => $emapData[21],
								'branchid' => $emapData[22],
								//'cash' => $emapData[23],
							'balance' => $emapData[24],
                            	 'mpesa' => $emapData[25],
                              'credit' => $emapData[26],
							    'voucher' => $emapData[27],
								'cheque' => $emapData[28],
								'points' => $emapData[29],
								
								'number' => $emapData[30],
								
								
                       			'deposite' => $emapData[31],
								'chargeid' => $emapData[32],
								'category' => $emapData[33],
							'createdat' => $emapData[34],
                            	 'updatedat' => $emapData[35],
                              'vatable' => $emapData[36],
							    'booings' => $emapData[37],
								'currency' => $emapData[38],
								'tax1' => $emapData[39],
								'tax2' => $emapData[40],
								
								
								
                                );
				
                      //  $usr_result = $this->adminusermodel->uploadhouse($data);
                    


					}
					 
					 
		$usr_result =$this->db->insert_batch('bookroom', $updateArray); 

					 
					 
			
					
					
					
        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 uploaded Houseses !</div>');
								
				redirect('admin/viewallplots');
								 
								 
								 
								 
								 
								 
						
							}
							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 House was uploaded. Try again</div>');
								
						
					redirect('admin/viewallplots');
								 
							}

                  }
            }
        }





	
	public function uploadhousebalances()
        {

          if(isset($_POST["btn_uploadbalances"]))
            { $createdat = Date('Y-m-d H:i:s') ;


	
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
              var_dump($_FILES["file"]["size"]);
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						  $plotno = $emapData[0];
						  	  $houseno = $emapData[1];
						 	$booking  = $this->usermodel->populatealldatanorraythree('bookroom','plotno', $plotno,'houseno', $houseno,'status','active');


							if($booking!=false){
									$itemid=$booking[0]['id']; 
						  
						  
						  
						  		  
			 $updateArray[]=array(	
						  
                       
								'id' => $itemid,
							'plotno' => $emapData[0],
                            	 'houseno' => $emapData[1],
                              'totalamount' => $emapData[2],
							    
								'deposite' => $emapData[3],
								
							
								'overpayment' => $emapData[4],
                       	
                                );
				}
                      //  $usr_result = $this->adminusermodel->uploadhouse($data);
                    


					}
					 
					 
					 			 	 $RESULT =	$this->db->update_batch('bookroom',$updateArray, 'id');

					 
					 
					 
                    fclose($file);
					
					
					
        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 uploaded Houseses !</div>');
								
				redirect('admin/viewallplots');
								 
								 
								 
								 
								 
								 
						
							}
							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 House was uploaded. Try again</div>');
								
						
					redirect('admin/viewallplots');
								 
							}

                  }
            }
        }



	
	
		public function uploadtenants()
        {

          if(isset($_POST["btn_uploadmembers"]))
            { 
	$session_data = $this->session->userdata('logged_in');
		 	 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		
		$data['id'] = $session_data['id'];
        
 $userid = $data['id'];
		  $createdat = Date('Y-m-d H:i:s') ;  
	
			
		
            	set_time_limit(0);
                $filename=$_FILES["file"]["tmp_name"];
          
                if($_FILES["file"]["size"] > 0)
                  {
                    $file = fopen($filename, "r");
                     while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
                     {
						 
						
									$new_date=	date('Y-m-d');
						     $transactionid = $userid.time()+1;
						 $confirm= $this->usermodel->populateallarray('people','idno',$emapData[4]);
if( $confirm==false){
					
						 
                            $data = array(
                            	
								    'firstname' => $emapData[2],
								 'lastname' => $emapData[3],
								  'idno' => $emapData[4],
								'phone' => $emapData[5],
									'category' => "accommodation",
                 
							'createdate' => $createdat,
							
								'companyid' => $companyid,
								
										'userid' => $userid,
									'transactionid' => $transactionid,

						
						
						
                                );
                           
						 	if($usr_result=$this->accomodationmodel->uploadalltenants2($data)){
								
								
									

                    	//$usr_result = $this->usermodel->uploadallproduct($data);
  
						
							$idno= $emapData[4];
							$plotno = $emapData[0];
				$houseno = $emapData[1];
				
				$status = "active";
				$entrydate = $createdat;
				$finaltransactionid=$this->accomodationmodel->getmytenantid($idno);
				$finaltransactionidrow;
				if(is_array($finaltransactionid)) {

   foreach($finaltransactionid as $finaltransactionidrow){

  $finaltransactionidrow= $finaltransactionidrow->id;
}} else {
     
}
			
				$data1 = array(
				'houseno' => $houseno,
				'plotno' => $plotno,
				'idno' => $emapData[4],
				'tenantid' => $finaltransactionidrow,
				'entrydate' => $entrydate,
				'createdat' => $createdat,
				'status' => $status,
				'companyid' => $companyid,
								
			'userid' => $userid,
				
			);
			
				
			
			 
			
			// insert form data into database
			if ($this->accomodationmodel->insertBooking($data1))
			{
				$this->accomodationmodel->occupyHouse($plotno,$houseno,"occpied");
			
			}
						
		
                     }
	}
        

   }

   fclose($file);
                
                   	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 new members !</div>');
								
						redirect('admin/viewalltenant');
								 
							}
							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 Member uploaded. Try again</div>');
								
						
						redirect('admin/viewalltenant');
							}

               
				  }
            }
        }
		
		
		
		
		
		
		
	
		 public function plots()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");

				$this->load->view('pmsdata/viewplots');
		$this->load->view("template/footerpage");
	}
	
	
	
	
		public function viewallhouses()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$data['house'] = $this->accomodationmodel->populateallHouses();

				$this->load->view('pmsdata/viewallhouses',$data);
		$this->load->view("template/footerpage");
	}
		 public function houses()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/viewhouses');
		$this->load->view("template/footerpage");
	}
	
			public function viewallcountries()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$data['country'] = $this->accomodationmodel->populateallallacountries();
	

				$this->load->view('pmsdata/allacountries',$data);
		$this->load->view("template/footerpage");
	}
		public function viewallpaymentmethod()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$data['paymentmethod'] = $this->accomodationmodel->populateallpaymentmethod();
	

				$this->load->view('pmsdata/allapaymentmethod',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
		public function viewallsmscategory()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$data['smscategory'] = $this->accomodationmodel->populatesmscategory();
	

				$this->load->view('pmsdata/smscategory',$data);
		$this->load->view("template/footerpage");
	}
	
	
		
	
		public function viewallsms()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$data['sms'] = $this->accomodationmodel->populatesms();
	

				$this->load->view('pmsdata/viewallsms',$data);
		$this->load->view("template/footerpage");
	}
	
	
	
	
	
	
	
	
		 public function paymentmethod()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/viewpaymentmethod');
		$this->load->view("template/footerpage");
	}
	
		public function viewallpaymentsection()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
	$data['paymentsection'] = $this->accomodationmodel->populateallpaymentsection();


				$this->load->view('pmsdata/allapaymentsection',$data);
		$this->load->view("template/footerpage");
	}
	
	
		public function viewallpaymentcharge()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
	$data['paymentcharge'] = $this->accomodationmodel->populateallpaymentcharges();


				$this->load->view('pmsdata/allapaymentcharges',$data);
		$this->load->view("template/footerpage");
	}
	
		public function viewalldiscounts()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		  	$data['discount'] =$this->usermodel->populateall('discount','id >',0);


				$this->load->view('pmsdata/viewalldiscounts',$data);
		$this->load->view("template/footerpage");
	}
	
		public function viewalldoorlocks()
	{ 
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		  	$data['doorlock'] =$this->usermodel->populateall('doorlock','id >',0);


				$this->load->view('pmsdata/viewalldoorlocks',$data);
		$this->load->view("template/footerpage");
	}
	
		 public function paymentsection()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/viewpaymentsection');
		$this->load->view("template/footerpage");
	}
	
	 
	 		 public function searchhouse()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");

				$this->load->view('pmsdata/searchhouses');
		$this->load->view("template/footerpage");
	}
	
	  		 public function searchhousebyno()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/searchhousebyno');
		$this->load->view("template/footerpage");
	}
	 
	 	 		 public function searchstatement()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/searchstatement');
		$this->load->view("template/footerpage");
	}
	
	  	 		 public function searchpayment()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
				$this->load->view('pmsdata/searchpayment');
		$this->load->view("template/footerpage");
	}
	 
	 
	 	 		 public function searchbalance()
	{ 
		 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		 $data['tenant'] = false;
		 				//$data['tenant'] = $this->accomodationmodel->populatealltenant();

					//$data['tenant'] = $this->accomodationmodel->populatealltenant();

				$this->load->view('pmsdata/searchbalance',$data);
		$this->load->view("template/footerpage");
	}
	
	 
	 	 		 public function confirmreading()
	{ 
	
	
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
			$companyid = $data['companyid'];
	
	
	
	
	
	
	
	$amount="500";
		$category="residential";

				
		$GETWATER = $this->usermodel->populatealldatanoarraythreeAsc('waterrates','category', $category,'start <',$amount,'companyid',$companyid);


$totalamount=0;
if(is_array($GETWATER)){
	
foreach ($GETWATER as $row){
	$total=0;
	$start=$row->start;
	$end=$row->end;
	$rate=$row->amount;
	$flatrate=$row->flatrate;
	if($flatrate=="yes"){
			$total=$rate;

		
	}else{
		if($amount  >=  $end ){
		$total=(($end-$start)*$rate);
		}else{
			$total=(($amount-$start)*$rate);
		}
		
		
	}
		echo "<br>". $id=$row->id;
//echo "<br>".$total;
	
$totalamount=$totalamount+$total;


			
						}
								
					echo"</br>". $totalamount;			
								
								}else{
									echo "HAIKO";
									
								}
	 
	 
	}
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
  function addplotcharge()
    {
		
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $createdat = Date('Y-m-d H:i:s') ;
			$plotno = $this->input->post("plotno");
			$action = $this->input->post("action");
		   	  $cost = $this->input->post("cost");
		  	 $chargeid = $this->input->post("chargeid");
           $status = $this->input->post("status");
 			   
			$description = $this->input->post("description");
							$bulkactivation = $this->input->post("bulkactivation");
		
          //set validations
		  	
		$this->form_validation->set_rules('plotno', 'Plot Number', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('cost', 'Charge cost', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('status', 'status', 'trim|required|xss_clean');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allcharges',$data);
		$this->load->view("template/footerpage");
		//redirect('admin/plots');
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_charge') == "charge")
		 {
						
			
 			   
			
			$data = array(
				'plotno' => $plotno,
				'cost' => $cost,
				'chargeid' => $chargeid,
				'status' => $status,
				'description' => $description,
				'createdat' => $createdat,
				'companyid' => $companyid,
				
			);
				if($action=="insert"){
			if (($this->accomodationmodel->PlotCharges($plotno,$chargeid))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error!  This plot charge is not added . The plot has already been added.. Try other charges. </div>');
				 	 redirect('admin/plotcharges?randomitemidentifier='.$plotno);
			}
			if ($this->accomodationmodel->insertPlotCharges($data))
			{
				
				if($bulkactivation=="yes"){
					
					
	 $myrawdata = $this->usermodel->populatealldatanoarray('house','plotno', $plotno,'id >', 0);

	
	if(is_array($myrawdata)){

	
	   foreach($myrawdata as $row)
	   {
		   
		 
						 $roomid=$row->id;

		
		
$sales_orderdata[]=array(	
'plotno' => $plotno,
				'cost' => $cost,
				'chargeid' => $chargeid,
				'roomid' => $roomid,
				'userid' => $userid,
				'status' => $status,
				'createdat' => $createdat,
				'companyid' => $companyid,

			
			
								);
	   
	   //
		}
		
		
			
		$usr_result =$this->db->insert_batch('roomcharges', $sales_orderdata); 


		        if($this->db->affected_rows() > 0)
	{
		
		
		
	
			
		}
		
		
	}
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
				}
				
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">The charge  is added Successfully to the plot ! !!!</div>');
					 redirect('admin/plotcharges?randomitemidentifier='.$plotno);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Plot charge not charged. Please try again later!!!  is done</div>');
				 redirect('admin/plotcharges?randomitemidentifier='.$plotno);
			}
			
				}else 	if($action=="update"){
					
						$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadetePlotcharge($data,$id))
			{
				
				$allhouses = $this->input->post("allhouses");
									  $updatedat = Date('Y-m-d H:i:s') ;

				if($allhouses=="yes"){
						$newprices=array(		
						
										'cost'=>$cost,
										'updatedat'=>$updatedat,
										'userid'=>$userid,
										);
					
					
									 $this->usermodel->updatedatabytwo($newprices,'roomcharges','plotno',$plotno,'chargeid',$chargeid);

					
				}
				
				
				
				
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Plot charge is updated Successfully ! !!!</div>');
				 redirect('admin/plotcharges?randomitemidentifier='.$plotno);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Plot charge not updated. Please try again </div>');
				 redirect('admin/plotcharges?randomitemidentifier='.$plotno);
			}
					
				}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	function addplot2()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	$createdat = Date('Y-m-d H:i:s') ;
		$action = $this->input->post("action");
		
		   	  $name = $this->input->post("name");
		  	 $location = $this->input->post("location");
           $agentid = $this->input->post("agentid");
 			    $landlordid = $this->input->post("landlordid");
				    $totalhouse = $this->input->post("totalhouse");
					    $country = $this->input->post("country");
						    $description = $this->input->post("description");
								$accountno = $this->input->post("accountno");
				$accountname = $this->input->post("accountname");	
		
						
    $confirmtotal = $this->accomodationmodel->countplotcompanyid($companyid);

		//var_dump($confirmtotal);
		
	
		
		
			$confirmlevel= $this->accomodationmodel->confirmsmsconfig($companyid);
			$tplot=$confirmlevel[0]['plot'];
			
			
			if(($tplot!="" )&& ($tplot<= $confirmtotal )){
				
				//echo"You have reach a maximum of ".$tplot."plots which was assigned to you. Please contact robiseach ltd";
				
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning!! Plot not added!. You have reached a maximum of '.$tplot.'plots which was assigned to you out of expected '.$tplot.' plots.Please contact robiseach ltd(0780655987) to add more plots!! </div>');
				 redirect('admin/viewallplots');
				 return false;
			}
			
			"You  have  added ".$confirmtotal." plots out of expected ".$tplot." Feel free to add more";	
			
			
		  	
		$this->form_validation->set_rules('name', 'Plot Name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('location', 'location Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('totalhouse', 'total house', 'trim|required|xss_clean');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allplots',$data);
		$this->load->view("template/footerpage");
		//redirect('admin/plots');
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_plot') == "plot")
		 {
						
			
			$data = array(
				 'companyid' => $companyid,
				'userid' => $userid,
				'name' => $this->input->post('name'),
				'location' => $this->input->post('location'),
				'agentid' => $this->input->post('agentid'),
				'landlordid' => $this->input->post('landlordid'),
				'createdat' => $createdat,
					'accountname' => $this->input->post('accountname'),
				'accountno' => $this->input->post('accountno'),
				'totalhouse' => $this->input->post('totalhouse'),
				'country' => $this->input->post('country'),
				'agentid' => $this->input->post('agentid'),
				'description' => $this->input->post('description'),
				'commission' => $this->input->post('commission'),

			);
			
			if($action=="insert"){
			if ($this->accomodationmodel->insertPlot($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Plot is added Successfully ! !!!</div>');
					 redirect('admin/viewallplots');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Plot could not be added. Please try again later!!! </div>');
				 redirect('admin/viewallplots');
			}
			}else if($action=="update"){
				
					$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadetePlot($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Plot is updated Successfully ! !!!</div>');
					 redirect('admin/viewallplots');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Plot not updated. Please try again </div>');
				 redirect('admin/viewallplots');
			}
				
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	function addplot()
    {
		 $session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	$createdat = Date('Y-m-d H:i:s') ;
		$action = $this->input->post("action");
		
		   	  $name = $this->input->post("name");
		  	 $location = $this->input->post("location");
           $agentid = $this->input->post("agentid");
 			    $landlordid = $this->input->post("landlordid");
				    $totalhouse = $this->input->post("totalhouse");
					    $country = $this->input->post("country");
						    $description = $this->input->post("description");
								$accountno = $this->input->post("accountno");
																$penalty = $this->input->post("penalty");
								$branchid = $this->input->post("branchid");
								$service = $this->input->post("service");

				$accountname = $this->input->post("accountname");	
		 	  $branch = $this->input->post("branch");
		  	 $bank = $this->input->post("bank");
           $tax = $this->input->post("tax");
		   		   		   	$utility = $this->input->post("utility");	

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

		   	$areas = $this->input->post("areas");	
		 	  $coparent = $this->input->post("coparent");
		  	 $showpenalty = $this->input->post("showpenalty");
           $water = $this->input->post("water");
				           $garbage = $this->input->post("garbage");
						           $taxtype = $this->input->post("taxtype");

		   				           $power = $this->input->post("power");
		   				           $vat2 = $this->input->post("vat2");

		     $invoicedate = $this->input->post("invoicedate");
		   	$penaltydate = $this->input->post("penaltydate");

		   
		     $lease = $this->input->post("lease");
		   	$servicedeposit = $this->input->post("servicedeposit");

			
				
		   	
	
		        $invoicesms = $this->input->post("invoicesms");
		   				           $receiptsms = $this->input->post("receiptsms");

		   
		   
		   
		   
						
    $confirmtotal = $this->accomodationmodel->countplotcompanyid($companyid);

		//var_dump($confirmtotal);
		
	
		//
		
			$confirmlevel= $this->accomodationmodel->confirmsmsconfig($companyid);
			$tplot=$confirmlevel[0]['plot'];
			
	
		///	
			///"You  have  added ".$confirmtotal." plots out of expected ".$tplot." Feel free to add more";	
			
			
		  	
		$this->form_validation->set_rules('name', 'Plot Name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('location', 'location Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('totalhouse', 'total house', 'trim|required|xss_clean');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allplots',$data);
		$this->load->view("template/footerpage");
		//redirect('admin/plots');
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_plot') == "plot")
		 {
						
			 
  
			$data = array(
			
			 'lease' => $lease,
				'servicedeposit' => $servicedeposit,
				
				
			 'invoicedate' => $invoicedate,
				'penaltydate' => $penaltydate,
				
				
				 'companyid' => $companyid,
				'userid' => $userid,
				    'garbage' => $garbage,
				'water' => $water,
		   	'showpenalty' => $showpenalty,
		   	'areas' => $areas,
		   	'coparent' => $coparent,
					   	'partial' => $partial,
					   	'vat2' => $vat2,
		   		   	'service' => $service,

		   		   	'branchid' => $branchid,
		   		   	'power' => $power,
		   		   	'receiptsms' => $receiptsms,
		   		   	'invoicesms' => $invoicesms,
		   		   	'utility' => $utility,

		   
				'name' => $this->input->post('name'),
				'category' => trim($this->input->post('category')),

				'location' => $this->input->post('location'),
				'agentid' => $this->input->post('agentid'),
				'landlordid' => $this->input->post('landlordid'),
				'createdat' => $createdat,
					'accountname' => $this->input->post('accountname'),
				'accountno' => $this->input->post('accountno'),
				'totalhouse' => $this->input->post('totalhouse'),
				'country' => $this->input->post('country'),
				'agentid' => $this->input->post('agentid'),
				'description' => $this->input->post('description'),
				'commission' => $this->input->post('commission'),
				'bank' => $this->input->post('bank'),
				'tax' => $this->input->post('tax'),
				'branch' => $this->input->post('branch'),
				'penalty' => $this->input->post('penalty'),
								'penaltytype' => $this->input->post('penaltytype'),
																'taxtype' => $this->input->post('taxtype'),



			);
			
			if($action=="insert"){
						
			if(($tplot!="" )&& ($tplot<= $confirmtotal )){
				
				//echo"You have reach a maximum of ".$tplot."plots which was assigned to you. Please contact robiseach ltd";
				
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning!! Plot not added!. You have reached a maximum of '.$tplot.'plots which was assigned to you out of expected '.$tplot.' plots.Please contact robiseach ltd(0780655987) to add more plots!! </div>');
				 redirect('admin/viewallplots');
				 return false;
			}
			if ($this->accomodationmodel->insertPlot($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Plot is added Successfully ! !!!</div>');
					 redirect('admin/viewallplots');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Plot could not be added. Please try again later!!! </div>');
				 redirect('admin/viewallplots');
			}
			}else if($action=="update"){
				
					$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadetePlot($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Plot is updated Successfully ! !!!</div>');
					 redirect('admin/viewallplots');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Plot not updated. Please try again </div>');
				 redirect('admin/viewallplots');
			}
				
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	function addhouse()
    {
		 $session_data = $this->session->userdata('logged_in');

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

				
				
	 
		  $createdat = Date('Y-m-d H:i:s') ;
		$action = $this->input->post("action");
	
		$id = $this->input->post("id");
			
					$vat = $this->input->post("vat");
					$commission = $this->input->post("commission");
					$priority = $this->input->post("priority");

		$plotno = $this->input->post("plotno");
		
			$houseno = $this->input->post("houseno");
		   			$category = trim($this->input->post("category"));

		  	 $type = $this->input->post("type");
           $cost = $this->input->post("cost");
 			    $status = $this->input->post("status");
				    			    $floor = $this->input->post("floor");
			$branchid = $this->input->post("branchid");
			$vat2 = $this->input->post("vat2");
			$paymentdetails = $this->input->post("paymentdetails");
			$meternumber = $this->input->post("meternumber");

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

					$electricitycharge = $this->input->post("electricitycharge");
					$bowholeno = $this->input->post("bowholeno");
					$bowholerate = $this->input->post("bowholerate");

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

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

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

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

			
			
			
			
			
			
			
		//$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('type', 'House type ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
			
		
		
		
		
		
		
		
			$data['errors'] = validation_errors();
		
		
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewhouses',$data);
		$this->load->view("template/footerpage");
		//redirect('admin/plots');
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_house') == "house")
		 {
			 
			 		$confirmtotal = $this->accomodationmodel->countplotno($plotno);

		
		
		
		
			$confirmhouseno = $this->accomodationmodel->confirmnhouseno($plotno);
			$tthouse=$confirmhouseno[0]['totalhouse'];
			$confirmtotal;
			

				$data = array(
								 'vat' => $vat,

				'companyid' => $companyid,
				'userid' => $userid,
								'vat2' => $this->input->post('vat2'),

				'houseno' => $this->input->post('houseno'),
				'plotno' => $this->input->post('plotno'),
				'type' => $this->input->post('type'),
				'cost' => $this->input->post('cost'),
				'status' => $this->input->post('status'),
				'waterno'=>$waterno,
				'waterrate'=>$waterrate,
				'watercharge'=>$watercharge,
				'electricityno'=>$electricityno,
				'electricityrate'=>$electricityrate,
				'electricitycharge'=>$electricitycharge,
				'bowholeno'=>$bowholeno,
				'bowholerate'=>$bowholerate,
				'bowholecharge'=>$bowholecharge,
								'beds'=>$beds,

				
				
				
				'category' => $category,
				'createdat' => $createdat,
				'floor' => $floor,
				'commission' => $commission,
				'branchid' => $branchid,
				'paymentdetails' => $paymentdetails,
				'meternumber' => $meternumber,

				'priority' => $priority,

				'vat' => $vat,

				
				'description' => $this->input->post('description')
			);
			if($action=="insert"){
							if (($this->accomodationmodel->checkroomavailablity($plotno,$houseno))==TRUE )
			{	
		
		  if ($confirmtotal > $tthouse)
						   {
							  
							  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">The number of houses/rooms ('.$confirmtotal.') should not be more than('.$tthouse.') that are indicated in the plot..Make sure you update the number in the plot first.</div>');
								
				redirect('admin/viewplot?randomitemidentifier='.$plotno.'&category='.$category);
return false;
						   }
						
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! House / Room can not be Added! . House / Room number '.$houseno.' in plot ' .$plotno.'  is already added. You can just update the house/room. </div>');
				 		 $this->load->view("template/headerpagemin");
				redirect('admin/viewplot?randomitemidentifier='.$plotno.'&category='.$category);
				
				return false;
			}
		
			if ($this->accomodationmodel->insertHouse($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">House is added Successfully ! !!!</div>');
				redirect('admin/viewplot?randomitemidentifier='.$plotno.'&category='.$category);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. House not added. Please try again </div>');
				 redirect('admin/houses');
			}
			} if($action=="update"){
				
				if ($this->accomodationmodel->upadeteHouse($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">House is updated Successfully ! !!!</div>');
				redirect('admin/editroom?randomitemidentifier='.$id);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. House not updated. Please try again </div>');
				redirect('admin/editroom?randomitemidentifier='.$id);
			}
				
				
				
				
				
				
				
				
				
				
				
				
				
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	function addhouse2()
    {
		 $session_data = $this->session->userdata('logged_in');

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

				
				
	 
		  $createdat = Date('Y-m-d H:i:s') ;
		$action = $this->input->post("action");
	
		$id = $this->input->post("id");
			
		
		
		$plotno = $this->input->post("plotno");
		
			$houseno = $this->input->post("houseno");
		   
		  	 $type = $this->input->post("type");
           $cost = $this->input->post("cost");
 			    $status = $this->input->post("status");
				    			    $floor = $this->input->post("floor");

			$description = $this->input->post("description");
			
		//$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('type', 'House type ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
			
		
		
		
		
		
		
		
			$data['errors'] = validation_errors();
		
		
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewhouses',$data);
		$this->load->view("template/footerpage");
		//redirect('admin/plots');
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_house') == "house")
		 {
			 
			 		$confirmtotal = $this->accomodationmodel->countplotno($plotno);

		
		
		
		
			$confirmhouseno = $this->accomodationmodel->confirmnhouseno($plotno);
			echo$tthouse=$confirmhouseno[0]['totalhouse'];
			echo$confirmtotal;
			
						 
				$data = array(
				 'companyid' => $companyid,
				'userid' => $userid,
				'houseno' => $this->input->post('houseno'),
				'plotno' => $this->input->post('plotno'),
				'type' => $this->input->post('type'),
				'cost' => $this->input->post('cost'),
				'status' => $this->input->post('status'),
				'createdat' => $createdat,
				'floor' => $floor,
				
				'description' => $this->input->post('description')
			);
			if($action=="insert"){
							if (($this->accomodationmodel->checkroomavailablity($plotno,$houseno))==TRUE )
			{	
		
		  if ($confirmtotal > $tthouse)
						   {
							  
							  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">The number of houses/rooms ('.$confirmtotal.') should not be more than('.$tthouse.') that are indicated in the plot..Make sure you update the number in the plot first.</div>');
								
												redirect('admin/viewplot?randomitemidentifier='.$plotno,$data);
return false;
						   }
						
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! House / Room can not be Added! . House / Room number '.$houseno.' in plot ' .$plotno.'  is already added. You can just update the house/room. </div>');
				 		 $this->load->view("template/headerpagemin");
				redirect('admin/viewplot?randomitemidentifier='.$plotno,$data);
				
				return false;
			}
		
			if ($this->accomodationmodel->insertHouse($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">House is added Successfully ! !!!</div>');
					 redirect('admin/viewplot?randomitemidentifier='.$plotno);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. House not added. Please try again </div>');
				 redirect('admin/houses');
			}
			} if($action=="update"){
				
				if ($this->accomodationmodel->upadeteHouse($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">House is updated Successfully ! !!!</div>');
					 redirect('admin/viewpallmyplots');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. House not updated. Please try again </div>');
				 redirect('admin/houses');
			}
				
				
				
				
				
				
				
				
				
				
				
				
				
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	 public function updatechekout()
    {
		
		
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
					  $updatedat = Date('Y-m-d H:i:s') ;

 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $plotno = $this->input->post("plotno");
		 		 $houseno = $this->input->post("houseno");
		   	  $itemid = $this->input->post("itemid");

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

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

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


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

	
		 $this->load->view('pmsdata/allbooking', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('updatecharges') == "charges")
					   {
						   
						   
						   
			        		$bookroom = $this->usermodel->populateallarray('bookroom','id',$itemid);

						$checkstatus=$bookroom[0]["paymentstatus"];
								$creditpaid=$bookroom[0]["credit"];

		
		
		
			
		
		
			if($creditpaid>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> Check out was not successful since there is pendig balance of '.$creditpaid .' which should be paid/cleared first .. Try again</div>');								

								redirect('admin/allocate?randomitemidentifier='.$houseno .'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					


					return false;
			}
						   
						if($checkstatus=="Not Cleared"){
 $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 out was not successful because the room has not been cleared. Please clear/pay first .. Try again</div>');								

								redirect('admin/allocate?randomitemidentifier='.$houseno .'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					


					return false;
			}
						   
						   
						   
									   
						   
						   
						   
						   
						   
						   
						   
						   
												$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								);
								
								
								
								
								
															$mydata=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
										
								
								
								
								
								
								
								
							$usr_result = $this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 //$this->usermodel->updatedatabytwo($mydata,'house','houseno',$houseno,'plotno',$plotno);
							$usr_result = $this->usermodel->updatedata($mydata,'house','id',$roomidentifier);

								 
						 $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('admin/viewpallmyplots');

							 
								 
								// redirect('admin/allocate?randomitemidentifier='.$houseno .'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
							}
							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> Check out was not Updated.. Try again</div>');
								
								 redirect('admin/allocate?randomitemidentifier='.$houseno .'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	 public function myupdatechekout()
    {
		
		
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
					  $updatedat = Date('Y-m-d H:i:s') ;

 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 

		 		 $plotno = $this->input->post("plotno");
		 		 $houseno = $this->input->post("houseno");
		 		 $roomidentifier = $this->input->post("roomidentifier");

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

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

		
							  		  $this->form_validation->set_rules("roomidentifier", "room details", "trim|required");


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

		
		 $this->load->view('pmsdata/searchallhouse', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('updatecheckout') == "checkout")
					   {
						   	      $checkoutcustomerwithbalance=$this->usermodel->populatuserpermissionsdataarray('accomodation','checkoutcustomerwithbalance',$userid);

	$booking  = $this->usermodel->populatealldatanorraythree('bookroom','plotno', $plotno,'houseno', $houseno,'status','active');



	  $itemid=$booking[0]['id'];
						 
   
   

						 

						$checkstatus=$booking[0]["paymentstatus"];
								//$creditpaid=$booking[0]["credit"];
								
								
								   $houserent = $this->accomodationmodel->gethousedetails($plotno,$houseno);

 $category=$houserent[0]["category"];
								
			if(	$category=="rental"){
$creditpaid=$booking[0]["totalamount"];
			}else{
$creditpaid=$booking[0]["credit"];
			}				
								
		
		
		
		if($checkoutcustomerwithbalance==false){
						
					
		
			if($creditpaid>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> Check out was not successful since there is pendig balance of '.$creditpaid .' which should be paid/cleared first .. Try again</div>');								

					 	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/viewpallmyplots');	
						}


								 
					


					return false;
			}
							   
						if($checkstatus=="Not Cleared"){
 $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 out was not successful because the room has not been cleared. Please clear/pay first .. Try again</div>');								

	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/viewpallmyplots');	
						}
					


					return false;
			}
						   
				}								 
						   

			if ($this->input->post('balance'))
		 { 
			 $balance = $this->input->post("balance");
			
			 if( $balance=="yes"){
				 
							 											$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 		'totalamount'=>0,
			
			'checkoutdate'=>$updatedat,
				
			
								); 
			 }else{
			 
			 											$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								);
			 }
			 
		 }else{
			 
														$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								); 
		 }
			   
	
								
								
								
								
								
															$mydata=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
								
								
															$mydatadaily=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			'ordersales'=>$status,
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
				
				
				$updateroom=array(		
			'updatedby'=>$userid,
			
				
			///
		  	'ordersales'=>"vacant",
			
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
								
								
								
								
					
								
							$usr_result = $this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);

							$usr_result = 	 $this->usermodel->updatedata($mydata,'house','id',$roomidentifier);

														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								$bookingdailycharges  = $this->usermodel->populatealldatanorraythree('dailycharges','plotno', $plotno,'houseno', $houseno,'ordersales','active');
								$itemiddailycharges=$bookingdailycharges[0]['id'];
					$itemiddailycharges=$bookingdailycharges[0]['id'];

	  


								
								
							//	$this->usermodel->updatedatabytwo($updateroom,'dailycharges','houseno',$houseno,'plotno',$plotno);

		$this->usermodel->updatedata($mydatadaily,'dailycharges','id',$itemiddailycharges);
	$getbooking= $this->usermodel->geteallsales_Bookings($bookingdailycharges[0]['transactioncode']);
if($getbooking < 1){
	
	$this->usermodel->updatedata($datachekout,'bookroom','transactioncode',$bookingdailycharges[0]['transactioncode']);
	
}
								 
		if ($this->input->post('sendsms'))
		 { 
		$sendsms = $this->input->post("sendsms");
			 if($sendsms=="yes"){
				 
				 if ($this->input->post('view')){
						$myview = $this->input->post("view");
						
						}else{
						$myview = "admin/viewpallmyplots";
						}
			$myowner = $this->usermodel->populateallarray('bookroom','id',$itemid);
			$smsowner=$myowner[0]["tenantid"];
						$owner = $this->usermodel->populateallarray('people','id',$smsowner);

						$contact=$owner[0]["phone"];


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

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

if($feedback !=""){
	$taskmessage =$feedback;

}else{
	$taskmessage = "Hi! Thank you for visiting our hotel. Remember to return the key";

}


					$this->pushroomsms($taskmessage,$contact,$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>');	
					if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/viewpallmyplots');	
						}
							}
							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> Check out was not Updated.. Try again</div>');
								
	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/viewpallmyplots');	
						}
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	 public function myupdatechekoutbedsgoup()
    {
		
		
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
					  $updatedat = Date('Y-m-d H:i:s') ;

 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 
		 		// $bedid = $this->input->post("bedid");

		 		 $plotno = $this->input->post("plotno");
		 		 $houseno = $this->input->post("houseno");
		 		 $roomidentifier = $this->input->post("roomidentifier");

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

		    		 		 $balance = $this->input->post("balance");
		    		 		 $view = $this->input->post("view");

		
							  		  $this->form_validation->set_rules("roomidentifier", "room details", "trim|required");


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

		
		 $this->load->view('pmsdata/dailypaymentgroup', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('updatecheckout') == "checkoutbedgroup")
					   {
						   	      $checkoutcustomerwithbalance=$this->usermodel->populatuserpermissionsdataarray('accomodation','checkoutcustomerwithbalance',$userid);

	$booking  = $this->usermodel->populateallarray('dailycharges','id', $roomidentifier);
	  $bedid=$booking[0]['bedid'];
	  $itemid=$booking[0]['id'];
			  $transactioncode=$booking[0]['transactioncode'];				 
   
			$allbooking  = $this->usermodel->populateallarray('bookroom','transactioncode', $transactioncode);
				   

						$checkstatus=$allbooking[0]["paymentstatus"];
								//$creditpaid=$booking[0]["credit"];
								
								
								   $houserent = $this->accomodationmodel->gethousedetails($plotno,$houseno);
 $myroomid=$houserent[0]["id"];
 $category=$houserent[0]["category"];
$ttbeds=$houserent[0]['beds'];
$originalstatus=$houserent[0]['status'];				
			if(	$category=="rental"){
$creditpaid=$booking[0]["totalamount"];
			}else{
$creditpaid=$booking[0]["credit"];
			}				
								
		
		
		
		if($checkoutcustomerwithbalance==false){
						
					
		
			if($creditpaid>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> Check out was not successful since there is pendig balance of '.$creditpaid .' which should be paid/cleared first .. Try again</div>');								
	redirect($view.$transactioncode);



								 
					


					return false;
			}
							   
						if($checkstatus=="Not Cleared"){
 $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 out was not successful because the room has not been cleared. Please clear/pay first .. Try again</div>');								

redirect($view.$transactioncode);
					


					return false;
			}
						   
				}								 
						   

			if ($this->input->post('balance'))
		 { 
			 $balance = $this->input->post("balance");
			
			 if($balance=="yes"){
				 
			$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 		'totalamount'=>0,
			
			'checkoutdate'=>$updatedat,
				
			
								); 
			 }else{
			 
			 											$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								);
			 }
			 
		 }else{
			 
														$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								); 
		 }
			   
					if($bedid !=""){
						$beddata=array(		
			
			'status'=>"active",
			
			);
					
								 $this->usermodel->updatedata($beddata,'beds','id',$bedid);
				
	
$confirmvacantrooms = $this->usermodel->GettatalbedsVacant($myroomid);

$currentstatus="";
if(($ttbeds > 1) && ($ttbeds !="")) {

if($confirmvacantrooms  >= $ttbeds){	
$currentstatus=$status;

}else{
$currentstatus=$originalstatus;

}	
}else{
$currentstatus=$status;

}	
 	}else{
	$currentstatus=$status;
	
		
	}
					
								
								
								
								
			$mydata=array(		
			'userid'=>$userid,
			'status'=>$currentstatus,
			'updatedat'=>$updatedat,
			);
										
					$datachekoutrooms=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 		
			
		
				
			
								); 
							
								
								
								
					
								
							$usr_result = $this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);
			$this->usermodel->updatedata($datachekoutrooms,'dailycharges','id',$roomidentifier);
								 $this->usermodel->updatedata($mydata,'house','id',$myroomid);

														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 //$this->usermodel->updatedatabytwo($mydata,'house','houseno',$houseno,'plotno',$plotno);

								 
						 $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($view.$transactioncode);						
							}
							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> Check out was not Updated.. Try again</div>');
								
redirect($view.$transactioncode);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	 public function mergedsales() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
	 
	 $session_data = $this->session->userdata('logged_in');

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

	 $companyid = $data['companyid'];
	    if (isset($_GET['invoice'])){
	
    
      $invoice= $_GET['invoice'];

	 
	 
	 
	 
	 
	 
	 
    
 $data['roomcharges']= $this->usermodel->populateall('dailycharges','invoice',$invoice);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

		
				$this->load->view('pmsdata/mergedsales',$data);
		$this->load->view("template/footerpage");
		}else{
			echo "That action is not allowed. Try again";
			
		}
  }
	
	
	
	
	  public function pendinbookings() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
    
	//$data['booking'] = $this->usermodel->populatedailypeyment($companyid);
	$data['booking'] = $this->usermodel->pendingbookings($companyid,$branchid);

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

		
				$this->load->view('pmsdata/pendinbookings',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
	
	
	
	
	
	
	
	
	
	  public function pendingbeds() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
    
	//$data['booking'] = $this->usermodel->populatedailypeyment($companyid);
	$data['booking'] = $this->usermodel->populatedailypeymentpendingbybeds($companyid,$branchid);

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

		
				$this->load->view('pmsdata/pendingbeds',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
	
	
	
	
	
	
		  public function activerooms() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
    
	//$data['booking'] = $this->usermodel->populatedailypeyment($companyid);
	$data['booking'] = $this->usermodel->activerooms($companyid,$branchid);

		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				  $data['fromdate'] = "";
				  $data['todate'] = "";


		
				$this->load->view('pmsdata/searchallpaymentnomoneybreakfast',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
	
	
	
	
	 public function myupdatechekoutbeds()
    {
		
		
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
					  $updatedat = Date('Y-m-d H:i:s') ;

 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 				 		 
		 		 $bedid = $this->input->post("bedid");

		 		 $plotno = $this->input->post("plotno");
		 		 $houseno = $this->input->post("houseno");
		 		 $roomidentifier = $this->input->post("roomidentifier");

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

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

		
							  		  $this->form_validation->set_rules("roomidentifier", "room details", "trim|required");


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

		
		 $this->load->view('pmsdata/searchallhouse', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('updatecheckout') == "checkoutbed")
					   {
						   	      $checkoutcustomerwithbalance=$this->usermodel->populatuserpermissionsdataarray('accomodation','checkoutcustomerwithbalance',$userid);

	$booking  = $this->usermodel->populateallarray('bookroom','id', $roomidentifier);



	  $itemid=$booking[0]['id'];
						 
   
						   

						$checkstatus=$booking[0]["paymentstatus"];
								//$creditpaid=$booking[0]["credit"];
								
								
								   $houserent = $this->accomodationmodel->gethousedetails($plotno,$houseno);
 $myroomid=$houserent[0]["id"];
 $category=$houserent[0]["category"];
$ttbeds=$houserent[0]['beds'];
$originalstatus=$houserent[0]['status'];				
			if(	$category=="rental"){
$creditpaid=$booking[0]["totalamount"];
			}else{
$creditpaid=$booking[0]["credit"];
			}				
								
		
		
		
		if($checkoutcustomerwithbalance==false){
						
					
		
			if($creditpaid>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> Check out was not successful since there is pendig balance of '.$creditpaid .' which should be paid/cleared first .. Try again</div>');								

					 	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/salesreceipts');	
						}


								 
					


					return false;
			}
							   
						if($checkstatus=="Not Cleared"){
 $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 out was not successful because the room has not been cleared. Please clear/pay first .. Try again</div>');								

	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/salesreceipts');	
						}
					


					return false;
			}
						   
				}								 
						   

			if ($this->input->post('balance'))
		 { 
			 $balance = $this->input->post("balance");
			
			 if( $balance=="yes"){
				 
							 											$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 		'totalamount'=>0,
			
			'checkoutdate'=>$updatedat,
				
			
								); 
			 }else{
			 
			 											$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								);
			 }
			 
		 }else{
			 
														$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								); 
		 }
			   
					
						$beddata=array(		
			
			'status'=>"active",
			
			);
					
								 $this->usermodel->updatedata($beddata,'beds','id',$bedid);

	
$confirmvacantrooms = $this->usermodel->GettatalbedsVacant($myroomid);






$currentstatus="";
if(($ttbeds > 1) && ($ttbeds !="")) {

if($confirmvacantrooms  >= $ttbeds){	
$currentstatus=$status;

}else{
$currentstatus=$originalstatus;

}	
}else{
$currentstatus=$status;

}	
 
					
								
								
								
								
			$mydata=array(		
			'userid'=>$userid,
			'status'=>$currentstatus,
			'updatedat'=>$updatedat,
			);
										
								
								
								
								
					
								
							$usr_result = $this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);

								 $this->usermodel->updatedata($mydata,'house','id',$myroomid);

														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								 //$this->usermodel->updatedatabytwo($mydata,'house','houseno',$houseno,'plotno',$plotno);

								 
						 $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>');	
	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/salesreceipts');	
						}
							}
							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> Check out was not Updated.. Try again</div>');
								
	if ($this->input->post('view')){
						$view = $this->input->post("view");
						redirect($view);
						}else{
						redirect('admin/salesreceipts');	
						}
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	 public function updatebulkchekout()
    {
		
		
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
					  $updatedat = Date('Y-m-d H:i:s') ;

 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $checkoutdate = $this->input->post("checkoutdate");
		 			 		 $view = $this->input->post("view");
		 			 		 $plotno = $this->input->post("plotno");
		 			 		 $status = $this->input->post("status");

		    
		
							  		  $this->form_validation->set_rules("checkoutdate", "checkout date", "trim|required");


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

		
		 $this->load->view('pmsdata/searchhouse', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('bulkcheckout') == "checkout")
					   {
					
												
$housebookings = $this->accomodationmodel->getbycheckoutdate($checkoutdate,$plotno);


if(is_array($housebookings)) {

   foreach($housebookings as $bookrow){

   $itemid=$bookrow->id;
      $houseno=$bookrow->houseno;
      $plotno=$bookrow->plotno;

   
												
												
												
												
												
												$datachekout=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 	
			
			'checkoutdate'=>$updatedat,
				
			
								);
								
															$data=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>$status,
			
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
										
								
								
								
								
								
								
								
							$usr_result = $this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);
							if ($usr_result ==TRUE) //active user record is present
							{

								 $this->usermodel->updatedatabytwo($data,'house','houseno',$houseno,'plotno',$plotno);
							}

   }		
							//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 Checked out..</div>');	
								 redirect($view);
							}
							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> Check out was not Updated.. Try again</div>');
								
								 redirect($view);
							}
					  

}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> Check out was not Updated.. No room was vacant.. Try again</div>');
								
								 redirect($view);
	
}
					  }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	 public function updatebulkstatuschange()
    {
		
		
		
		
		
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
	
		  $data['branchid'] = $session_data['branchid'];
		 	$branchid= $data['branchid'];
			
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
					  $updatedat = Date('Y-m-d H:i:s') ;

 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $checkoutdate = $this->input->post("checkoutdate");
		 			 		 $view = $this->input->post("view");
		 			 		 $fromstatus = $this->input->post("fromstatus");
		 			 		 $tostatus = $this->input->post("tostatus");
							
		
							  		  $this->form_validation->set_rules("checkoutdate", "checkout date", "trim|required");


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

		
		 $this->load->view('pmsdata/housekeeping', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('bulkstatuschange') == "status")
					   {
					
												
			$housebookings = $this->usermodel->populatealldatanoarray('house','branchid',$branchid,'status',$fromstatus);






								$updatedata = array();

if(is_array($housebookings)) {

   foreach($housebookings as $bookrow){

   $itemid=$bookrow->id;
      $status=$bookrow->status;
					
			$updatedata[] =array(			
			'userid'=>$userid,
				'id'=>$itemid,
				
			
		  	'status'=>$tostatus,
			
			 	
			
			'updatedat'=>$updatedat,
				
			
								);
   }	
		$RESULT =	$this->db->update_batch('house',$updatedata, 'id');
	    
}	
							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 changed the status in bulk ..</div>');	
								 redirect($view);
							}
							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> Status  was not Updated.. Try again</div>');
								
								 redirect($view);
							}
					  


					  }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	
	
	
public function addadvancebooking()
    {
		
		

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

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	  
		  $data['branchid'] = $session_data['branchid'];
		 	$branchid= $data['branchid'];
	 
	 
	 
	 
	 
	 
	 
	 
	 
 	$data['id'] = $session_data['id'];
         $postedtime = date('Y-m-d');
		$currenttime = date('H:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		 

$tenantid = $this->input->post("tenantid");
	  $startdate = $this->input->post("startdate");
	  $closedate = $this->input->post("closedate");		  
		  $amount = $this->input->post("amount");    
		    
		  $description = $this->input->post("description");   
		     		  $action = $this->input->post("action");   
				  		  $view = $this->input->post("view");   
				  		  $balance = $this->input->post("balance");   

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

				  		  $status = $this->input->post("status");   
  
	    $frotime = $this->input->post("frotime");
	  	  $totime = $this->input->post("totime");
		  	  	  $plotno = $this->input->post("plotno");
	  	  $houseno = $this->input->post("houseno");

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

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

		
		 $this->load->view('pmsdata/viewalladvance', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	if ($this->input->post('btn_advance') == "advance")
					   {
						   
						   
						   
						   
						   
						   if($plotno !=""){
							   
							 						 	$housedetails = $this->usermodel->populatealldataarray('house','plotno', $plotno,'houseno', $houseno);
														
															if ($housedetails ==false) //active user record is present
							{

								 
					
			 $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 plot No and house number entered are not correct or dont exist.. Try again</div>');	
								 redirect($view);
								 false;
							}
  
							   
							   
						   }
						   
						   
						   
						   
						   
						   
  
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
		   	  $startdate=$startdate." ".$frotime;
	  	  $closedate=$closedate." ".$totime;
	
						   
						   
						   
						   
						   
						   
						   
												$data=array(		
			'userid'=>$userid,
			
		
			'tenantid'=>$tenantid,
		  	'startdate'=>$startdate,
			
			
			'createdat'=>$dateposted,
			'closedate' => $closedate,		  
		  'amount' => $amount,    
	
		  'description' => $description,   
		   			    'balance' =>$balance,  

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

			   			    'branchid' => $branchid,  
							   			    'houseno' => $houseno,  
			   			    'plotno' => $plotno,  

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

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

								}
								
							
							
							
							
							//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/Updated  advanvce payment.!</div>');
								
								 
					
								 redirect($view);
							}
							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> Advanvce payment  was not added/updated.. Try again</div>');
								
								 redirect($view);
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	  public function updatebeds()
    {
		
			$session_data = $this->session->userdata('logged_in');

	
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $cost = $this->input->post("cost");
		   	  $description = $this->input->post("description");
	  $name = $this->input->post("name");
		   	  $roomid = $this->input->post("roomid");
			  		   	  $mycategoryid = $this->input->post("mycategoryid");
						
								   	  $status = $this->input->post("status");

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

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


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

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


											
												$data=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			'name'=>$name,
		  
		'description'=>$description,

			 	'companyid'=>$companyid,
			
			'updatedat'=>$dateposted,
						

			
								);
							$usr_result = $this->usermodel->updatedata($data,'beds','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('roommsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the bed..</div>');	
								 redirect($view );
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Bed  was not Updated.. Try again</div>');
								
								 redirect($view );
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	  public function updatecharges()
    {
		
			$session_data = $this->session->userdata('logged_in');

	
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $status = $this->input->post("status");
		 		 $cost = $this->input->post("cost");
		   	  $chargeid = $this->input->post("chargeid");
	  $name = $this->input->post("name");
		   	  $roomid = $this->input->post("roomid");
			  		   	  $mycategoryid = $this->input->post("mycategoryid");
						
								   	  $status = $this->input->post("status");

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

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


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

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


											
												$data=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			'name'=>$name,
		  	'cost'=>$cost,
						 	'chargeid'=>$chargeid,

			 	'companyid'=>$companyid,
			
			'updatedat'=>$dateposted,
							'status'=>$status,

			
								);
							$usr_result = $this->usermodel->updatedata($data,'roomcharges','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('roommsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the charges..</div>');	
								 redirect($view );
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not Updated.. Try again</div>');
								
								 redirect($view );
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	  public function updatesalesroomcharges()
    {
		
			$session_data = $this->session->userdata('logged_in');

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

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

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

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

		    
		
				$this->form_validation->set_rules("status", "Payment Status", "trim|required");


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

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


										
												$data=array(		
			'userid'=>$userid,
			
				'status'=>$status,
			
		  	'total'=>$total,
						 
				
			
								);
							$usr_result = $this->usermodel->updatedata($data,'roomsales','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
					
										
			$mydata=array(		
			'userid'=>$userid,
			
				'paymentstatus'=>$status,
		
						 
				
			
								);			
								
					$this->usermodel->updatedata($mydata,'sales','invoice',$invoice);
		
								
								
								 
						 $this->session->set_flashdata('roommsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the charges..</div>');	
								 redirect("user/mychangepayment?myid=$itemid&randomitemidentifier=$randomitemidentifier&randomitemidentifier1=$randomitemidentifier1&roomidentifier=$roomidentifier" );
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not Updated.. Try again</div>');
								
								 redirect("user/mychangepayment?myid=$itemid&randomitemidentifier=$randomitemidentifier&randomitemidentifier1=$randomitemidentifier1&roomidentifier=$roomidentifier" );
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	  public function updateroomcharges()
    {
		
			$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
	$data['companyid'] = $session_data['companyid'];
         $postedtime = date('Y-m-d');
		$currenttime = date('h:i:sa');
 		$dateposted =  ($postedtime)." ".$currenttime ;
		 $userid = $data['id'];
		  $companyid = $data['companyid'];
		 		
		 		 $qty = $this->input->post("qty");
		 		 $cost = $this->input->post("cost");
			
				 
	 $people = $this->input->post("people");
		 		 $sales = $this->input->post("sales");
		
				 
			  		   	  $mycategoryid = $this->input->post("mycategoryid");
			  		   	  $view = $this->input->post("btn_updateroomcharges");

		    
		
							  		  $this->form_validation->set_rules("cost", "total Cost", "trim|required");


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

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


				$amount=$cost * $qty;

												$data=array(		
			'userid'=>$userid,
			
				'amount'=>$amount,
			
		  	'cost'=>$cost,
			
			 	'companyid'=>$companyid,
			
			'updatedat'=>$dateposted,
						 	'qty'=>$qty,
			'sales'=>$sales,
		  	'uomqty'=>$people,
			
								);
							$usr_result = $this->usermodel->updatedata($data,'dailycharges','id',$mycategoryid);


														
							//check if username and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
								
								 
						 $this->session->set_flashdata('roommsg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> You have successfully updated the charges..</div>');	
								 redirect($view );
							}
							else if ($usr_result ==FALSE) 
							{     

			 $this->session->set_flashdata('roommsg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong> Charges  was not Updated.. Try again</div>');
								
								 redirect($view );
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	  public function updateroombooking()
    {
		
			$session_data = $this->session->userdata('logged_in');

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

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

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

		    	   	  $checkout = $this->input->post("checkout");
			  		   	  $checkin = $this->input->post("checkin");

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


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

		
		 $this->load->view('userdata/startbulkcheckinreservation', $data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					 	
						   
						   					 	if ($this->input->post('btn_updateroombooking')){
		
												$data=array(		
			'userid'=>$userid,
			
				'customer'=>$customer,
			'phone'=>$phone,
		  	'idno'=>$idno,
			
			 	'companyid'=>$companyid,
			
			'updatedat'=>$dateposted,
			
				'checkout'=>$checkout,
			
			'checkin'=>$checkin,
				
			
								);
							$usr_result = $this->usermodel->updatedata($data,'dailycharges','id',$mycategoryid);


														
							//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 updated the booking..</div>');	
								 redirect($view );
							}
							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> Booking  was not Updated.. Try again</div>');
								
								 redirect($view );
							}
					   }
					   else
					   {
							redirect('login');
					   }
	    }
    }
	
	
	
	
	
	
	
	
	
	function addbooking()
    {
		 $session_data = $this->session->userdata('logged_in');

   $number=0;
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
		
				   			  //  $tenantid = $this->input->post("tenantid");

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

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


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


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


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

			$houseno = $this->input->post("houseno");
	
					$people = $this->input->post("people");
					//$currency = $this->input->post("currency");

			
		$plotno = $this->input->post("plotno");
		$status = $this->input->post("status");
		 $entrydate = $this->input->post("entrydate");
		 
		 
		 
		 
		//
		$roomstatus="";
	
		
		 
		 		 $checkoutdate = $this->input->post("checkoutdate");
				 
				 		 $myroomtype= $this->input->post("roomtype");
		 	$getroomdetails = explode("==",$myroomtype);
		
								$roomtype = $getroomdetails[0];		
		
		$chargeid = $getroomdetails[1];	
						

	 $beds= $this->input->post("bed");
	 if( $beds!=""){
		 
		 
		 	$getbeddetails = explode("==",$beds);
		
		$bedid = $getbeddetails[0];		
		
		$bedname = $getbeddetails[1];	

	 }else{
			
		$bedid ="";		
		
		$bedname = 1;	 
		 
		 
	 }


						
				 	 
				 
				   $finaldate = strtotime(date($checkoutdate));
									$mycurrentdate = strtotime(date($createdat));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
				 
if($days< 1){
	
	$number=1;
}else{
		$number=$days;

}

$createdat=$createdat." ".$checkintime;

			$checkoutdate =$checkoutdate." ".$checkouttime;	 
			
			
			

		 
		 $myroomtype = $this->input->post("roomtype");
		 
		 
		 
		
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 $amount = $this->input->post("amount");
		 $paymentcode = $this->input->post("paymentcode");
		$paymentstatus = $this->input->post("paymentstatus");
 $mpesa = $this->input->post("mpesa");
		$card = $this->input->post("card");
				$voucher = $this->input->post("voucher");

						$credit = $this->input->post("credit");
						$points = $this->input->post("points");
						$cheque = $this->input->post("cheque");

								$totalamount = $this->input->post("totalamount");
	
		 		//$transactioncode=$this->createRandomPassword();

		 		 	$transactioncode = $userid.time();

		 
		   
		   			    //$tenantid = $this->input->post("tenantid");
						
						
	$tenantcodes = explode(':=',$this->input->post("tenantid"));
  $tenantid = htmlspecialchars(trim($tenantcodes[0]));

 
						
						 $maindiscount = $this->input->post("discount");
			$maindiscount = explode(':=',$this->input->post("discount"));

						   $mydisc = htmlspecialchars(trim($maindiscount[0]));
							 $disctype = htmlspecialchars(trim($maindiscount[1]));
					
						
						if($disctype=="Percentage"){
							$allthetotalamounts = $this->input->post("totalamount");

							$discount= $this->formatMoney((($mydisc/100)*$allthetotalamounts),true);

							
						}else{
							
							$discount=$mydisc;
						}
						

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

					$othercurrencyamount = $this->input->post("tocurrencyamount");
	
					$tocurrencyamount = $this->input->post("tocurrencypaid");
					$currency = $this->input->post("basecurrency");
					$tocurrencychnage = $this->input->post("tocurrencychnage");
			


			
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('status', 'status  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allbooking',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_booking') == "booking")
		 {
			 
			 
			 	if($status=="active"){
		$roomstatus="checkin";
		}else{
			$roomstatus=$status;
			
		}
			 
			 
			 
			 
			 
			 
			 
			 
			 
						$neededamount=($roomtype* $number);


			$finalamount=($totalamount);
				//$finalamount=($totalamount-$discount);

		
			
				$paid=$amount+$mpesa+$card+$voucher+$cheque+$points+$credit;
			$balance=$finalamount-$paid;
			$clientbalance=$finalamount-$paid-$credit;
			if($clientbalance > 0){
				$clientbalance =$clientbalance *-1;
			}else{
				$clientbalance =$clientbalance;

			}
		
			
		
			        		$customer = $this->usermodel->populateallarray('people','id',$tenantid);

						$idno=$customer[0]["idno"];
		
		
	        		$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);
										 $activatebank=$configuration[0]['bankcode'];

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

if($sendfeedback=="yes"){
				$smsowner=$configuration[0]["paymenttypes"];



	
			  		$owner = $this->usermodel->populateallarray('people','id',$smsowner);

						$contact=$owner[0]["phone"];
			//$total_amount=$owner[0]['totalsms'];	
			
						  		$myuser = $this->usermodel->populateallarray('people','id',$userid);

			    $correctime = date("d/m/Y H:ia");
			

	
		 	$taskmessage = "Hi! This is to inform you that room No.". $houseno ." has been sold by ". $myuser[0]['surname'] ." for Ksh.". $finalamount ." on  ". $correctime .". Kindly login to confirm from the system.Automatic sms.";

						   
					
			
}
			
			
			
			
			
			
		
		
			if($paid<$finalamount){
					$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! This customer with ID NO ('.$idno.') could not be checked in. The expected amount ('.$finalamount.') of the room  can not be less than total money  paid ('.$paid.') by the customer. Try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 return false;
			}
			
			
			
			
				if((($mpesa >0)&& ($paymentcode ==""))|| (($card >0)&& ($paymentcode ==""))|| (($cheque >0) && ($paymentcode ==""))){
					$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! You have to enter payment/transaction code for you to continue. Try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 return false;
			}
			
		
	
				 $vatable=0;
		$myfinaltax=0;
		
			$display1=$configuration[0]["display1"]; 
			$display2=$configuration[0]["display2"]; 
			
			$houserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
//$roomid=$houserents[0]['id'];

$tax1rate=	$houserents[0]['vat'];	
$tax2rate=$houserents[0]['vat2'];
$tax_included=$houserents[0]['vat2'];


$vattype="";
	if($display1=="yes"){
		$vattype="VATABLE";
			
	if($display2=="yes"){
//echo $tax_included
	$tax_included=$houserents[0]['vat'];

	
	
		
	$tax2rate=$configuration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 //$ttoltaxable=(($sellingprice*$latestqty)/ $mytax2);
	 $ttoltaxable=(($finalamount)/ $mytax2);

	 
	 $myfinaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$vatable= $this->formatMoney($ttoltaxable, true);

	
	

	
	
	
	
	
	
	

	}else{
	 		 


	$mytax=1+($tax1rate/100); 
	$vatable=($finalamount/$mytax);
	$myfinaltax=(($finalamount-$vatable));
	$finaltax2=0;							
								
								
		
	}
	}else{
	 $vatable=0;
		$myfinaltax=0;
		$finaltax2=0;
			$vattype="ZERO RATED";
	}
			
			//
			
		$realprice= $finalamount / $number;
				$realprice= $this->formatMoney($realprice, true);

			$data = array(
			

'bedname' => $bedname,
'bedid' => $bedid,


			
					'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
				'houseno' => $houseno,
				'plotno' => $plotno,
				
				'tenantid' => $tenantid,
				'createdat' => $createdat,
				'status' => $status,
				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
				'roomtype' => $finalamount,
			
				'transactioncode' =>$transactioncode,
							
							'chargeid' =>$chargeid,
					'people' =>$people,
				'paymentmode' =>$type,
					'total' => $finalamount,
				'cheque' =>$cheque,
				'points' =>$points,
				'card' =>$card,
				'voucher' =>$voucher,
				'amount' => $amount,
				'mpesa' =>$mpesa,
				'credit' =>$credit,
				'balance' => $clientbalance ,
			'branchid'=>$branchid,
				'number' => $number,
				
				'discount' => $discount,
				'paymentcode' => $paymentcode,
		 	'checkoutdate' => $checkoutdate ,
				
'status' => $status,
				'paymentstatus' => $paymentstatus,
								'currency' => $currency,
								'othercurrency' => $othercurrency,
								'othercurrencyamount' => $othercurrencyamount,
									'tocurrencyamount' => $tocurrencyamount,
										'tocurrencychnage' => $tocurrencychnage,
								
								
								
								
								
								
								
								

			);
			
											$servicedata=array(	


'vattype'=>$vattype,
			'tax2'=>$finaltax2,
			'taxable'=>$vatable,
			'tax' => $myfinaltax,

				'discount'=>$discount,							
			'userid'=>$userid,
			'code'=>$chargeid,
			'sprice' => $realprice,
			'uomqty' => $people,

				'amount' => $finalamount,
				'name'=>$chargeid,
				'qty'=>$number,
				'chargeid'=>$transactioncode,
		  	'plotno'=>$plotno,
						'houseno' => $houseno,
						'invoice' => $transactioncode,
						'myinvoice' => $userid.time(),
	

						'transactioncode' => $transactioncode,
			'companyid' => $companyid,
				'cost' => $realprice,
							'dateposted'=>$createdat,
					'branch'=>$branchid,
			'createdat'=>$createdat,
				'checkin'=>$createdat,
		'checkout' => $checkoutdate ,
		'bedid' => $bedid ,
		'ordersales' => "active" ,
'bedname' => $bedname ,
'status' => $roomstatus ,
					'type'=>"room",
			
								);
							

			
			
			
			if($action=="insert"){
				
						
			if (($checkoutdate<=$createdat))
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The check-out time  ('.$checkoutdate.') can not be the same or less than check-in time ('.$createdat.') . Please try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 
					return false;
			}
					
			if (($this->accomodationmodel->checkbookingdate($plotno,$houseno,$createdat,$checkoutdate))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The room is reserved between  '.$createdat.' and '.$checkoutdate.' hence you can only book before or after reservation date. Please try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 
					return false;
			}

	
			if (($this->accomodationmodel->checkvacancy($plotno,$houseno,$status))==FALSE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error!Room cant be Allocated! . The room is still occupied or reserved or freezed.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 return false;

			}
			
			if($status!="reserved"){
				if($bedid ==""){
			if (($this->accomodationmodel->checkbookingvacancy($plotno,$houseno))==TRUE )
			{	
				//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be Allocated! . The previous customer is still active. Please deactivate the previous tenant first.. </div>');
				 	// redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					// return false;
			}
			}
			}else{

if (($this->accomodationmodel->checkbookingdate($plotno,$houseno,$createdat,$checkoutdate))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The room is reserved between  '.$createdat.' and '.$checkoutdate.' hence you can only book before or after reservation date. Please try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 
					return false;
			}

				}
		
			// insert form data into database
			if ($this->accomodationmodel->insertBooking($data))
			{
				
	$this->usermodel->add($servicedata,'dailycharges');

				
				
				
				
				$accountname=0;
												
										if(($type=="Credit")|| ($type=="Invoice")|| ($type=="Creditnote")){
												
												$accountname=1100;
											}else{
											$accountname=1000;	
											}
				
				
				 $accountnames = $this->usermodel->populatealldataarray('rentalpaymentmethodes','chargeid', $chargeid,'branchid', $branchid);
if(	 $accountnames ==false){
			$myaccountnos= "1000";

}else{
		$myaccountnos= $accountnames[0]['type'];
	
}
//1000

		//$myaccountnos= $accountnames[0]['type'];
	
				if($description==""){
					
					$description="Room sold";
				}else{
					
					$description=$description;
				}
				//
			
			
						$creditdata=array( 'userid'=>$userid,'account'=>$myaccountnos,'credit'=>$finalamount,'description'=>$description,'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $tenantid);
						$this->usermodel->add($creditdata,'debitcredit');

				
				
				

				//$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'debit'=>$finalamount,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>("room No".$houseno."-".$plotno) ,'supplier'=> $tenantid);
							//$this->usermodel->add($debitdata,'debitcredit');


if($activatebank=="yes"){
			//
			
$confirmaccounts = $this->usermodel->populatealldatanoarray('paymentmethodes','branchid', $branchid,'companyid', $companyid);



if(is_array($confirmaccounts)){
		$insertdebitdata= array();
	   foreach($confirmaccounts as $row)
	   {
		
				$mybankname=$row->name;
		      $myaccountno=$row->type;
	
 
  

  
		   if(($mybankname=="cash") && ($cash != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$cash,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
 
		   }
		     if(($mybankname=="mpesa") && ($mpesa != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$mpesa,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
  
				}
		       if(($mybankname=="bank") && ($cheque != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$cheque,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
  
				}
				 if(($mybankname=="card") && ($card != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$card,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
					}

			if(($mybankname=="voucher") && ($voucher != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$voucher,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
					}
			if(($mybankname=="credit") && ($credit != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$credit,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
					}
			
			 if(($mybankname=="points") && ($points != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$points,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
			
					}
			
			
			if(($mybankname=="creditnote") && ($creditnote != 0)){
				$Creditnotetotal=0;
	if($creditnote<0){
			$Creditnotetotal=(-1*$creditnote);

	}else{
			$Creditnotetotal=$creditnote;

	}
				 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'credit'=>$Creditnotetotal,'description'=>"Sales returned",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'creditnote','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
		
					}

	   }
	   
	   	if(!empty($insertdebitdata)){
		$this->db->insert_batch('debitcredit', $insertdebitdata);

							}	
							
						
	   
}
		
			}else{
	
			
									if($type!="Cash"){
				

									$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$finalamount,'description'=>"Room sold expected amount",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);

													
									//$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'debit'=>$finalamount,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>("room No".$houseno."-".$plotno) ,'supplier'=> $tenantid);



									}else{
										
								
									$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$finalamount,'description'=>"Room  sold",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
	//
										
									}
								//$this->usermodel->updatedatabytwo($closedata,'sales_order','invoice',$invoice,'status<>','returned');
							$this->usermodel->add($debitdata,'debitcredit');

								
			}	

				
				
				
				
				
				
				
				
				
				
				if($bedid !=""){
					$beddata=array(
					
	   'status' =>"occupied"
	   );
		$this->usermodel->updatedata($beddata,'beds','id',$bedid);
								
				



				
$myhouserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
$myroomid=$myhouserents[0]['id'];				
$ttbeds=$myhouserents[0]['beds'];				
					
		 $confirmoccupiedrooms = $this->usermodel->GettatalbedsOccupied($myroomid);
	
					
$currentstatus="";
if($ttbeds > 1){

if($confirmoccupiedrooms  >= $ttbeds){	
$currentstatus="occupied";

}else{
$currentstatus="vacant";

}	
}else{
$currentstatus="occupied";

}	

$roomdata=array(
					
	   'status' =>$currentstatus,
	   );
		$this->usermodel->updatedata($roomdata,'house','id',$myroomid);
								
					







					
								
								}else{
									
				$this->accomodationmodel->occupyHouse($plotno,$houseno,$status);
		
								}
				
				
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');
				 	 						$receipt = $this->input->post("receipt");

					 if($sendfeedback=="yes"){
						 
						 	$myview="admin/housereceiptbyno?randomitemidentifier=".$transactioncode;
									  $this->pushroomsms($taskmessage,$contact,$myview);
					 }



if($receipt=="No"){
					$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');

					 	 redirect('admin/viewpallmyplots');

}else if($receipt=="OtherServices"){
redirect('/user/mychangepayment?myid='.$transactioncode);																


}else if($receipt=="OtherGuests"){
//redirect('/user/mychangepaymentmoreguests?myid='.$transactioncode);																
redirect('/user/mychangepayment?myid='.$transactioncode);																


}else if($receipt=="Yes"){



													
if(($type=="Credit")|| ($type=="Invoice")){
 redirect('admin/printhouseinvoice?randomitemidentifier='.$transactioncode);
												
}else{
 redirect('admin/housereceiptbynoold?randomitemidentifier='.$transactioncode);

}
	





}else{
	
	
													
if(($type=="Credit")|| ($type=="Invoice")){
 redirect('admin/printhouseinvoice?randomitemidentifier='.$transactioncode);
												
}else{
 redirect('admin/housereceiptbyno?randomitemidentifier='.$transactioncode);

}
	
	
	
	
	
					 	 redirect('admin/housereceiptbyno?randomitemidentifier='.$transactioncode);

}



			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not added. Please try again </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is updated Successfully ! !!!</div>');
				 	 redirect('admin/printallocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not updated. Please try again </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
	function updatebulkcheckin()
    {
		 $session_data = $this->session->userdata('logged_in');
//
   $number=0;
 	$data['id'] = $session_data['id'];
        
		 			    $ttrooms = $this->input->post("ttrooms");

		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 		  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
		
				   			  //  $tenantid = $this->input->post("tenantid");

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

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

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

	$phone = $this->input->post("phone");
	$checkout = $this->input->post("checkout");
	
		$idno = $this->input->post("idno");		
						$transactiontype = $this->input->post("transactiontype");		
	
						$checkintime = $this->input->post("checkintime");

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


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



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

			$myhouseno = $this->input->post("houseno");
	//
					//$people = "1";
					$currency = $this->input->post("currency");

			
		$plotno = $this->input->post("plotno");
	
		
		
		
		
		
		
		if($transactiontype=="reserved"){
			
				$status = "reserved";
		}else{
			
			$status = "active";	
		}
		//
		 $entrydate = $this->input->post("entrydate");
		
		 
		 		 $checkoutdate = $this->input->post("checkoutdate");
				 
				 		 $myroomtype= $this->input->post("roomtype");
		 	$getroomdetails = explode("==",$myroomtype);
		
								 $roomtype = $getroomdetails[0];		

		$chargeid = $getroomdetails[1];	
						

	 $beds= $this->input->post("bed");
	 
	 
	 

	 
	 
	 
	 
	 
	 if( $beds!=""){
		 
		 
		 	$getbeddetails = explode("==",$beds);
		
		$bedid = $getbeddetails[0];		
		
		$bedname = $getbeddetails[1];	

	 }else{
			
		$bedid ="";		
		
		$bedname = 1;	 
		 
		 
	 }

					
				 	 
				 
				   $finaldate = strtotime(date($checkoutdate));
									$mycurrentdate = strtotime(date($createdat));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
				 
if($days< 1){
	
	$number=1;
}else{
		$number=$days;

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


$createdat=$createdat." ".$checkintime;
			$checkoutdate =$checkoutdate." 10:00:00";	 
			
		 
		// $myroomtype = $this->input->post("roomtype");
		 
		 
		 
		
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 
		 $amount = $this->input->post("amount");
		 $paymentcode = $this->input->post("paymentcode");
		$paymentstatus = $this->input->post("paymentstatus");
 $mpesa = $this->input->post("mpesa");
		$card = $this->input->post("card");
				$voucher = $this->input->post("voucher");

						$credit = $this->input->post("credit");
						$points = $this->input->post("points");
						$cheque = $this->input->post("cheque");
						$paymentmode = $this->input->post("paymentmode");

		$totalamount = $this->input->post("totalamount");
			$group = $this->input->post("group");

		 		//$transactioncode=$this->createRandomPassword();
		$transactioncode = $this->input->post("transactioncode");
		$randomitemidentifier = $this->input->post("randomitemidentifier");

		 		 	//$transactioncode = $userid.time();

		 
		   
		   			    //$tenantid = $this->input->post("tenantid");
						
						
	$tenantcodes = explode(':=',$this->input->post("tenantid"));
  $tenantid = htmlspecialchars(trim($tenantcodes[0]));

 						 $otherdiscount = $this->input->post("maindiscount");

						
						 $maindiscount = $this->input->post("discount");
			$maindiscount = explode(':=',$this->input->post("discount"));

						   $mydisc = htmlspecialchars(trim($maindiscount[0]));
						$disctype = htmlspecialchars(trim($maindiscount[1]));
					
						
						if($disctype=="Percentage"){
							$allthetotalamounts = $this->input->post("totalamount");

							$discount= $this->formatMoney((($mydisc/100)*$allthetotalamounts),true);

							
						}else{
							
							$discount=$mydisc;
						}
						
 			    $people = $this->input->post("ttrooms");

 			    $roomidentifier = $this->input->post("roomidentifier");
				   
			$description = $this->input->post("description");
						
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		//$this->form_validation->set_rules('status', 'status  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/startbulkreservation',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_processbulkpayment') == "bulk")
		 {
			
			 
			   $allhouses=$this->usermodel->populateallarray('house','id', $myhouseno);
			$houseno=$allhouses[0]['houseno'];
			 
			 
			 
			 			 $pax = trim($this->input->post("pax"));
			 
						$neededamount=($roomtype* $number);

//totalamount
			$finalamount=($totalamount);
				//$finalamount=($totalamount-$discount);

//$finalamount=($neededamount);

			
				$paid=$amount+$mpesa+$card+$voucher+$cheque+$points+$credit;
			$balance=$finalamount-$paid;
			$clientbalance=$finalamount-$paid-$credit;
			if($clientbalance > 0){
				$clientbalance =$clientbalance *-1;
			}else{
				$clientbalance =$clientbalance;

			}
		
			
		
			        		$customer = $this->usermodel->populateallarray('people','id',$tenantid);

						//$idno=$customer[0]["idno"];
		
		
	        		$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);
										 $activatebank=$configuration[0]['bankcode'];

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

if($sendfeedback=="yess"){
				$smsowner=$configuration[0]["paymenttypes"];



	
			  		$owner = $this->usermodel->populateallarray('people','id',$smsowner);

						$contact=$owner[0]["phone"];
			//$total_amount=$owner[0]['totalsms'];	
			
						  		$myuser = $this->usermodel->populateallarray('people','id',$userid);

			    $correctime = date("d/m/Y H:ia");
			

	
		 	$taskmessage = "Hi! This is to inform you that room No.". $houseno ." has been sold by ". $myuser[0]['surname'] ." for Ksh.". $amount ." on  ". $correctime .". Kindly login to confirm from the system.Automatic sms.";

						   
					
			
}
			
			
			
			
			
			
		
		
			if($paid<$finalamount){
					//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! This customer with ID NO ('.$idno.') could not be checked in. The expected amount ('.$finalamount.') of the room  can not be less than total money  paid ('.$paid.') by the customer. Try again.. </div>');
	//redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$randomitemidentifier);
					// return false;
			}
			
			
			
			
				if((($mpesa >0)&& ($paymentcode ==""))|| (($card >0)&& ($paymentcode ==""))|| (($cheque >0) && ($paymentcode ==""))){
					//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! You have to enter payment/transaction code for you to continue. Try again.. </div>');
	//redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
					 //return false;
			}
			
		
	
				 $vatable=0;
		$myfinaltax=0;
		
			$display1=$configuration[0]["display1"]; 
			$display2=$configuration[0]["display2"]; 
			
			$houserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
//$roomid=$houserents[0]['id'];

$tax1rate=	$houserents[0]['vat'];	
$tax2rate=$houserents[0]['vat2'];
$vattype="";
	if($display1=="yes"){
		$vattype="VATABLE";
			
	if($display2=="yes"){
//echo $tax_included
	$tax_included=$houserents[0]['vat'];

	
	$tax2rate=$configuration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 //$ttoltaxable=(($sellingprice*$latestqty)/ $mytax2);
	 $ttoltaxable=(($finalamount)/ $mytax2);

	 
	 $myfinaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$vatable= $this->formatMoney($ttoltaxable, true);

	
	
	
	
	
	
	
	

	}else{
	 		 


	$mytax=1+($tax1rate/100); 
	$vatable=($finalamount/$mytax);
	$myfinaltax=(($finalamount-$vatable));
	$finaltax2=0;							
								
								
		
	}
	}else{
	 $vatable=0;
		$myfinaltax=0;
		$finaltax2=0;
			$vattype="ZERO RATED";
	}
			
			//
			
		//echo $finalamount;
		
		
			$data = array(
			

'bedname' => $bedname,
'bedid' => $bedid,


			
					'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
				'houseno' => $houseno,
				'plotno' => $plotno,
				
				'tenantid' => $tenantid,
				'createdat' => $dateposted,
				'status' => $status,
				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
				'roomtype' => $finalamount,
				'total' => $finalamount,
				'transactioncode' =>$transactioncode,
								'card' =>$card,
							'voucher' =>$voucher,
							'chargeid' =>$chargeid,
					'people' =>$people,

				'cheque' =>$cheque,
				'points' =>$points,
				'paymentmode' =>$paymentmode,

				'mpesa' =>$mpesa,
				'credit' =>$credit,
			'branchid'=>$branchid,
				'number' => $number,
				'amount' => $amount,
				'discount' => $discount,
				'paymentcode' => $paymentcode,
				'checkoutdate' => $checkoutdate ,
				'balance' => $clientbalance ,
				'category' => $group,

				'paymentstatus' => $paymentstatus,
								'currency' => $currency,

			);
			
			
			$updatedata = array(
			

'bedname' => $bedname,
'bedid' => $bedid,


			
					'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
				'houseno' => $houseno,
				'plotno' => $plotno,
				
				'tenantid' => $tenantid,
				'createdat' => $dateposted,
				'status' => $status,
				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
				'roomtype' => $finalamount,
				'total' => $finalamount,
				//'transactioncode' =>$transactioncode,
								'card' =>$card,
							'voucher' =>$voucher,
							'chargeid' =>$chargeid,
					'people' =>$people,

				'cheque' =>$cheque,
				'points' =>$points,
				'paymentmode' =>$paymentmode,

				'mpesa' =>$mpesa,
				'credit' =>$credit,
			'branchid'=>$branchid,
				'number' => $number,
				'category' => $group,

				'amount' => $finalamount,
				'discount' => $discount,
				'paymentcode' => $paymentcode,
		 	'checkoutdate' => $checkoutdate ,
				'balance' => $clientbalance ,

				'paymentstatus' => $paymentstatus,
								'currency' => $currency,

			);
			
	$servicedata=array(	

'bedname' => $bedname,
'bedid' => $bedid,
'vattype'=>$vattype,
			'tax2'=>$finaltax2,
			'taxable'=>$vatable,
			'tax' => $myfinaltax,

				'discount'=>$otherdiscount,							
			'userid'=>$userid,
			'code'=>$chargeid,
			'sprice' => $finalamount,
			'uomqty' => $people,

				'amount' => $finalamount,
				'name'=>$chargeid,
				'qty'=>$pax,
			
				'chargeid'=>$transactioncode,
		  	'plotno'=>$plotno,
						'houseno' => $houseno,
						'invoice' => $transactioncode,
						'myinvoice' => $userid.time(),
	

						'transactioncode' => $transactioncode,
			'companyid' => $companyid,
				'cost' => $amount,
							'dateposted'=>$createdat,
					'branch'=>$branchid,
			'createdat'=>$dateposted,
					'type'=>"room",
			
				'checkout'=>$checkout,

				'checkin'=>$createdat,
				'customer'=>$name,
				'idno'=>$idno,
				'phone'=>$phone,
				'ordersales'=>"active",

				
				'status'=>$transactiontype,
			
			
			
			
			
								);
							

			
			
			
			if($action=="insert"){

				
						
			if (($checkoutdate<=$createdat))
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The check-out time  ('.$checkoutdate.') can not be the same or less than check-in time ('.$createdat.') . Please try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 
					return false;
			}
				

	if (($this->accomodationmodel->checkbookingdate($plotno,$houseno,$createdat,$checkoutdate))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The room is reserved between  '.$createdat.' and '.$checkoutdate.' hence you can only book before or after reservation date. Please try again.. </div>');
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
					 
					return false;
			}


				
			if (($this->accomodationmodel->checkbookingdate($plotno,$houseno,$createdat,$checkoutdate))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The room is reserved between  '.$createdat.' and '.$checkoutdate.' hence you can only book before or after reservation date. Please try again.. </div>');
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
					 
					return false;
			}

	
			if (($this->accomodationmodel->checkvacancy($plotno,$houseno,$status))==FALSE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error!Room cant be Allocated! . The room is still occupied or reserved or freezed.. </div>');
				 	// redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					// return false;

			}
			
			if($transactiontype != "reserved"){
			
				if($bedid ==""){
			if (($this->accomodationmodel->checkbookingvacancy($plotno,$houseno))==TRUE )
			{	
			//	$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be Allocated! . The previous customer is still active. Please deactivate the previous tenant first.. </div>');
	//redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
					// return false;
			}
			}
			}else{

if (($this->accomodationmodel->checkbookingdate($plotno,$houseno,$createdat,$checkoutdate))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Room can not be booked! . The room is reserved between  '.$createdat.' and '.$checkoutdate.' hence you can only book before or after reservation date. Please try again.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
					 
					return false;
			}

				}
		
			// insert form data into database
			
			//
			
			
			
$getroomdata= $this->usermodel->populateallarray('bookroom','transactioncode',$transactioncode);
if($getroomdata==false){
	$getreserbvationdata= $this->usermodel->populateallarray('bulkreservation','transactioncode',$transactioncode);


		
		
	
	
	
			$bookingdata = array(
			

'bedname' => $bedname,
'bedid' => $bedid,


			
					'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
				'houseno' => "Group",
				'plotno' => "Group",
				
				'tenantid' => $tenantid,
				'createdat' => $dateposted,
				'status' => $status,
				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
				'roomtype' => $finalamount,
				'total' => $finalamount,
				'transactioncode' =>$transactioncode,
								'card' => $getreserbvationdata[0]['card'],
							'voucher' => $getreserbvationdata[0]['voucher'],
							'chargeid' =>$chargeid,
					'people' =>$people,

				'cheque' => $getreserbvationdata[0]['cheque'],
				'points' => $getreserbvationdata[0]['points'],
				'paymentmode' =>$paymentmode,

				'mpesa' => $getreserbvationdata[0]['mpesa'],
				'credit' => $getreserbvationdata[0]['credit'],
			'branchid'=>$branchid,
				'number' => $number,
				'amount' => $amount,
				'discount' => $discount,
				'paymentcode' => $paymentcode,
				'checkoutdate' => $checkoutdate ,
				'balance' => $clientbalance ,
				'category' => $group,

				'paymentstatus' => $paymentstatus,
								'currency' => $currency,

			);
			
			
	
     
	
	
	
	$result=$this->accomodationmodel->insertBooking($bookingdata);
///
}else{
	
		//$result=$this->accomodationmodel->UpdateBooking($data,$id);
		//$result=$this->usermodel->updatedata($updatedata,'bookroom','transactioncode',$transactioncode);
$result=true;
	
}



			
			if ($result==true)
			{
			 $ttrooms=$getroomdata[0]["people"];
			
		
		
			 $confirmallrooms = $this->usermodel->Gettatalroomsandbeds($transactioncode);;



						   //$confirmlevel= $this->accomodationmodel->confirmsmsconfig($companyid);
			//$tplot=$confirmlevel[0]['plot'];
			
		
			if(($confirmallrooms !="" )&& ($confirmallrooms  >=  trim($people))){
				
				//echo"You have reach a maximum of ".$tplot."plots which was assigned to you. Please contact robiseach ltd";
				
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning!! The customer could not be checked-in!. You have reached a maximum number ('.$ttrooms.') of customers in this group. Adjust the number of customers then  you can add more customers. </div>');
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
				 return false;
			}
				
		
		
		
		
		
		
		
		
				
	$this->usermodel->add($servicedata,'dailycharges');


		 $previousbalance=$getroomdata[0]["total"];
		
		$totalbalance=	$previousbalance+$finalamount;	
		$updaterefund=array(		
		'paymentstatus'=>"Not Cleared",
		'updatedat'=>$dateposted,
		'total'=>$totalbalance,
			'credit'=>($getroomdata[0]["credit"]+$finalamount),
		'balance'=>"-".($getroomdata[0]["credit"]+$finalamount),
		
		);
		
		if($getroomdata !=false){
		$this->usermodel->updatedata($updaterefund,'bookroom','transactioncode',$transactioncode);
					
		}
				
				
				
				$accountname=0;
												
										if(($type=="Credit")|| ($type=="Invoice")|| ($type=="Creditnote")){
												
												$accountname=1100;
											}else{
											$accountname=1000;	
											}
				
				
				 $accountnames = $this->usermodel->populatealldataarray('rentalpaymentmethodes','chargeid', $chargeid,'branchid', $branchid);
if(	 $accountnames ==false){
			$myaccountnos= "1000";

}else{
		$myaccountnos= $accountnames[0]['type'];
	
}
//1000

		//$myaccountnos= $accountnames[0]['type'];
	
				if($description==""){
					
					$description="Room sold";
				}else{
					
					$description=$description;
				}
				//
			
			
						$creditdata=array( 'userid'=>$userid,'account'=>$myaccountnos,'credit'=>$finalamount,'description'=>$description,'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $tenantid);
						$this->usermodel->add($creditdata,'debitcredit');

				
				
				

				//$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'debit'=>$finalamount,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>("room No".$houseno."-".$plotno) ,'supplier'=> $tenantid);
							//$this->usermodel->add($debitdata,'debitcredit');


if($activatebank=="yes"){
			//
			
$confirmaccounts = $this->usermodel->populatealldatanoarray('paymentmethodes','branchid', $branchid,'companyid', $companyid);



if(is_array($confirmaccounts)){
		$insertdebitdata= array();
	   foreach($confirmaccounts as $row)
	   {
		
				$mybankname=$row->name;
		      $myaccountno=$row->type;
	
 
  

  
		   if(($mybankname=="cash") && ($cash != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$cash,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
 
		   }
		     if(($mybankname=="mpesa") && ($mpesa != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$mpesa,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
  
				}
		       if(($mybankname=="bank") && ($cheque != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$cheque,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
  
				}
				 if(($mybankname=="card") && ($card != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$card,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
					}

			if(($mybankname=="voucher") && ($voucher != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$voucher,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
					}
			if(($mybankname=="credit") && ($credit != 0)){
			 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$credit,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
					}
			
			 if(($mybankname=="points") && ($points != 0)){
		 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'debit'=>$points,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
			
					}
			
			
			if(($mybankname=="creditnote") && ($creditnote != 0)){
				$Creditnotetotal=0;
	if($creditnote<0){
			$Creditnotetotal=(-1*$creditnote);

	}else{
			$Creditnotetotal=$creditnote;

	}
				 $insertdebitdata[]=array( 'userid'=>$userid,'account'=>$myaccountno,'credit'=>$Creditnotetotal,'description'=>"Sales returned",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'creditnote','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
		
					}

	   }
	   
	   	if(!empty($insertdebitdata)){
		$this->db->insert_batch('debitcredit', $insertdebitdata);

							}	
							
						
	   
}
		
			}else{
	
			
									if($type!="Cash"){
				

									$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$finalamount,'description'=>"Room sold expected amount",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);

													
									//$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'debit'=>$finalamount,'description'=>"Expected house income",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>("room No".$houseno."-".$plotno) ,'supplier'=> $tenantid);



									}else{
										
								
									$debitdata=array( 'userid'=>$userid,'account'=>$accountname,'debit'=>$finalamount,'description'=>"Room  sold",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$transactioncode ,'supplier'=> $tenantid);
	//
										
									}
								//$this->usermodel->updatedatabytwo($closedata,'sales_order','invoice',$invoice,'status<>','returned');
							$this->usermodel->add($debitdata,'debitcredit');

								
			}	

				
				
				
				
				
				
				
				if($transactiontype !="reserved"){
				
				
				if($bedid !=""){
					$beddata=array(
					
	   'status' =>"occupied"
	   );
		$this->usermodel->updatedata($beddata,'beds','id',$bedid);
								
				



				
$myhouserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
$myroomid=$myhouserents[0]['id'];				
$ttbeds=$myhouserents[0]['beds'];				
					
		 $confirmoccupiedrooms = $this->usermodel->GettatalbedsOccupied($myroomid);
	
					
$currentstatus="";
if($ttbeds > 1){

if($confirmoccupiedrooms  >= $ttbeds){	
$currentstatus="occupied";

}else{
$currentstatus="vacant";

}	
}else{
$currentstatus="occupied";

}	




$roomdata=array(
					
	   'status' =>$currentstatus,
	   );
		$this->usermodel->updatedata($roomdata,'house','id',$myroomid);
								
					







					
								
								}else{
									
				$this->accomodationmodel->occupyHouse($plotno,$houseno,$status);
		
								}
				
				}
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');
				 	 						$receipt = $this->input->post("receipt");

					 if($sendfeedback=="yes"){
						 
						 	$myview="admin/housereceiptbyno?randomitemidentifier=".$transactioncode;
									  $this->pushroomsms($taskmessage,$contact,$myview);
					 }

if($receipt=="No"){
					$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');

					 	 redirect('admin/viewpallmyplots');

}else if($receipt=="Next"){
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);


}else{
	
	
													
if(($paymentmode=="Credit")|| ($paymentmode=="Invoice")){
 redirect('admin/printhouseinvoice?randomitemidentifier='.$transactioncode);
												
}else{
 redirect('admin/housereceiptbyno?randomitemidentifier='.$transactioncode);

}
	
	
	
	
	
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);

}



			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not added. Please try again </div>');
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
			}
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
	
	
	public function checkinreservations() {
   if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
    else {
	
		$session_data = $this->session->userdata('logged_in');

   	$data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    	$data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
 	$data['id'] = $session_data['id'];
         $updatedat = date('Y-m-d H:i:s');

		 $userid = $data['id'];
	 /// $salestype = trim($_GET['salestype']);

	

	  
	  
	  $transactionid = trim($_GET['randomitemidentifier']);
	  $transactioncode = trim($_GET['transactioncode']);
	  $transactiontype = trim($_GET['transactiontype']);
	
		$booking  = $this->usermodel->populateallarray('dailycharges','id', $transactionid);
	  $bedid=$booking[0]['bedid'];
	  $itemid=$booking[0]['id'];
	  
	$houseno=$booking[0]['houseno'];
	$plotno=$booking[0]['plotno'];
	$status="inactive";
	
				$updatedata=array(
					
	   'status' =>"checkin"
	   );
		  $usr_result = $this->usermodel->updatedata($updatedata,'dailycharges','id',$transactionid);
			

	  

	  
					

							//check if username and password is correct
		if ($usr_result ==TRUE) //active user record is present
		{
	
		$this->accomodationmodel->occupyHouse($plotno,$houseno,"occpied");

	
	
	if($bedid !=""){
						$beddata=array(		
			
			'status'=>"active",
			
			);
					
								 $this->usermodel->updatedata($beddata,'beds','id',$bedid);
				
	
$confirmvacantrooms = $this->usermodel->GettatalbedsVacant($myroomid);

$currentstatus="";
if(($ttbeds > 1) && ($ttbeds !="")) {

if($confirmvacantrooms  >= $ttbeds){	
$currentstatus=$status;

}else{
$currentstatus=$originalstatus;

}	
}else{
$currentstatus=$status;

}	
 	}else{
	$currentstatus=$status;
	
		
	}
					
				$bookingdata=array(		
			'userid'=>$userid,
			'status'=>"active",
			'updatedat'=>$updatedat,
			);				
								
								
								
			$mydata=array(		
			'userid'=>$userid,
			'status'=>$currentstatus,
			'updatedat'=>$updatedat,
			);
										
					$datachekoutrooms=array(		
			'userid'=>$userid,
			
				
			
		  	'status'=>'inactive',
			
			 		
			
		
				
			
								); 
							
								
								
								
					
								
							//$usr_result = $this->usermodel->updatedata($datachekout,'bookroom','id',$itemid);
			$this->usermodel->updatedata($datachekoutrooms,'dailycharges','id',$roomidentifier);
								 $this->usermodel->updatedata($mydata,'house','id',$myroomid);

									 $this->usermodel->updatedata($bookingdata,'bookroom','transactioncode',$transactioncode);

	
	
	
	
	$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');

		redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);

			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not added. Please try again </div>');
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode.'&transactiontype='.$transactiontype);
			}
	
	
	
	}
	
	
	}
	
	
	
	
	
	
	
  	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"];

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

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

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

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

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

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

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


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

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

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

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

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

			}
			
			
			


						   
						   
						   
						   
						   
			
							
							//check if username and password is correct
			
					  
	    
    }
  
  
  
  
  
  
  
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function addbulkinvoice()
    {
		  $createdats = Date('Y-m-d H:i:s') ;
	
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	 
		  $data['branchid'] = $session_data['branchid'];
		 	$branchid= $data['branchid'];
	
		//$transactioncode='IN-'.$this->createRandomPassword();
			$duedate = $this->input->post("duedate");
			

		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
				$chargeid = $this->input->post("chargeid");

		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			  
				//$type = trim(strtoupper($this->input->post("type")));
				
			$description = $this->input->post("description");
						
         	$transactioncode=0;
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('month', ' Month', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('duedate', 'Due date  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/bulkhouse',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_invoice') == "invoice")
		 {
							 $plots = $this->accomodationmodel->dispalytenantavailable($plotno);
 
	

$utilities="";
$plotpayments="";

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

   foreach($plots as $plotsrow){

//$plotpayments=$plotsrow->invoicesms;

				//$plotutility=$plotsrow->utility;
				$plotutility="";
	 
				if($chargeid =="all"){
				$utilities="rent and utilities ";
				}else{
										
	   
	   	$housescharge = $this->usermodel->populateallarray('charges','id',$chargeid);

		
		
		
     $chargetype = $housescharge[0]['type'];
	 
	 
				$utilities=$chargetype;

				}


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

   foreach($houserent as $houserentrow){

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

	
   $type="";
      $cost=0;
  $tenantid=$houserentrow->tenantid;
   
   $insertcharges = array();
   		
	
				
				
				
				
						$finalvat=0;
			
			 
			 	   //	$houserents = $this->accomodationmodel->gethousedetails($plotsrow->plotno,$plotsrow->houseno);
								 	   	$houserents = $this->accomodationmodel->gethousedetailsActive($plotsrow->plotno,$plotsrow->houseno);

$roomid=$houserents[0]['id'];


	 if($houserents!=false){


		 $vat=$houserents[0]["vat"];
				$paymentdetails=$houserents[0]["paymentdetails"];
 $houseno="";
  $debitcreditdata=array();


			 
		 if($chargeid =="all"){
	 $charges = $this->accomodationmodel->getplotcharges($plotno,$roomid);
 
				 
			 }else{
				 
	 	 $charges = $this->accomodationmodel->getplotchargesbychargeid($plotno,$roomid,$chargeid);
 
				 
			 }
			 


if(is_array($charges)) {

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


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

								 								$finalvat=0; 

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

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

			 $insertcharges[]=array(	
						  
               	'vat' => $finalvat,
				 'chargeid' =>$charges->name,

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

if(!empty($insertcharges)){

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

}else{
 $usr_result =0;
	
}







}



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


								'companyid' => $companyid,

				'description' => $description
			);

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

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

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


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

				

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

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



			$invoicelink= base_url()."printinvoicehouse?refnumber=".$transactioncode;

						$receiptlink= base_url()."pintreceipthouse?refnumber=".$transactioncode;



			 
		 if($chargeid =="all"){
		 	//$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". Your total balance is now Ksh.". ($totalinvoice+$currentuserbalance) ." . Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments;
 				$taskmessage = "Dear ". $users[0]['firstname'] ."!You have been invoiced Ksh.". $totalinvoice ." for ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". Your previous balance is: ".$currentuserbalance.". Your total balance is now Ksh.". (($totalinvoice+$currentuserbalance)-$myhouserent[0]["overpayment"]) ." . Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments.".Click here to view your invoice. ".$invoicelink;

				 
			 }else{
				 
		 	$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". ".$paymentdetails.".".$plotpayments;
  				$taskmessage = "Dear ". $users[0]['firstname'] ."!You have been invoiced Ksh.". $totalinvoice ." for ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". Your previous balance is: ".$currentuserbalance.". Your total balance is now Ksh.". (($totalinvoice+$currentuserbalance)-$myhouserent[0]["overpayment"]) ." . Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments.".Click here to view your invoice. ".$invoicelink;

				 		 //	$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments;

			 }

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

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








						
		
		}
		
		
		}
		
	}
}


}


}

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

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


} else {
      echo "That plot has no house";
}
			 
			 
			
			
		}else
			{
				// error
				 redirect('admin');
			}
		
	}
	
	}
	
	
	
	
	function expenditure()
    {
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		$transactioncode='EXP-'.$this->createRandomPassword();
			
				

		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $approvedby = $this->input->post("approvedby");
				   $amount = $this->input->post("amount");
				   $type = $this->input->post("type");
				
			$description = $this->input->post("description");
						
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allexpenditure',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_expenditure') == "expenditure")
		 {
			
			$data = array(
				'houseno' => $houseno,
				'plotno' => $plotno,
				'type' => $type,
				'approvedby' => $approvedby,
				'paymentstatus' =>'expenditure',
				'createdat' => $createdat,
				'amount' => $amount,
				
				'transactioncode' => $transactioncode,
				'month' => $month,
				'year' => $year,
				
				'description' => $description
			);
			
			
			if($action=="insert"){
				
			
			// insert form data into database
			if ($this->accomodationmodel->insertExpenditure($data))
			{
			$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Expenditure is added Successfully ! !!!</div>');
					 redirect('admin/viewexpenditure');	
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Expenditure not added. Please try again </div>');
				 redirect('admin/viewexpenditure');
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Invoice is updated Successfully ! !!!</div>');
					 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Invoice not updated. Please try again </div>');
				 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	    
  public function overpayment() {

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
    
	$data['payment'] = $this->accomodationmodel->populateoverpayment($companyid);

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

		
				$this->load->view('pmsdata/overpayment',$data);
		$this->load->view("template/footerpage");
	
  }
  
  
  
  
  function savebulkreservation()
    {
		$session_data = $this->session->userdata('logged_in');

   //
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
		 $paymentid = trim($this->input->post("paymentid"));


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

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


		$group = $this->input->post("group");
					$originalamount = $this->input->post("originalamount");

			$ttrooms = $this->input->post("ttrooms");
		   
		$paymentmode = $this->input->post("paymentmode");
	
         			$paymentcode = trim($this->input->post("paymentcode"));
			$description = $this->input->post("description");

		 	    $checkout = $this->input->post("checkout");
			 $checkin = $this->input->post("checkin");

		 	    $tenantid = $this->input->post("tenantid");
		 	    $discount = $this->input->post("discount");
		 	    $createdat = $this->input->post("checkin");

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

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

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





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

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

					$people = $this->input->post("people");
					$currency = $this->input->post("currency");
					$plotno = $this->input->post("plotno");

			
		$plotno = "bulk";
		$status = $this->input->post("status");
		 $entrydate = $this->input->post("entrydate");
				 $paymentmode = $this->input->post("paymentmode");

		 
		 		 $checkoutdate = $this->input->post("checkout");
				 
				 		 $myroomtype= $this->input->post("roomtype");
		 			
		
		$chargeid = "bulk";	
												
				 	 
				 
				   $finaldate = strtotime(date($checkoutdate));
									$mycurrentdate = strtotime(date($createdat));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
				 
if($days< 1){
	
	$number=1;
}else{
		$number=$days;

}

$createdat=$createdat." ".$mytime=date("H:i:s");



			 $checkoutdate =$checkoutdate." 10:00:00";	 
		
		 
		 $myroomtype = $this->input->post("roomtype");
		 
		 
		 
		
		 
		 
		 
		 
		 
		 
		 
		 		 						$phone = $this->input->post("phone");
		 		 						$duedate = $this->input->post("duedate");

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

		 $amount = $this->input->post("amount");
		 $paymentcode = $this->input->post("paymentcode");
		$paymentstatus = $this->input->post("paymentstatus");
 $mpesa = $this->input->post("mpesa");
		$card = $this->input->post("card");
				$voucher = $this->input->post("voucher");
						$receipt = $this->input->post("receipt");

						//$credit = $this->input->post("credit");
						$points = $this->input->post("points");
						$cheque = $this->input->post("cheque");

								$totalamount = $this->input->post("totalamount");
							$credit = $this->input->post("originalamount");

		 		//$transactioncode=$this->createRandomPassword();

		 		 	$transactioncode = $userid.time();

		 
		   
		   			    //$tenantid = $this->input->post("tenantid");
						
						
	$tenantcodes = explode(':=',$this->input->post("tenantid"));
  $tenantid = htmlspecialchars(trim($tenantcodes[0]));

 
						
						 $maindiscount = $this->input->post("discount");
			$maindiscount = explode(':=',$this->input->post("discount"));

						   $mydisc = htmlspecialchars(trim($maindiscount[0]));
							 $disctype = htmlspecialchars(trim($maindiscount[1]));
					
						
						if($disctype=="Percentage"){
							$allthetotalamounts = $this->input->post("totalamount");

							$discount= $this->formatMoney((($mydisc/100)*$allthetotalamounts),true);

							
						}else{
							
							$discount=$mydisc;
						}
						

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

		
			//insert the user registration details into database
						if ($this->input->post('btn_bulksavereservation') == "reservation")
						 {
											$data['paymentcode'] = $paymentcode;				

				     	$data['checkin'] = $checkin;
			     	$data['checkout'] = $checkout;

     	$data['ttrooms'] = $ttrooms;
		$data['group'] = $group;
		$data['paymentmode'] = $paymentmode;
		$data['originalamount'] = $originalamount;
				$data['paymentid'] = $paymentid;
							$data['description'] = $description;
				
											$data['discount'] = $discount;

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


			//$finalamount=($totalamount-$discount);
				$finalamount=($originalamount-$discount);

				$paid=$amount+$mpesa+$card+$voucher+$cheque+$points+$credit;
			$balance=$finalamount-$paid;
			$clientbalance=$finalamount-$paid-$credit;
			if($clientbalance > 0){
				$clientbalance =$clientbalance *-1;
			}else{
				$clientbalance =$clientbalance;

			}
			//
			$data['methode'] = $this->usermodel->populatealldatanoarray('glaccounts','companyid',$companyid,'accounttype','1');


		//$this->load->view("template/headerpagemin");
		
		// $this->load->view("template/tableheader");
				$data['myinvoice'] = true;
	$data['tenantid'] = $tenantid;

				
					
			
			
			
			
			
		
		
			if($paid<$finalamount){
					$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! This customer / Company could not be checked in. The expected amount ('.$finalamount.') of the room  can not be less than total money  paid ('.$paid.') by the customer. Try again.. </div>');
				 	
				 
	$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				$data['myinvoice'] = true;


				$this->load->view('pmsdata/startbulkreservation',$data);
					
					return false;
			}
			
			
			
			
				if((($mpesa >0)&& ($paymentcode ==""))|| (($card >0)&& ($paymentcode ==""))|| (($cheque >0) && ($paymentcode ==""))){
					$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! You have to enter payment/transaction code for you to continue. Try again.. </div>');
				 								$data['paymentcode'] = $paymentcode;				

				 
	$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				$data['myinvoice'] = true;


				$this->load->view('pmsdata/startbulkcheckin',$data);
					
					return false;
					
			}
			
	
	
				 $vatable=0;
		$myfinaltax=0;
		
			$display1=$configuration[0]["display1"]; 
			$display2=$configuration[0]["display2"]; 
			
			//$houserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
//$roomid=$houserents[0]['id'];

$tax_included=	$configuration[0]['tax1rate'];	
$tax2rate=$configuration[0]['tax2rate'];
$tax1rate=	$configuration[0]['tax1rate'];	

	if($display1=="yes"){
		
			
	if($display2=="yes"){
//echo $tax_included
		//$tax_included=$houserents[0]['vat'];

	
	$tax2rate=$configuration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 //$ttoltaxable=(($sellingprice*$latestqty)/ $mytax2);
	 $ttoltaxable=(($finalamount)/ $mytax2);

	 
	 $myfinaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$vatable= $this->formatMoney($ttoltaxable, true);

	
	
	
	
	
	
	

	}else{
	 		 


	$mytax=1+($tax1rate/100); 
	$vatable=($finalamount/$mytax);
	$myfinaltax=(($finalamount-$vatable));
	$finaltax2=0;							
								
								
		
	}
	}else{
	 $vatable=0;
		$myfinaltax=0;
		$finaltax2=0;
	}
				
				
					if($salestype=="reserve"){
				$mysatus ="new";	

			}else{
				$mysatus ="active";	

				
				
				}
			
				
			$data = array(
			//
								'paymentmode' => $paymentmode,
				'category' => $group,

					'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
				'houseno' => "Group",
				'plotno' => "Group",
				
				'tenantid' => $tenantid,
				'createdat' => $createdat,
				'status' => $mysatus,
				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
				'roomtype' => $finalamount,
				'total' => $finalamount,
				'transactioncode' =>$transactioncode,
								'card' =>$card,
							'voucher' =>$voucher,
							'chargeid' =>$chargeid,
							'branchid' =>$branchid,
					'people' =>$ttrooms,

				'cheque' =>$cheque,
				'points' =>$points,

				'mpesa' =>$mpesa,
				'credit' =>$credit,


				'number' => $ttrooms,
				'amount' => $amount,
				'discount' => $discount,
				'paymentcode' => $paymentcode,
					'checkoutdate' => $checkoutdate ,
				'balance' => $clientbalance ,
//abunaaaa
				'paymentstatus' =>$paymentstatus,
								'currency' => $currency,

			);
			
			
			$result="";
			if($salestype=="reserve"){
				$result =	$this->usermodel->add($data,'bulkreservation');

			}else{
				$result =	$this->usermodel->add($data,'bookroom');

				
				
				}
						
				
				if($result==true){	
			 
			  $dateposted = date('Y-m-d H:i:s');
			 
			 if($receipt=="Next"){
				 
    
	

$getiddata= $this->usermodel->populateallarray('bulkreservation','transactioncode',$transactioncode);

$randomitemidentifierid=$getiddata[0]["id"];
	redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode);
		 
				 
				 
				 
			 }else{
					 $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 done bulk reservation..</div>');	
				 	 
					// redirect("admin/viewbulkreservation");
			
		redirect('admin/viewbalance?invoice='.$transactioncode);	

			//redirect('admin/viewbulkreservation?dateposted='.$dateposted);
	
			 }
			 
			 
			 
			 
				
			//
			
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not added. Please try again </div>');
				 	 redirect("admin/bukreservation");
			}
				
				
				
				
				
				
				
				
				
				
				$this->load->view('pmsdata/startbulkcheckin',$data);
						 
}
  
  
	}
  
  
  
   public function verifybulkreservationcheckin() {
		
		if (!isset($_GET['randomitemidentifier'])){

    
      show_error('No identifier provided', 500);
    }
   else {
    
	
	  
	 $transactioncode = $_GET['randomitemidentifier'];
	
		if(isset($_GET['transactiontype'])){
		     $transactiontype = $_GET['transactiontype'];
	
			
		}else{
			
			     $transactiontype = "checkin";

		}
		
		
		
		
		
		
		
		



$getroomdata= $this->usermodel->populateallarray('bookroom','transactioncode',$transactioncode);


if($getroomdata==false){
		$configuration= $this->usermodel->populateallarray('bulkreservation','transactioncode',$transactioncode);
					$data['tenantid'] =$configuration[0]["tenantid"];				

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

$data['myid'] =$configuration[0]["id"];


}else{
	
	
$configuration=$getroomdata;
	
	
}






					$data['transactiontype'] =$transactiontype;				


					$data['transactioncode'] =$configuration[0]["transactioncode"];				

					$data['paymentcode'] =$configuration[0]["paymentcode"];				

				     	$data['checkin'] = $configuration[0]["createdat"];
			     	$data['checkout'] = $configuration[0]["checkoutdate"];
			     	$data['companyid'] = $configuration[0]["companyid"];

     	$data['ttrooms'] = $configuration[0]["people"];
		$data['plotno'] = $configuration[0]["plotno"];
				$data['houseno'] = $configuration[0]["houseno"];

		$data['paymentmode'] = $configuration[0]["paymentmode"];
		$data['originalamount'] = $configuration[0]["total"];
				$data['paymentid'] = "";
							$data['description'] = $configuration[0]["description"];
				
				
						$data['discount'] =$configuration[0]["discount"];
						$data['group'] =$configuration[0]["category"];
$data['credit'] =$configuration[0]["credit"];
				$data['cash'] =$configuration[0]["amount"];
						$data['mpesa'] =$configuration[0]["mpesa"];
			$data['methode'] = $this->usermodel->populatealldatanoarray('glaccounts','companyid',$configuration[0]["companyid"],'accounttype','1');

					$data['booking'] = $this->usermodel->populateall('dailycharges', 'transactioncode',$configuration[0]["transactioncode"]);











		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				$data['myinvoice'] = true;
	$data['tenantid'] = $configuration[0]["tenantid"];

	$this->load->view('pmsdata/startbulkcheckinreservation',$data);
		}
 
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
		 $paymentid = trim($this->input->post("paymentid"));


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

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

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

		$group = $this->input->post("group");
		
			$ttrooms = $this->input->post("ttrooms");
		   
		$paymentmode = $this->input->post("paymentmode");
	
         			$paymentcode = trim($this->input->post("paymentcode"));
			$description = $this->input->post("description");

		 	    $checkout = $this->input->post("checkout");
						 	    $checkin = $this->input->post("checkin");

		 	    $tenantid = $this->input->post("tenantid");
		 	    $discount = $this->input->post("discount");
		 	    $createdat = $this->input->post("checkin");

			

		
			//insert the user registration details into database
						if ($this->input->post('btn_processbulkpayment') == "process")
						 {
											$data['paymentcode'] = $paymentcode;				

				     	$data['checkin'] = $checkin;
			     	$data['checkout'] = $checkout;

     	$data['ttrooms'] = $ttrooms;
		$data['group'] = $group;
		$data['paymentmode'] = $paymentmode;
		$data['originalamount'] = $originalamount;
				$data['paymentid'] = $paymentid;
							$data['description'] = $description;
				
											$data['discount'] = $discount;

		
			$data['methode'] = $this->usermodel->populatealldatanoarray('glaccounts','companyid',$companyid,'accounttype','1');


		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				$data['myinvoice'] = true;
	$data['tenantid'] = $tenantid;

				$this->load->view('pmsdata/startbulkcheckin',$data);
						 }
						 else if ($this->input->post('btn_processbulkpayment') == "bulk")
						 {
//

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

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

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



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


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

		
						 $myhouseno = $this->input->post("houseno");

					$people = $this->input->post("people");
					$currency = $this->input->post("currency");
					$plotno = $this->input->post("plotno");
					$bed = $this->input->post("bed");



  $allhouses=$this->usermodel->populateallarray('house','id', $myhouseno);
			$houseno=$allhouses[0]['houseno'];


 $myroomtype= $this->input->post("roomtype");
		 	$getroomdetails = explode("==",$myroomtype);
		
		$roomtype = $getroomdetails[0];		
		
		$chargeid = $getroomdetails[1];	








		
		
		$status = $this->input->post("status");
		 $entrydate = $this->input->post("entrydate");
		
		 
		 		 $checkoutdate = $this->input->post("checkout");
				 
				 		 $myroomtype= $this->input->post("roomtype");
		 			
		
		///$chargeid = "bulk";	
												
				 	 
				 
				   $finaldate = strtotime(date($checkoutdate));
									$mycurrentdate = strtotime(date($createdat));

									$secs = $finaldate - $mycurrentdate;// == <seconds between the two times>
									$days = $secs / 86400;
				 
if($days< 1){
	
	$number=1;
}else{
		$number=$days;

}

$createdat=$createdat." ".$mytime=date("H:i:s");



			$checkoutdate =$checkoutdate." 10:00:00";	 
			
		 
		 $myroomtype = $this->input->post("roomtype");
		 
		 
		 
		
		 
		 
		 
		 
		 
		 
		 
		 		 						$phone = $this->input->post("phone");
		 		 						$duedate = $this->input->post("duedate");

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

		 $amount = $this->input->post("amount");
		 $paymentcode = $this->input->post("paymentcode");
		$paymentstatus = $this->input->post("paymentstatus");
 $mpesa = $this->input->post("mpesa");
		$card = $this->input->post("card");
				$voucher = $this->input->post("voucher");
						$receipt = $this->input->post("receipt");
						$myidno = $this->input->post("idno");

						$credit = $this->input->post("credit");
						$points = $this->input->post("points");
						$cheque = $this->input->post("cheque");

								$totalamount = $this->input->post("totalamount");
	
		 		//$transactioncode=$this->createRandomPassword();

		 		 	//$transactioncode = $userid.time();

		 
		   
		   			    //$tenantid = $this->input->post("tenantid");
						
						
	$tenantcodes = explode(':=',$this->input->post("tenantid"));
  $tenantid = htmlspecialchars(trim($tenantcodes[0]));

 
						
						 $maindiscount = $this->input->post("discount");
			$maindiscount = explode(':=',$this->input->post("discount"));

						   $mydisc = htmlspecialchars(trim($maindiscount[0]));
							 $disctype = htmlspecialchars(trim($maindiscount[1]));
					
						
						if($disctype=="Percentage"){
							$allthetotalamounts = $this->input->post("totalamount");

							$discount= $this->formatMoney((($mydisc/100)*$allthetotalamounts),true);

							
						}else{
							
							$discount=$mydisc;
						}
						

 			    $roomidentifier = $this->input->post("roomidentifier");
				   
			$description = $this->input->post("description");
						
         	
		  	
		$this->form_validation->set_rules('tenantid', 'Customer Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');

			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/startbulkcheckin',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		
		 if ($this->input->post('btn_processbulkpayment') == "bulk"){
 

			 
						//$neededamount=($roomtype* $number);
								$originalamount = $this->input->post("originalamount");




			//$finalamount=($totalamount-$discount);
				$finalamount=($originalamount-$discount);

			$paid=$amount+$mpesa+$card+$voucher+$cheque+$points+$credit;
			$balance=$finalamount-$paid;
			$clientbalance=$finalamount-$paid-$credit;
			if($clientbalance > 0){
				$clientbalance =$clientbalance *-1;
			}else{
				$clientbalance =$clientbalance;

			}
		
		
			        		$customer = $this->usermodel->populateallarray('people','id',$tenantid);

						$idno=$customer[0]["idno"];
		
		
	        		$configuration= $this->usermodel->populateallarray('smsconfig','id',$companyid);

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

if($sendfeedback=="yes"){
				$smsowner=$configuration[0]["paymenttypes"];



	
			  		$owner = $this->usermodel->populateallarray('people','id',$smsowner);

						$contact=$owner[0]["phone"];
			//$total_amount=$owner[0]['totalsms'];	
			
						  		$myuser = $this->usermodel->populateallarray('people','id',$userid);

			    $correctime = date("d/m/Y H:ia");
			

	
		 	$taskmessage = "Hi! This is to inform you that ". count($houseno) ." rooms has been sold by ". $myuser[0]['surname'] ." for Ksh.". $amount ." on  ". $correctime .". Kindly login to confirm from the system.Automatic sms.";

						   
					
			
}
			
			
			
			
			
			
		
		
			if($paid<$finalamount){
					$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! This customer with ID NO ('.$idno.') could not be checked in. The expected amount ('.$finalamount.') of the room  can not be less than total money  paid ('.$paid.') by the customer. Try again.. </div>');
				 	
				 
	$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				$data['myinvoice'] = true;


				$this->load->view('pmsdata/startbulkcheckin',$data);
					
					return false;
			}
			
			
			
			
				if((($mpesa >0)&& ($paymentcode ==""))|| (($card >0)&& ($paymentcode ==""))|| (($cheque >0) && ($paymentcode ==""))){
					$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Warning! You have to enter payment/transaction code for you to continue. Try again.. </div>');
				 								$data['paymentcode'] = $paymentcode;				

				 
	$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
				$data['myinvoice'] = true;


				$this->load->view('pmsdata/startbulkcheckin',$data);
					
					return false;
					
			}
			
		
	
				 $vatable=0;
		$myfinaltax=0;
		
			$display1=$configuration[0]["display1"]; 
			$display2=$configuration[0]["display2"]; 
			
			//$houserents = $this->accomodationmodel->gethousedetails($plotno,$houseno);
//$roomid=$houserents[0]['id'];

$tax1rate=	$configuration[0]['tax1rate'];	
$tax2rate=$configuration[0]['tax2rate'];

	if($display1=="yes"){
		
			
	if($display2=="yes"){
//echo $tax_included
	$tax_included=$configuration[0]['tax1rate'];


	$tax2rate=$configuration[0]["tax2rate"]; 
	 $mytax2=1+(($tax2rate+$tax_included)/100); 
	 //$ttoltaxable=(($sellingprice*$latestqty)/ $mytax2);
	 $ttoltaxable=(($finalamount)/ $mytax2);

	 
	 $myfinaltax= $this->formatMoney(($ttoltaxable*($tax_included/100)), true);


	$finaltax2= $this->formatMoney(($ttoltaxable*($tax2rate/100)), true);
	$vatable= $this->formatMoney($ttoltaxable, true);

	









	}else{
	 		 


	$mytax=1+($tax1rate/100); 
	$vatable=($finalamount/$mytax);
	$myfinaltax=(($finalamount-$vatable));
	$finaltax2=0;							
								
								
		
	}
	}else{
	 $vatable=0;
		$myfinaltax=0;
		$finaltax2=0;
	}
			
			
			
					 $counter =count((array) $name);
				
			   for($b=0; $b< $counter; $b++) {
		$ourhouseno = explode(':=',($this->input->post("houseno")[$b]));

				 	$myhousenos = htmlspecialchars(trim($ourhouseno[0]));
						   
					$myplots = htmlspecialchars(trim($ourhouseno[1]));

					$ourhouseids = explode('xxxx',($myplots));
					 $myplotnos = htmlspecialchars(trim($ourhouseids[0]));
					$ROOMIDS= htmlspecialchars(trim($ourhouseids[1]));
												
	

	   	if (($this->accomodationmodel->checkbookoccupancy($myhousenos,$myplotnos))==true )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error!Room cant be Allocated! . The room is still occupied or reserved or freezed.. </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno[$b].'&randomitemidentifier1='.$plotno[$b].'&roomidentifier='.$roomidentifier);
					 return false;

			}
			
				
				
			   }
			
				 	$dailydata[]=array(			


//'vattype'=>$vattype,
			//'tax2'=>$finaltax2,
			//'taxable'=>$vatable,
			//'tax' => $myfinaltax,

											
			'userid'=>$userid,
			'code'=>$chargeid,
			'sprice' => $finalamount,
		//	'uomqty' => $people,

				'amount' => $finalamount,
				'name'=>$chargeid,
				'qty'=>$number,
				'chargeid'=>$transactioncode,
		  	'plotno'=>$plotno,
						//'houseno' => $houseno,
						'invoice' => $transactioncode,
						'myinvoice' => $userid.time(),
	

						'transactioncode' => $transactioncode,
			'companyid' => $companyid,
				'cost' => $amount,
							'dateposted'=>$createdat,
					'branch'=>$branchid,
			'createdat'=>$createdat,
					'type'=>"room",
			
								);
														
									
			
			$data = array(
			//
					'vatable' => $vatable,
				'tax1' => $myfinaltax,
				'tax2' => $finaltax2,
				'houseno' => "Group",
				'plotno' => "Group",
				'category' => $group,

				'tenantid' => $tenantid,
				'createdat' => $createdat,
				'status' => "active",
				'description' => $description,
				'companyid' => $companyid,
				'userid' => $userid,
				'roomtype' => $finalamount,
				'total' => $finalamount,
				'transactioncode' =>$transactioncode,
								'card' =>$card,
							'voucher' =>$voucher,
							'chargeid' =>$chargeid,
							'branchid' =>$branchid,
					'people' =>$counter,

				'cheque' =>$cheque,
				'points' =>$points,

				'mpesa' =>$mpesa,
				'credit' =>$credit,


				'number' => $counter,
				'amount' => $amount,
				'discount' => $discount,
				'paymentcode' => $paymentcode,
					'checkoutdate' => $checkoutdate ,
				'balance' => $clientbalance ,

				'paymentstatus' =>"Cleared",
								'currency' => $currency,

			);
			
			
		
			
			
			
			
			
			
			
			
			if($action=="insert"){
				
						
	
	
		
			
			// insert form data into database
			if ($this->accomodationmodel->insertBooking($data))
			{
				
				
						 $counter =count((array) $name);
				$insertdata = array();
								$updatedata = array();

			   for($C=0; $C< $counter; $C++) {
					 $ourhouseno = explode(':=',($this->input->post("houseno")[$C]));

				$myhousenos = htmlspecialchars(trim($ourhouseno[0]));
					   
						   
					$myplots = htmlspecialchars(trim($ourhouseno[1]));

					$ourhouseids = explode('xxxx',($myplots));
					 $myplotnos = htmlspecialchars(trim($ourhouseids[0]));
					$ROOMIDS= htmlspecialchars(trim($ourhouseids[1]));
							
							
				
				
					$getroomdetails = explode("==",$myroomtype[$C]);
		
								$ourroomtype = $getroomdetails[0];
								$chargeid = $getroomdetails[1];
								
								if($myhousenos != "na"){
	$finalstatus="occupied";
	
		$updatedata[]=array(
	 'status'=>"occupied",
				 'id'=>$ROOMIDS,


											);
											
											
	  	$insertdata[]=array(		
						
				 	'userid'=>$userid,
							 	'code'=>$chargeid,

				'houseno'=>$myhousenos,
				'plotno'=>$myplotnos,
				'checkin'=>$createdat,
				'amount'=>$ourroomtype,
				'customer'=>$name[$C],
				'idno'=>$myidno[$C],
				'phone'=>$phone,
				'type'=>"room",
				'sprice'=>$ourroomtype,
				'qty'=>1,
				'transactioncode' =>$transactioncode,
				'invoice' =>$transactioncode,

				'checkout'=>$duedate[$C],
				'branch'=>$branchid,
				'discount'=>$maindiscount[$C],

				 'amount'=>"0.00",
				'myinvoice' => $userid.time()+$C,
				 'companyid'=>$companyid,
				 'createdat'=>$createdat,


											);
											
											
									
											
											
											
											
											
											
											
											
											
											
				
				
			   }
				
			}
			
			   $this->db->insert_batch('dailycharges', $insertdata); 
	
				
				
				       if($this->db->affected_rows() > 0){

				$this->db->update_batch('house',$updatedata, 'id');
							   //$this->db->insert_batch('dailycharges', $dailydata); 

				
					   }
				
				
				
				
				
				
				
				//$this->accomodationmodel->occupyHouse($plotno,$houseno,$status);
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');
				 	 						$receipt = $this->input->post("receipt");

					 if($sendfeedback=="yes"){
						 
						 	$myview="admin/housereceiptbyno?randomitemidentifier=".$transactioncode;
									  $this->pushroomsms($taskmessage,$contact,$myview);
					 }



/*
if($receipt=="No"){
					$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is done Successfully ! !!!</div>');

					 	 redirect('admin/viewpallmyplots');

}else if($receipt=="OtherServices"){
redirect('/user/mychangepayment?myid='.$transactioncode);																


}else{

													
if(trim($paymentmode) =="Invoice"){
 
redirect('admin/printhouseinvoice?randomitemidentifier='.$transactioncode);
												
}else{
 redirect('admin/housereceiptbyno?randomitemidentifier='.$transactioncode);

}
	
}
*/
 redirect('admin/verifybulkreservationcheckin?randomitemidentifier='.$transactioncode);


			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not added. Please try again </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Booking is updated Successfully ! !!!</div>');
				 	 redirect('admin/printallocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Booking not updated. Please try again </div>');
				 	 redirect('admin/allocate?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
		 
						
  
	}
  
  function verifyinvoice()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	   $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
	 
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
		 $paymentid = trim($this->input->post("paymentid"));


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


		$plotno = $this->input->post("plotno");
		
			$houseno = $this->input->post("houseno");
		   
		$paymentmode = $this->input->post("paymentmode");
	
         			$paymentcode = trim($this->input->post("paymentcode"));
			$description = $this->input->post("description");

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

		$data['category']=$category;

		
			//insert the user registration details into database
						if ($this->input->post('btn_processpayment') == "process")
						 {
											$data['paymentcode'] = $paymentcode;				

							
				$data['houseno'] = $houseno;				
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		$data['paymentmode'] = $paymentmode;
		$data['originalamount'] = $originalamount;
				$data['paymentid'] = $paymentid;
							$data['description'] = $description;
				
				
			$data['invoice'] = $this->accomodationmodel->gethouseinvoicewithbalance($plotno,$houseno,$tenantid);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
$data['payment'] = $this->accomodationmodel->getmyhousepayment($plotno,$houseno,$tenantid);
	$data['myinvoice'] = $this->accomodationmodel->gethouserentinvoicewithbalance($plotno,$houseno);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
			//$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
			$data['methode'] = $this->usermodel->populatealldatanoarray('glaccounts','companyid',$companyid,'accounttype','1');


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

				$this->load->view('pmsdata/receivepayment',$data);
						 }else if ($this->input->post('btn_postpayment') == "postpayment")
						 {	











	
					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 = $this->input->post("description");
					

$mypaymentmode = $this->input->post("paymentmode");
					
				
				
				 	 $mytotalinvoice=0;
						$counter =count((array) $invoiceid);
			   for($b=0; $b< $counter; $b++) {
	   
	   
	   
	   	 $mytotalinvoice=$mytotalinvoice+$amount[$b];	
				
				
			   }


		if($mytotalinvoice !=$originalamount){
			   
		  
		   
		   	//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error. The total amount entered ('.$originalamount.') is not equal to total money distributed ('.$mytotalinvoice.'). Try again </div>');
				// redirect('admin/receivepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
				 	//return false;
					 }		
				
				
				
					$finaloverpayemnt=0;
					if($overpayment>0){
						
							$finaloverpayemnt=$overpayment;
					}else{
							$finaloverpayemnt=0;
					}
					
					
					
										$users = $this->usermodel->populateallarray('people','id', $tenantid);
										$currentuserbalance=$users[0]['balance'];
																	$contact=$users[0]['phone'];
								
								
								
								
								
									$houserent = $this->accomodationmodel->getbookingbytenant($plotno,$houseno);
									$rentalid=$houserent[0]["id"];
										$prvioushousebalance=$houserent[0]["totalamount"];
									$CURRENTOVERPAYMENTMADE=$houserent[0]["overpayment"];
															 $totalinvoice=0;

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

			  
							 $finalvat=0;
							 	 $finalcommission=0;

						$plotdatils = $this->accomodationmodel->getplotid($plotno);

			$receiptsms="";
			$plotpayments="";	
				

				///$paymentdetails=$vatdetails[0]["paymentdetails"];
		
				$receiptsms=$plotdatils[0]["receiptsms"];
				$plotutility=$plotdatils[0]["utility"];
				$utilities="";
				if($plotutility=="no"){
				$utilities="";
				}else{
				$utilities="/ utilities";

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


								'companyid' => $companyid,

				'description' => $description
			);

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

			$count =count((array) $invoiceid);

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

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

							 }else{
								 
															 	 $finalcommission=0;


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

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

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

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

									
								}
								
			
						

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


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

						
												$this->usermodel->updatemember($peopledta,$tenantid) ;
								
									$ttbalance=($prvioushousebalance-$totalinvoice);
							
						$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'credit'=>$originalamount,'description'=>"Expected  income paid",'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$houseno ,'supplier'=> $tenantid,'transactioncode'=> $paymentcode);
							$this->usermodel->add($debitdata,'debitcredit');

							$salesdata=array( 'userid'=>$userid,'account'=>$paymentmode,'debit'=>$originalamount,'description'=>$description,'code'=>$transactioncode,'crateddate'=>$createdat,'branch' => $branchid,'companyid'=> $companyid,'type'=>'sales' ,'supplier'=> $tenantid,'transactioncode'=> $paymentcode);
						 $this->usermodel->add($salesdata,'debitcredit');

		
								
							
								
										if($originalamount>0){
								
			   $correctime = date("d/m/Y", strtotime($createdat));

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


									$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);
							
							
							}
			
			
			
			
							
						
		
	
	
 }else
							{
								// error
								 redirect('admin');
							}
	}
	
  
  
  
	
	function addbulkpenaltyinvoice()
    {
		
		
		
		$session_data = $this->session->userdata('logged_in');

    $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
 $data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
        
		
			 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
		
		  $createdats = Date('Y-m-d H:i:s') ;
	
	 $myduedate = Date('Y-m-d') ;
	
		//$transactioncode='IN-'.$this->createRandomPassword();
			$duedate = $this->input->post("duedate");
			

		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$transactioncode=0;
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			  
				$type = trim(strtoupper($this->input->post("type")));
				
			$description = $this->input->post("description");
						
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('month', ' Month', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('duedate', 'Due date  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/penaltyinvoice',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_penaltyinvoice') == "penalty")
		 {
			 
			 		        $plots = $this->accomodationmodel->getplotcoparentbalance($plotno,$duedate,$month,$year);

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

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

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

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

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


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


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

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

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

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

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

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

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

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

}
  // $plotsrow->plotno; 


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


								'companyid' => $companyid,

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

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

						);
			
			
			
			

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

			}

   }
}

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

}else{
 $usr_result =0;
	
}



















        if($usr_result > 0)
	{

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


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

		















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

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


} else {
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">! Error. This building does not have active penalty.Please update the penalty  to be charged for late payment first. </div>');
				 redirect('admin/penaltyinvoice?randomitemidentifier1='.$plotno);
				 
				 }
			 
			 
			
			
			
			
	
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	public function coparentinvoice() {
 
     if (isset($_GET['randomitemidentifier']) && isset($_GET['randomitemidentifier1'])){
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
	$data['invoice'] = $this->accomodationmodel->gethouseinvoice($plotno,$houseno);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/houseinvoice',$data);
		$this->load->view("template/footerpage");
	}   else if (isset($_GET['randomitemidentifier1'])){
$plotno = $_GET['randomitemidentifier1'];
    
   	$data['plotno'] = $plotno;
	$data['invoice'] = $this->accomodationmodel->getbulkcoparentnvoice($plotno);
	//$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		//$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	//$data['houserent'] = $this->accomodationmodel->getbulkhousedetails($plotno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/coparentinvoice',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  
  
	
	
	
	function addbulcoparentinvoice()
    {
		$session_data = $this->session->userdata('logged_in');

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

		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
		
		   
		  	 $year = $this->input->post("year");
 			  
				$type = trim(strtoupper($this->input->post("type")));
				
						
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('month', ' Month', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('duedate', 'Due date  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/penaltyinvoice',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_coparentinvoice') == "coparent")
		 {
			// $plots = $this->accomodationmodel->dispalytenantavailable($plotno);

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


if(is_array($plots)) {

   foreach($plots as $plotsrow){
	   $type=$plotsrow->type;
	   
if($type!="PENALTY") {
										$finalvat=0;
							 	 $finalcommission=0;
							
						$itemid=$plotsrow->id;
   						
						$paid=$plotsrow->paid;
						$invoiced=$plotsrow->amount;;
						$balance=$invoiced-$paid;
							 $mycoparent=$plotsrow->coparent;
				$mycoparentcommission=$plotsrow->coparentcommission;
					$mycoparentvat=$plotsrow->coparentvat;
							
						if($balance >0){
				
	   	$houserent = $this->accomodationmodel->gethousedetails($plotsrow->plotno,$plotsrow->houseno);
$vat=$houserent[0]['vat'];
$commission	=$houserent[0]['commission'];
	   
						if(($type=="1")||($type=="6")) {
								  $mytax=1+($vat/100); 
								 $vatable=($balance/$mytax);
								 $myfinaltax=($balance-$vatable);
								 $myfinalcommission=(($commission/100)*$balance);

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

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

								 	$finalvat=$mycoparentvat; 

							 }
	
	
	
	
						    $data=array(		
						'coparent'=>$balance,
							'coparentcommission'=>$finalcommission,
							'coparentvat'=>$finalvat,
						
						'coparentdate'=>$dateposted,
							'coparentuserid'=>$userid,
							
						);
						   
				
				
				
				
					$usr_result =  $this->usermodel->updatedata($data,'invoice','id',$itemid);

		
		

 }

   }
}
							
							//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 posted coparent payment</div>');	
				 redirect('admin/coparentinvoice?randomitemidentifier1='.$plotno);
							}
							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>Coparent   was not posted.. Try again</div>');
								
				 redirect('admin/coparentinvoice?randomitemidentifier1='.$plotno);
							}


} 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>Coparent   was not posted.. You can not pay before the duedate or no house availble with balance.Try again</div>');
								
				 redirect('admin/coparentinvoice?randomitemidentifier1='.$plotno);
}
			 
			 
			
			
			
			
	
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
		

  
  
  
  
  public function allhousereceiptbynorent() {
   if (!isset($_GET['randomitemidentifier1'])){

    
      show_error('No identifier provided', 500);
    }
    else {
		
				  		$session_data = $this->session->userdata('logged_in');

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

		$transactionid = $_GET['randomitemidentifier1'];
     $houseno = $_GET['houseno'];
	 $plotno = $_GET['plotno'];
	 $tenantid = $_GET['nyumbaid'];
	 //$month = $_GET['month'];
	 //$year = $_GET['year'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
			$data['tenantid'] = $tenantid;
		$data['charges'] = $this->accomodationmodel->getrentplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->getmyhousepayment($plotno,$houseno,$tenantid);
		//$data['allpayment'] = $this->accomodationmodel->getplotreceiptallbyype($plotno,$houseno,$month,$year, $tenantid);
		$data['balance'] = $this->accomodationmodel->getplotreceiptallbybalancerent($plotno,$houseno, $tenantid);

        		$data['configuration'] = $this->usermodel->populateallarray('smsconfig','id',$companyid);
			//$data['mypayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);
					$data['mypayment'] = $this->usermodel->populateall('receipt', 'id',$transactionid);

		//$data['mypayment'] = $this->accomodationmodel->getplotreceiptallbyno($plotno,$houseno,$month,$year, $tenantid);
				//$data['mypayment'] = $this->accomodationmodel->getplotreceiptbyno($transactionid);

		
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);

	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
				$session_data = $this->session->userdata('logged_in');

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

	 
	
		$transactionid = $_GET['randomitemidentifier'];
     $houseno = $_GET['houseno'];
	 $plotno = $_GET['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		 $tenantid = $_GET['nyumbaid'];
		$data['charges'] = $this->accomodationmodel->getrentplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->getmyhousepayment($plotno,$houseno,$tenantid);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);
		$data['balance'] = $this->accomodationmodel->getplotreceiptallbybalancerent($plotno,$houseno, $tenantid);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbynorent($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);

	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

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

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

    
      show_error('No identifier provided', 500);
    }
    else {
				$session_data = $this->session->userdata('logged_in');

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

	 
	
		$transactionid = $_GET['randomitemidentifier'];
     $houseno = $_GET['houseno'];
	 $plotno = $_GET['plotno'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
		 $tenantid = $_GET['nyumbaid'];
		$data['charges'] = $this->accomodationmodel->getrentplotcharges($plotno);
	$data['payment'] = $this->accomodationmodel->getmyhousepayment($plotno,$houseno,$tenantid);
			$data['allpayment'] = $this->accomodationmodel->getallhousepayment($plotno,$houseno);
		$data['balance'] = $this->accomodationmodel->getplotreceiptallbybalancerent($plotno,$houseno, $tenantid);

		$data['mypayment'] = $this->accomodationmodel->getplotreceiptbynorent($transactionid);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
				$data['plotnames'] = $this->accomodationmodel->getplotid($plotno);
$data['viewreceipt']= $this->usermodel->populateallarray('receipt','id',$transactionid);



	$transactioncode=$data['viewreceipt'][0]["transactioncode"];
	$data['viewsales']= $this->usermodel->populateall('invoice','transactioncode',$transactioncode);

	
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		
	 $tenantbalance=($data['tenant'][0]['totalamount']);
		
		 			$data['tenantbalance']=$tenantbalance;

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

  
  	
  
  
    public function penaltyinvoice() {
 
     if (isset($_GET['randomitemidentifier']) && isset($_GET['randomitemidentifier1'])){
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;

	$data['invoice'] = $this->accomodationmodel->gethouseinvoice($plotno,$houseno);
	$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
		$data['charges'] = $this->accomodationmodel->getplotcharges($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/houseinvoice',$data);
		$this->load->view("template/footerpage");
	}   else if (isset($_GET['randomitemidentifier1'])){
$plotno = $_GET['randomitemidentifier1'];
    
   	$data['plotno'] = $plotno;
	$data['invoice'] = $this->accomodationmodel->getbulkhouseinvoice($plotno);
	$data['otherinvoice'] = $this->accomodationmodel->getbulkhouseentalinvoice($plotno);
		$this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		

				$this->load->view('pmsdata/penaltyinvoice',$data);
		$this->load->view("template/footerpage");
    } else{
		 
      show_error('No identifier', 500);
		
	
  }
    }
	
  
  
  
  
  
    public function receivepayment() {
 
     if (isset($_GET['randomitemidentifier']) && isset($_GET['randomitemidentifier1'])){
     $houseno = $_GET['randomitemidentifier'];
	 $plotno = $_GET['randomitemidentifier1'];
	 	// $category = $_GET['category'];
		 
		 
	 $session_data = $this->session->userdata('logged_in');

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

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

		 
		 
		 
		 
		 
		 
		 
		 	$data['category'] = $category;
     	$data['houseno'] = $houseno;
		$data['plotno'] = $plotno;
			$data['tenant'] = $this->accomodationmodel->gettenantid($plotno,$houseno);
					$tenantid=($data['tenant'][0]['tenantid']);
					
					
				
	$data['invoice'] = $this->accomodationmodel->gethouseinvoicewithbalance($plotno,$houseno,$tenantid);
		
			$data['methode'] = $this->usermodel->populatealldatanoarray('glaccounts','companyid',$companyid,'accounttype','1');

			//$data['methode'] = $this->accomodationmodel->getpaymentsection($plotno);
$data['payment'] = $this->accomodationmodel->getmyhousepayment($plotno,$houseno,$tenantid);
		$data['charges'] = $this->accomodationmodel->getrentplotcharges($plotno);
	$data['houserent'] = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$data['myinvoice'] = FALSE;
			$data['tenantid'] = $tenantid;
		 $this->load->view("template/tableheader");

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

				$this->load->view('pmsdata/receivepayment',$data);
		$this->load->view("template/footerpage");
	
    }
}
 
	
	
	
	
	function addinvoice()
    {
		
		 $session_data = $this->session->userdata('logged_in');

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

		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		$transactioncode='IN-'.$userid.time();

			$duedate = $this->input->post("duedate");
				$paymentcode = $this->input->post("paymentcode");

		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
	
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $tenantid = $this->input->post("tenantid");
				   $amount = $this->input->post("amount");
				$type = $this->input->post("type");
				$yesno = $this->input->post("yesno");
				$priority = $this->input->post("priority");

			$description = $this->input->post("description");
							$name = $this->input->post("name");
		
         	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		//$this->form_validation->set_rules('type', 'Invoice type', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/houseinvoice',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_invoice') == "invoice")
		 {
			 				$vatdetails = $this->accomodationmodel->gethousedetails($plotno,$houseno);
		$plotdatils = $this->accomodationmodel->getplotid($plotno);

			$paymentdetails="";
			$plotpayments="";	
				

				$paymentdetails=$vatdetails[0]["paymentdetails"];
		
				$plotpayments=$plotdatils[0]["invoicesms"];
				$plotutility=$plotdatils[0]["utility"];
				$utilities="";
				if($plotutility=="no"){
				$utilities="";
				}else{
				$utilities="/ utilities";

				}
				
				
								$vat=$vatdetails[0]["vat"];

						$finalvat=0;
	$ttvat=0;
		$totalinvoice=0;
					$totaldeposite=0;
$debitcreditdata = array();
			$count =count((array) $type);

   for($i=0; $i< $count; $i++) {
	   	$finaldate=$createdat;
			   	$myduedate=$duedate;
				
				
			    if(($type[$i]=="1")||($type[$i]=="6")) {
								  $mytax=1+($vat/100); 
								 $vatable=($amount[$i]/$mytax);
								 $myfinaltax=($amount[$i]-$vatable);


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

								 								$finalvat=0; 

							 }	
				
				$ttvat=$ttvat+$finalvat;
					 $accountname = $this->usermodel->populatealldataarray('rentalpaymentmethodes','chargeid', $type[$i],'branchid', $branchid);

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

     $myyesno=$yesno[$i];	
      $data=array(
		'type' =>$type[$i],				
	   'createdat' =>$createdat,
	   'amount'=>$amount[$i],
		'month'=>$month[$i],
		'year'=>$year[$i],
        'duedate' =>$duedate,
		 'priority' =>$priority[$i],
		'houseno' => $houseno,
				'plotno' => $plotno,
				'chargeid' => $name[$i],

				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'vat' => $finalvat,

			
				'paymentcode' => $paymentcode,
				'transactioncode' => $transactioncode,
			
			'branchid' => $branchid,
						'companyid' => $companyid,
				'userid' => $userid,
				'description' => $description
		
							
								);
								if (!(($this->accomodationmodel->checkinvoice($plotno,$houseno,$type[$i],$month[$i],$year[$i],$tenantid  ))==TRUE ) && ($myyesno=="Yes"))
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Invoice Error !'.$type[$i].' for the year of '.$year[$i].' and the month of '.$month[$i].' has been invoiced already for house no '.$houseno.' and Plot no '.$plotno.'! . Try again.. </div>');
				 	// redirect('admin/rentinvoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
									 $usr_result = $this->accomodationmodel->insertInvoice($data);
		$totalinvoice=$totalinvoice+$amount[$i];
if($type[$i]=="2"){
	
				$totaldeposite=$totaldeposite+$amount[$i];

			}
			}			
					
       }
		
			
			
			
				if ($usr_result ==TRUE) //active user record is present
							{
								

								
								$invoicedata = array(
				'houseno' => $houseno,
				
				'amount' => $totalinvoice,
				'plotno' => $plotno,
			
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $finaldate,
					'exactime' => $myduedate,
										'tax1' => $ttvat,

				'userid' => $userid,
					'paidby' => "",
								'paymentmode' => 0,
						'overpayment' => 0,
						'paymentcode' => 0,


				'companyid' => $companyid,

				'description' => $description
			);

					
					$this->usermodel->add($invoicedata,'receipt');
								
						$debitdata=array( 'userid'=>$userid,'account'=>1100 ,'debit'=>$totalinvoice,'description'=>"Expected Rental income",'code'=>$transactioncode,'crateddate'=>$finaldate,'branch' => $branchid,'companyid'=> $companyid,'type'=>'Payment','transactioncode'=>$houseno ,'supplier'=> $tenantid);
							$this->usermodel->add($debitdata,'debitcredit');

				
						$this->db->insert_batch('debitcredit', $debitcreditdata);

								
						
										$users = $this->usermodel->populateallarray('people','id', $tenantid);
										$currentuserbalance=$users[0]['balance'];
									$contact=$users[0]['phone'];
								

									$houserent = $this->accomodationmodel->getbookingbytenant($plotno,$houseno);
									$rentalid=$houserent[0]["id"];
										$prvioushousebalance=$houserent[0]["totalamount"];
										$overpayment=$houserent[0]["overpayment"];
										
										
										
										
								
									$updatedata = array('totalamount' => ($totalinvoice+$prvioushousebalance),
									//'deposite' => ($totaldeposite),
									
									);
									$this->usermodel->updatedata($updatedata,'bookroom','id',$rentalid);
									$ttbalance=($totalinvoice+$currentuserbalance);
								$peopledta = array('balance' => ($totalinvoice+$currentuserbalance),);

						
												$this->usermodel->updatemember($peopledta,$tenantid) ;
								
										$invoicelink= base_url()."printinvoicehouse?refnumber=".$salesid;

						$receiptlink= base_url()."pintreceipthouse?refnumber=".$salesid;
								
								
								if($totalinvoice>0){
								
			   $correctime = date("d/m/Y", strtotime($finaldate));
			   $correctduetime = date("d/m/Y", strtotime($myduedate));
				$taskmessage = "Dear ". $users[0]['firstname'] ."! You have been invoiced Ksh.". $totalinvoice ." for rent ". $utilities ." for Hs No.". $houseno ." on ". $correctime .". Your previous balance is: ".$currentuserbalance.". Your total balance is now Ksh.". ($ttbalance-$overpayment) ." . Kindly settle the total balance by ". $correctduetime .".".$paymentdetails.".".$plotpayments.".Click here to view your invoice: ".$invoicelink;



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

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

								
								
						$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Invoice is added Successfully ! !!!</div>');
					 redirect('admin/rentinvoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);	
								
							}
							else
							{     
	$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Invoice not added. Please try again </div>');
				 redirect('admin/rentinvoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
							}
			
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	function addhouseinvoice()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
	    $branchid = $_GET['branchid'];
		 	$data['branchid']=$branchid;
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		$transactioncode='IN-'.$this->createRandomPassword();
			$duedate = $this->input->post("duedate");
				$paymentcode = $this->input->post("paymentcode");

		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $tenantid = $this->input->post("tenantid");
				   $amount = $this->input->post("amount");
				$type = trim(strtoupper($this->input->post("type")));

			$description = $this->input->post("description");
						
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/houseinvoice',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_invoice') == "invoice")
		 {
			
			$data = array(
				'houseno' => $houseno,
				'plotno' => $plotno,
				'type' => $type,
				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdat,
				'amount' => $amount,
				'paymentcode' => $paymentcode,
				'transactioncode' => $transactioncode,
				'month' => $month,
				
				'year' => $year,
				'duedate' => $duedate,
				'description' => $description,
				'branchid' => $branchid,
						'companyid' => $companyid,
				'userid' => $userid,
			);
			
			
			if($action=="insert"){
				
			if (($this->accomodationmodel->checkinvoice($plotno,$houseno,$type,$month,$year))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Invoice Error !'.$type.' for the year of '.$year.' and the month of '.$month.' has been invoiced already for house no '.$houseno.' and Plot no '.$plotno.'! . Try again.. </div>');
				 	 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
			// insert form data into database
			if ($this->accomodationmodel->insertInvoice($data))
			{
			$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Invoice is added Successfully ! !!!</div>');
					 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);	
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Invoice not added. Please try again </div>');
				 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Invoice is updated Successfully ! !!!</div>');
					 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Invoice not updated. Please try again </div>');
				 redirect('admin/invoice?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
		function addapproval()
    {
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
$data['surname'] = $session_data['surname'];
$surname = $data['surname'];
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		$transactioncode1='COP-'.$this->createRandomPassword();
		$rate = $this->input->post("rate");
		$transactioncode = $this->input->post("transactioncode");
		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $tenantid = $this->input->post("tenantid");
				   $amount = $this->input->post("amount");
				   $type = $this->input->post("type");
				
			$description = $this->input->post("description");
				$approval = $this->input->post("approval");	
$approvedby = $this->input->post("approvedby");
$paymentmode = $this->input->post("paymentmode");
			$amount1 = (($amount)*(-1))	;
      
$userid = $this->input->post("userid");		 
		  	$totalamount=	((($rate + 100)/100)* ($amount1));
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/housepayment',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_addaproval') == "payment")
		 {
			
			$data = array(
				'houseno' => $houseno,
				'approval' => $approval,
				'amount' => $amount,
				'totalamount' => $totalamount,
				'plotno' => $plotno,
				'type' => $type,
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'receipt',
				'approvaldate' => $createdats,
				'month' => $month,
				'year' => $year,
				'approvedby' => $surname ,
				'userid' => $userid ,
				'paymentmode' => $paymentmode,
				'description' => $description,
				'companyid' => $companyid,
			);
			
			
			if($action=="insert"){
				
			
			// insert form data into database
			if ($this->accomodationmodel->insertHousepayment($data))
			{
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> payment is added Successfully ! !!!</div>');
					 redirect('admin/viewcoparent?randomitemidentifier='.$id);
						
			}
			else
			{
				
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment not added. Please try again </div>');
				redirect('admin/viewcoparent?randomitemidentifier='.$id);	
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->Updateapproval($data,$id))
			{
				if($approval=="approved"){
						$copadata = array(
				'houseno' => $houseno,
				
				'amount' => $totalamount,
				'plotno' => $plotno,
				
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdats,
				'month' => $month,
				'year' => $year,
				
				'userid' => $approvedby ,
				'paymentcode' => $transactioncode1,
				'rate' => $rate
			);
					if ($this->accomodationmodel->insertCoparent($copadata))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> payment is added Successfully ! !!!</div>');
					 redirect('admin/viewcoparent?randomitemidentifier='.$id);
			}else
			{
				
				// error
								$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> payment is added Successfully ! !!!</div>');

				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Copa rent invoice not successful </div>');
				redirect('admin/viewcoparent?randomitemidentifier='.$id);	
			}
				
				
				
				
				
				}else{
						$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> payment is added Successfully ! !!!</div>');
					 redirect('admin/viewcoparent?randomitemidentifier='.$id);
						
					}
				
				
				
				
				
				
				
				
				
				
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">payment is updated Successfully ! !!!</div>');
				redirect('admin/viewcoparent?randomitemidentifier='.$id);	
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment not updated. Please try again </div>');
						redirect('admin/viewcoparent?randomitemidentifier='.$id);	
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	function addinvoicecoparent()
    {
		
	$session_data = $this->session->userdata('logged_in');

 $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	     $branchid = $_GET['branchid'];
		 	$data['branchid']=$branchid;
			
$data['surname'] = $session_data['surname'];
$surname = $data['surname'];
		  $createdats = Date('Y-m-d H:i:s') ;
	$totalexpected = $this->input->post("totalamount");
	
		$id = $this->input->post("id");
		$transactioncode1='COP-'.$this->createRandomPassword();
		$rate = $this->input->post("rate");
		
		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $tenantid = $this->input->post("tenantid");
				   $amount = $this->input->post("amount");
					$type = trim(strtoupper($this->input->post("type")));

			$description = $this->input->post("description");
				$approval = $this->input->post("approval");	
$transactioncode = $this->input->post("transactioncode");
$paymentmode = $this->input->post("paymentmode");
			$amount1 = (($amount)*(-1))	;
      
$userid = $this->input->post("userid");		
if (($this->accomodationmodel->checkcoparentinvoice($plotno,$houseno,$month,$year))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Invoice Error ! Invoice for the year of '.$year.' and the month of '.$month.' has been invoiced already for house no '.$houseno.' and Plot no '.$plotno.'! . Try again.. </div>');
				 	 redirect('admin/invoicecoparent?randomitemidentifier='.$id);
			} 
			$totalintrest=	((($rate)/100)* ($amount1));
		  	$totalamount=	($totalintrest+$totalexpected);
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/housepayment',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_addinvoice') == "invoicerent")
		 {
			
			$data = array(
			'houseno' => $houseno,
				
				'amount' => $totalintrest,
				'plotno' => $plotno,
				
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'invoice',
				'createdat' => $createdats,
				'month' => $month,
				'year' => $year,
					'branchid' => $branchid,
						'companyid' => $companyid,
				'userid' => $surname ,
				'paymentcode' => $transactioncode1,
				'rate' => $rate
			);
			
			
		
				
			
			// insert form data into database
			if ($this->accomodationmodel->insertCoparent($data))
			{
				
				
				
				
				
				
				$updatedata = array(
			
				'totalamount' => $totalamount,
				
				
			);
				
				
				
		
				
				
					if ($this->accomodationmodel->Updateapproval($updatedata,$id)){
					$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> The invoice is added Successfully ! !!!</div>');
					 redirect('admin/viewcoparent?randomitemidentifier='.$id);
			
							}else{
											$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> The invoice is added Successfully ! !!!</div>');
					 redirect('admin/viewcoparent?randomitemidentifier='.$id);
					 
					 	// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Total expected amount not actvated</div>');
				redirect('admin/viewcoparent?randomitemidentifier='.$id);	
							}
				
			}
			else
			{
				
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Invoice not added. Please try again </div>');
				redirect('admin/viewcoparent?randomitemidentifier='.$id);	
			}
				
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
	
	function addpayment()
    {
		
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		$transactioncode='RC-'.$this->createRandomPassword();
		
		
		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $tenantid = $this->input->post("tenantid");
				   $amount = $this->input->post("amount");
				   $type = $this->input->post("type");
				
			$description = $this->input->post("description");
					
$userid = $this->input->post("userid");
$paymentmode = $this->input->post("paymentmode");
				$roomidentifier = $this->input->post("roomidentifier");
	
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/housepayment',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_payment') == "payment")
		 {
			
			$data = array(
				'houseno' => $houseno,
				
				'amount' => $amount,
				'plotno' => $plotno,
				'type' => $type,
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'receipt',
				'createdat' => $createdat,
				'month' => $month,
				'year' => $year,
				'userid' => $userid,
				'paymentmode' => $paymentmode,
								'companyid' => $companyid,

				'description' => $description
			);
			
			
			if($action=="insert"){
				
			
			// insert form data into database
			if ($this->accomodationmodel->insertHousepayment($data))
			{
			$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> payment is added Successfully ! !!!</div>');
					 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);	
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment not added. Please try again </div>');
					 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);	
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">payment is updated Successfully ! !!!</div>');
					 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);	
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment not updated. Please try again </div>');
					 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno.'&roomidentifier='.$roomidentifier);	
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
		public function addmpesapayment()
	{  	
		  $createdats = Date('Y-m-d H:i:s') ;
	 $this->load->view("template/headerpagemin");
		//$output="ROBISEARCH1";
		$json = file_get_contents('php://input');
$result = json_decode($json);
	
	 

		$output=$result->amount;

		$data=array(		
			'output'=>$output,
			'createdats'=>$createdats,
			'xml'=>$result,
			'json'=>$json,
				
			
								);
				$usr_result = $this->usermodel->add($data,'mpesa');
				if($usr_result){
					
 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> SAVED ..</div>');	
					$this->load->view('pmsdata/mpesa',$data);

								
				}else{
				$this->session->set_flashdata('msg', '<div class="alert alert-danger fade in"><a href="#" class="close" data-dismiss="alert">&times;</a>
						 
								<strong>Success!</strong> SAVED ..</div>');		
					$this->load->view('pmsdata/mpesa',$data);
		
				}
				$this->load->view("template/footerpage");
		
	}
	
	
	
	
	
	
	
	
	
	
	
	function addmpesapayment1()
    {
		
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		  $createdats = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
	
		$id = $this->input->post("id");
		$transactioncode='RC-'.$this->createRandomPassword();
		
		
		$plotno = $this->input->post("plotno");
		$month = $this->input->post("month");
			$houseno = $this->input->post("houseno");
		   
		  	 $year = $this->input->post("year");
           $createdat = $this->input->post("createdat");
 			    $tenantid = $this->input->post("tenantid");
				   $amount = $this->input->post("amount");
				   $type = $this->input->post("type");
				
			$description = $this->input->post("description");
					
$userid = $this->input->post("userid");
$paymentmode = $this->input->post("paymentmode");
					
         	
		  	
		$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('houseno', ' house no', 'trim|required|min_length[1]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('amount', 'amount  ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/housepayment',$data);
		$this->load->view("template/footerpage");
		
		
        }
		else
		{
			//insert the user registration details into database
		if ($this->input->post('btn_payment') == "payment")
		 {
			
			$data = array(
				'houseno' => $houseno,
				
				'amount' => -$amount,
				'plotno' => $plotno,
				'type' => $type,
				'transactioncode' => $transactioncode,
				'tenantid' => $tenantid,
				'paymentstatus' =>'receipt',
				'createdat' => $createdat,
				'month' => $month,
				'year' => $year,
				'userid' => $userid,
				'paymentmode' => $paymentmode,
								'companyid' => $companyid,

				'description' => $description
			);
			
			
			if($action=="insert"){
				
			
			// insert form data into database
			if ($this->accomodationmodel->insertHousepayment($data))
			{
			$this->session->set_flashdata('msg','<div class="alert alert-success text-center"> payment is added Successfully ! !!!</div>');
					 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);	
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment not added. Please try again </div>');
				 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
			}if($action=="update"){
				
				
					if ($this->accomodationmodel->UpdateBooking($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">payment is updated Successfully ! !!!</div>');
					 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment not updated. Please try again </div>');
				 redirect('admin/housepayment?randomitemidentifier='.$houseno.'&randomitemidentifier1='.$plotno);
			}
				
				
			}
			
			
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	function addlandlord()
    {
		
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
	 
	 
		$action = $this->input->post("action");
		$createdat = Date('Y-m-d H:i:s') ;
				$firstname = $this->input->post("firstname");
				$lastname = $this->input->post("lastname");
				$location = $this->input->post("location");
 			    $phone = $this->input->post("phone");
				$email = $this->input->post("email");
				$idno = $this->input->post("idno");
				$country = $this->input->post("country");
					$county = $this->input->post("county");
					
				$gender = $this->input->post("gender");
				$description = $this->input->post("description");
					$accountno = $this->input->post("accountno");
				$accountname = $this->input->post("accountname");	
				
				
				
          //set validations
		  	
		//$this->form_validation->set_rules('plotno', 'Plot Name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('firstname', ' first name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('lastname', 'lastname ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('idno', 'idno', 'trim|required|xss_clean');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewlandlord',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_landlord') == "landlord")
		 {
			
				
				
			$data = array(
				'accountname' => $this->input->post('accountname'),
				'accountno' => $this->input->post('accountno'),
				'companyid' => $companyid,
				'userid' => $userid,

						'county' => $this->input->post('county'),
				'firstname' => $this->input->post('firstname'),
				'lastname' => $this->input->post('lastname'),
				'location' => $this->input->post('location'),
				'phone' => $this->input->post('phone'),
				'email' => $this->input->post('email'),
				'idno' => $this->input->post('idno'),
				'country' => $this->input->post('country'),
				'gender' => $this->input->post('gender'),
				'createdat' =>$createdat,
				'description' => $this->input->post('description')
			);
			
			// insert form data into database
			if($action=="insert"){
				
					if (($this->accomodationmodel->checkalandlordidno($idno))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Landlord can not be added ! . The Landlord  with ID NO of '  .$idno.  '  is already existing.. You can just update the details </div>');
				 	 redirect('admin/viewallandlord');
			}
			
			if ($this->accomodationmodel->insertlandlord($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Landlord is added Successfully ! !!!</div>');
					 redirect('admin/viewallandlord');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Landlord not added. Please try again </div>');
				 redirect('admin/viewallandlord');
			}
			}else if($action=="update"){
			
				$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadeteLandlord($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Landlord is updated Successfully ! !!!</div>');
					 redirect('admin/viewallandlord');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. House not updated. Please try again </div>');
				 redirect('admin/viewallandlord');
			}
				
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	function addagent()
	
    { 
$session_data = $this->session->userdata('logged_in');

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

	$createdat = Date('Y-m-d H:i:s') ;
	$action = $this->input->post("action");
				$firstname = $this->input->post("firstname");
				$lastname = $this->input->post("lastname");
				$location = $this->input->post("location");
 			    $phone = $this->input->post("phone");
				$email = $this->input->post("email");
				$idno = $this->input->post("idno");
				$country = $this->input->post("country");
				$gender = $this->input->post("gender");
				$description = $this->input->post("description");
					$county = $this->input->post("county");
							$accountno = $this->input->post("accountno");
				$accountname = $this->input->post("accountname");	
			
          //set validations
		  	
		//$this->form_validation->set_rules('email', 'email', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('firstname', ' first name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('lastname', 'lastname ', 'trim|required|xss_clean');
		//$this->form_validation->set_rules('idno', 'idno', 'trim|required|xss_clean');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allagents',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_agent') == "agent")
		 {
			
				
				
			$data = array(
				'firstname' => $this->input->post('firstname'),
				'lastname' => $this->input->post('lastname'),
				'location' => $this->input->post('location'),
				'phone' => $this->input->post('phone'),
				'email' => $this->input->post('email'),
				'idno' => $this->input->post('idno'),
				'country' => $this->input->post('country'),
				'gender' => $this->input->post('gender'),
				'createdat' => $createdat,
			'county' => $this->input->post('county'),
				'description' => $this->input->post('description'),
					
				'accountname' => $this->input->post('accountname'),
				'accountno' => $this->input->post('accountno'),
				 'companyid' => $companyid,
				'userid' => $userid,
				
			);
			
			if($action=="insert"){
						if (($this->accomodationmodel->checkagentidno($idno))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Agent can not be added ! . The Agent  with ID NO of '  .$idno.  '  is already existing.. You can just update the details </div>');
				 	 redirect('admin/viewallagents');
			}
			if ($this->accomodationmodel->insertagent($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Agent is added Successfully ! !!!</div>');
					 redirect('admin/viewallagents');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. House not added. Please try again </div>');
				 redirect('admin/viewallagents');
			}
			}else if($action=="update"){
				
					$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadeteAgent($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Agent is updated Successfully ! !!!</div>');
					 redirect('admin/viewallagents');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Manager not updated. Please try again </div>');
				 redirect('admin/viewallagents');
			}
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	function addtenant()
    {
		 $session_data = $this->session->userdata('logged_in');

   //
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	  
		 $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];	
	
				$createdat = Date('Y-m-d H:i:s') ;
				$action = $this->input->post("action");
				$transactionid = $this->input->post("transactionid");
				$firstname = $this->input->post("firstname");
				$lastname = $this->input->post("lastname");
				$location = $this->input->post("location");
 			    $phone = $this->input->post("phone");
				$email = $this->input->post("email");
				$idno = $this->input->post("idno");
				$country = $this->input->post("country");
								$dob = $this->input->post("dob");
								$idnumber = $this->input->post("idnumber");


				$gender = $this->input->post("gender");
				$description = $this->input->post("description");
									$company = $this->input->post("company");
	
						$currentimg_id = rand(100, 9900000).time();
						//$address_1 = $this->input->post("address_1");
						$img_id = $this->input->post("img_id");
						$type = $this->input->post("type");
						$view = $this->input->post("view");
          //set validations
		  	
		//$this->form_validation->set_rules('email', 'email', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		$this->form_validation->set_rules('action', ' action', 'trim|required|min_length[2]|max_length[40]|xss_clean');
		//$this->form_validation->set_rules('idno', 'idno', 'trim|required|xss_clean');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewlandlord',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
		
		
			
		if ($this->input->post('btn_tenant') == "tenant")
		 {
			 	
			  
					$confirmuseridno = $this->usermodel->populatealldataarray('people','idno', $idno,'companyid', $companyid);
	   								
																		
																		$confirmuser = $this->usermodel->populatealldataarray('people','phone', $phone,'companyid', $companyid);
						   			$details="Details are :Name: ".$confirmuser[0]['firstname'].", Company: ".$confirmuser[0]['company'].",Phone: ".$confirmuser[0]['phone']." .";
	   if(($confirmuser !=false)||($confirmuseridno !=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 personel already exist on the system.'.	$details.' Try again. Try different personel.</div>');

						  
								redirect($view);	
	   return false;
					   }
					   
					   
				
			$data = array(
				'image_id' => $img_id,
					'firstname' => $this->input->post('firstname'),
				'lastname' => $this->input->post('lastname'),
				'company' => $this->input->post('company'),
				'phone' => $this->input->post('phone'),
				'email' => $this->input->post('email'),
				'category' => "accommodation",

				'idno' => $this->input->post('idno'),
				'country' => $this->input->post('country'),
				'gender' => $this->input->post('gender'),
				'comments' => $this->input->post('description'),
				'createdate' => $createdat,
				'county' => $this->input->post('county'),
				//'address_1' => $address_1,
					  'companyid' => $companyid,
					  'idnumber' => $idnumber,

					  					  'dob' => $dob,

				'userid' => $userid,
				
			);
			
			if($action=="insert"){
				if (($this->accomodationmodel->checktenatidno($idno))==TRUE )
			{	
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Error! Customer can not be added ! . The Customer  with ID NO of '  .$idno.  '  is already existing.. You can just update the details </div>');
				 	 redirect($view);
			}
			
			if ($this->accomodationmodel->inserttenant($data))
			{	  
					
			
					 $this->session->set_flashdata('msg', '<div class="alert alert-success fade in">
						  <a href="#" class="close" data-dismiss="alert">&times;</a><strong>Congratulations!  </strong>  Customer('.$idno.') was added successfully. Proceed and check in the customer.</div>');		
			
			 		 $file= trim($_FILES["photo"]['name']);
			
					if($file!=""){
						
								 				 		 $documentname = $this->input->post("documentname");

								$data2=array(		
			'img_id'=>$currentimg_id,
			
			'documentname'=>$documentname,
				'idno'=>$idno,
			
		  	'description'=>"Customer Document",
			'category'=>"Identification ",
			'entrydate'=>$createdat,
			'dateposted'=>$createdat,
					'userid'=>$userid,
					'companyid'=>$companyid,
					'mydocuments'=>$img_id,
					
								);
							$usr_result = $this->usermodel->add($data2,'documents');
							
			
       if($usr_result ==TRUE){
		   $this->uploadimage($view, $currentimg_id,$userid);
						
					}
						
					
					}
					
					
					
					
					
						

			 redirect($view);
				 
					 
					 
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Customer not added. Please try again </div>');
				 	 redirect($view);
			}
			
			
			}else if($action=="update"){
					$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadeteTenant($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Customer is updated Successfully ! !!!</div>');
				 	 redirect($view);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Customer not updated. Please try again </div>');
				 	 redirect($view);
			}
				
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	function addpaymentmethod()
    {
			$createdat = Date('Y-m-d H:i:s') ;
				$action = $this->input->post("action");
				$method = $this->input->post("method");
				
				$description = $this->input->post("description");
						
          //set validations
		  	
		$this->form_validation->set_rules('method', 'method', 'trim|required|min_length[2]|max_length[40]|xss_clean');
	
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewpaymentmethod',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_paymentmethod') == "paymentmethod")
		 {
			
				
				
			$data = array(
				'method' => $this->input->post('method'),
				
				'createdat' => $createdat,
				'description' => $this->input->post('description')
			);
			
		if($action=="insert"){
			if ($this->accomodationmodel->insertpaymentmethod($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Payment method  is added Successfully ! !!!</div>');
					 redirect('admin/viewallpaymentmethod');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Payment method not added. Please try again </div>');
				 redirect('admin/viewallpaymentmethod');
			}
		}else if($action=="update"){
			
				$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadetePaymentmethod($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Payment method  is updated Successfully ! !!!</div>');
					 redirect('admin/viewallpaymentmethod');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Payment method  not updated. Please try again </div>');
				 redirect('admin/viewallpaymentmethod');
			}
			
			
		}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
 
 
	public function uploadimages($imgid,$companyid,$branchid,$userid) {
     		  $dateposted = date('Y-m-d H:i:s');

    $file= $_FILES["photo"]['name'];
$imgid = $this->input->post("imgid");
if($file!=""){
		$photo = $this->input->post("photo");
		$config['upload_path'] = is_dir($photo).'photoimghod/';
  		$new_date=date('Ymd');
     $ext = explode(".", strtolower($file));
		 $ext = strtolower(end($ext));
			 $new_name = $new_date.time().".".$ext;
		 
		$config['file_name'] = $new_name;
		
		
        $config['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif';
        $config["max_size"] = 1024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);



        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
         
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'img_id'=>$imgid,
				'companyid'=>$companyid,
		'userid'=>$userid,
			'branchid'=>$branchid,
				'date'=>$dateposted,
				);
		
      							$usr_result = $this->usermodel->add($data1,'alldocuments');

		 
		 }
        



        }  


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

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

	 
			$createdat = Date('Y-m-d H:i:s') ;
				$action = $this->input->post("action");
				$category = $this->input->post("category");
				
				$message = $this->input->post("message");
						
          //set validations
		  	
		$this->form_validation->set_rules('category', 'category', 'trim|required|min_length[2]|max_length[200]|xss_clean');
	
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/smscategory',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_smscategory') == "smscategory")
		 {
			
				
				
			$data = array(
				'category' => $this->input->post('category'),
				'companyid' => $companyid,
				'userid' => $userid,
				'createdat' => $createdat,
				'message' => $this->input->post('message')
			);
			
		if($action=="insert"){
			if ($this->accomodationmodel->insertsmscategory($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms category  is added Successfully ! !!!</div>');
					 redirect('admin/viewallsmscategory');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. sms category not added. Please try again </div>');
				 redirect('admin/viewallsmscategory');
			}
		}else if($action=="update"){
			
				$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadetesmscategory($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Payment method  is updated Successfully ! !!!</div>');
					 redirect('admin/viewallsmscategory');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Payment method  not updated. Please try again </div>');
				 redirect('admin/viewallpaymentmethod');
			}
			
			
		}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
		function addsms()
    {$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
	 
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
	 
			$createdat = Date('Y-m-d H:i:s') ;
				$action = $this->input->post("action");
				$number = $this->input->post("number");
				$message = $this->input->post("message");
						
          //set validations
		  	
		$this->form_validation->set_rules('number', 'number', 'trim|required|min_length[5]|max_length[40]|xss_clean');
			$this->form_validation->set_rules('message', 'message', 'trim|required|min_length[2]|max_length[200]|xss_clean');

		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewallsms',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_sms') == "sms")
		 {
			
				
				
			
			
			$myArray = explode(',', $number);
foreach($myArray as $allconatcts){
   // echo $my_Array.'<br>';  

	$data = array(
				'number' => $allconatcts,
				 'companyid' => $companyid,
				'userid' => $userid,
				'createdat' => $createdat,
				'user' => $userid,
				'message' => $this->input->post('message')
			);
$url = 'http://mybettersms.net/BetterSmsPost/Default.aspx';
$xml = "<SendMessage><message id='292' sentdate='636742' message='$message' source='$allconatcts'/></SendMessage>";
$ch = curl_init();

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, true);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $xml );

$response = curl_exec($ch);
//echo $allconatcts; echo"</br>";




if($response!=false){
	//echo $allconatcts; echo"</br>";
			$this->accomodationmodel->insertsms($data);
			
				
	
}else if($response==false){
	
	echo '<div class="alert alert-danger text-center">SMS  not Sent to  '.$allconatcts .'Error was Encountered  while sending SMS.  <a href=' .base_url(). 'admin/viewallsms> clicke here to go back  </a> </div>';
					 //
			
		
	

}
curl_close($ch);
}
			
			
			
		if($response!=false){
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">sms   is sent Successfully ! !!!</div>');
					 //redirect('admin/viewallsms');
			
	redirect('admin/viewallsms');
		}		
			
			
			
			
			
			
			
			
			
			
		
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	
	
	
	
	
	function addcountry()
    {
			$createdat = Date('Y-m-d H:i:s') ;
				$action = $this->input->post("action");
				$name = $this->input->post("name");
				
				$description = $this->input->post("description");
						
          //set validations
		  	
		$this->form_validation->set_rules('name', 'name', 'trim|required|min_length[2]|max_length[40]|xss_clean');
	
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allacountries',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_country') == "country")
		 {
			
				
				
			$data = array(
				'name' => $this->input->post('name'),
				
				'createdat' => $createdat,
				'description' => $this->input->post('description')
			);
			
		if($action=="insert"){
			if ($this->accomodationmodel->insertCountry($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Country  is added Successfully ! !!!</div>');
					 redirect('admin/viewallcountries');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Country  not added. Please try again </div>');
				 redirect('admin/viewallcountries');
			}
		}else if($action=="update"){
			
				$id = $this->input->post("id");
				
					if ($this->accomodationmodel->upadetecountry($data,$id))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Country   is updated Successfully ! !!!</div>');
					 redirect('admin/viewallcountries');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Country   not updated. Please try again </div>');
				 redirect('admin/viewallcountries');
			}
			
			
		}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	function addpaymentsection()
    {
		$createdat = Date('Y-m-d H:i:s') ;
				$name = $this->input->post("name");
				$methodid = $this->input->post("methodid");
				$description = $this->input->post("description");
						
          //set validations
		  	
		$this->form_validation->set_rules('name', 'name', 'trim|required|min_length[2]|max_length[40]|xss_clean');

		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allapaymentsection',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_paymentsection') == "paymentsection")
		 {
			
				
				
			$data = array(
				'name' => $name,
				'methodid' => $methodid,
				'description' => $description,
				'createdat' => $createdat
			);
			
			// insert form data into database
			if ($this->accomodationmodel->insertpaymentsection($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">payment section is added Successfully ! !!!</div>');
					 redirect('admin/allpaymentsection?randomitemidentifier='.$methodid);
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment section not added. Please try again </div>');
				 redirect('admin/allpaymentsection?randomitemidentifier='.$methodid);
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	function addpaymentcharge()
    {
		
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		$createdat = Date('Y-m-d H:i:s') ;
				
				$action = trim($this->input->post("action"));
				$type = trim(strtoupper($this->input->post("type")));
				$description = trim($this->input->post("description"));
									$priority = trim($this->input->post("priority"));
	
          //set validations
		  			$this->form_validation->set_rules('type', 'type', 'trim|required|min_length[2]|max_length[40]|xss_clean');


				   $confirmname = $this->accomodationmodel->confirmname($type);
						   if ($confirmname ==true)
						   {
							  	 $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">That charge ('.$type. ') is already in the system. Add a different one or just use the existing charge.</div>');
								
								 redirect('admin/viewallpaymentcharge');
						   }
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/allapaymentsection',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_paymentcharge') == "paymentcharge")
		 {
			
				
				
			$data = array(
				
				'type' => $type,
				'description' => $description,
				'createdat' => $createdat,
					'companyid' => $companyid,
						'priority' => $priority,
			);
			
			// insert form data into database
			if ($this->accomodationmodel->insertpaymentcharge($data))
			{
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">payment Charges is added Successfully ! !!!</div>');
					 redirect('admin/viewallpaymentcharge');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. payment Charges not added. Please try again </div>');
				 redirect('admin/viewallpaymentcharge');
			}
		}
			else
			{
				// error
				 redirect('admin');
			}
		}
	}
	
	
	
	
	function adddiscount()
    {
		
		$session_data = $this->session->userdata('logged_in');

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 	  $data['branchid'] = $session_data['branchid'];
	 $branchid = $data['branchid'];
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		$createdat = Date('Y-m-d H:i:s') ;
				
				$name = trim(strtoupper($this->input->post("name")));
				$discount = trim($this->input->post("discount"));
					$type = trim($this->input->post("type"));

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


 $action = trim($this->input->post("action"));
				  
  $mycategoryid = $this->input->post("categoryid");
          //set validations
		 
		  			$this->form_validation->set_rules('discount', 'discount', 'trim|required|min_length[2]|max_length[40]|xss_clean');

			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
			 $this->load->view("template/headerpagemin");
		
		 $this->load->view("template/tableheader");
		$this->load->view('pmsdata/viewalldiscounts',$data);
		$this->load->view("template/footerpage");
		
        }
		else
		{
			
		if ($this->input->post('btn_adddiscount') == "discountcharge")
		 {
			
				
				
			$data = array(
				
				'name' => $name,
				'discount' => $discount,
				'createdate' => $createdat,
					'companyid' => $companyid,
						'branchid' => $branchid,
						'type' => $type,
							'updatedate' => $default,

							'userid' => $userid,
			);
				
			// insert form data into database
			
		
			 if($action=="insert"){
							$usr_result = $this->usermodel->add($data,'discount');

							}else{
								
								$usr_result = $this->usermodel->updatedata($data,'discount','id',$mycategoryid);

								}
			
			
			
			
			//check if surname and password is correct
							if ($usr_result ==TRUE) //active user record is present
							{
				
				$this->session->set_flashdata('msg','<div class="alert alert-success text-center">Discount  offer was  added Successfully ! !!!</div>');
					 redirect('admin/viewalldiscounts');
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Discount offer was  not added. Please try again </div>');
				 redirect('admin/viewalldiscounts');
			}
		}
			else
			{
				// error
				 redirect('login');
			}
		}
	}
	
	
	public function displaystudentupload()
	{ 
		 $this->load->view("template/headerpagemin");
		
				$this->load->view('pmsdata/campusupload');
		$this->load->view("template/footerpage");
	}




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

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

     $data['surname'] = $session_data['surname'];
      $data['firstname'] = $session_data['firstname'];
       $data['email'] = $session_data['email'];
 	 $data['id'] = $session_data['id'];

	$id= $data['id'] ;
	 $data['admin'] = $this->accomodationmodel->populateadmindata($id);
	 $this->load->view("template/headerpagemin");
   $data['userid'] = "yes";
		
		 $this->load->view('admindata/adminpage',$data);
		$this->load->view("template/footerpage");
    }
    else {
     $itemid = $_GET['randomitemidentifier'];
      $data['userid'] = "no";
	 $data['admin'] = $this->accomodationmodel->populateadmindata($itemid);
	 $this->load->view("template/headerpagemin");

		
		 $this->load->view('admindata/adminpage',$data);
		$this->load->view("template/footerpage");
		
	}
  }
	
 
 public function displayregisteruser()
	{
	  $this->load->view("template/headerpagemin");
		
		$this->load->view('registeruser');
		$this->load->view("template/footerpage");
	}
	
 
   public function adminbio() {
	$session_data = $this->session->userdata('logged_in');

     $data['email'] = $session_data['email'];
 	$data['id'] = $session_data['id'];
	
	 	$this->load->view("template/headerpagemin");
	
		$this->load->view("template/studentnave");
		 $this->load->view('studentdata/biodata', $data);
		$this->load->view("template/footerpage");
     
    }
 
    public function adminfamily() {
	$session_data = $this->session->userdata('logged_in');

     $data['email'] = $session_data['email'];
 	$data['id'] = $session_data['id'];
	
	 	$this->load->view("template/headerpagemin");
		
		$this->load->view("template/studentnave");
		$this->load->view('studentdata/familydata', $data);
		$this->load->view("template/footerpage");
     
    }
 
   public function adminschool() {
	$session_data = $this->session->userdata('logged_in');

     $data['email'] = $session_data['email'];
 	$data['id'] = $session_data['id'];
	
	 	$this->load->view("template/headerpagemin");
	
		$this->load->view("template/studentnave");
		$this->load->view('studentdata/schoolbackground', $data);
		$this->load->view("template/footerpage");
     
    }
 
 
    public function adminaddress() {
	$session_data = $this->session->userdata('logged_in');

     $data['email'] = $session_data['email'];
 	$data['id'] = $session_data['id'];
	
	 	$this->load->view("template/headerpagemin");
		
		$this->load->view("template/studentnave");
		 $this->load->view('studentdata/addressdata', $data);
		$this->load->view("template/footerpage");
     
    }
 
 
  function registerusers()
    {
			 $lastname = $this->input->post("lastname");
		   	  $firstname = $this->input->post("firstname");
		  	 $email = $this->input->post("email");
           $status = $this->input->post("status");
 				$createdat = Date('Y-m-d H:i:s') ;
				
          //set validations
		  	
				$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|alpha|min_length[3]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[systemusers.email]');
		//$this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
		
			$data['errors'] = validation_errors();
		
		//validate form input
		if ($this->form_validation->run() == FALSE)
        {
		  $this->load->view("template/headerpagemin");
		
		$this->load->view('registeruser');
		$this->load->view("template/footerpage");
        }
		else
		{
			//insert the user registration details into database
		
			
			$data = array(
				'firstname' => $this->input->post('firstname'),
				'lastname' => $this->input->post('lastname'),
				'email' => $this->input->post('email'),
				'status' => $this->input->post('status'),
				'password' => $this->input->post('password'),
				'createdat' => $createdat
			);
			
			// insert form data into database
			if ($this->usermodel->inseradmintUser($data))
			{
				// send email
				if ($this->sendEmail($this->input->post('email')))
				{
					// successfully sent mail
					$this->session->set_flashdata('signupmsg','<div class="alert alert-success text-center">You are Successfully Registered! Please confirm the mail sent to your Email-account!!!</div>');
					 redirect('admin/registerform');
				}
				else
				{
					// error
					$this->session->set_flashdata('signupmsg','<div class="alert alert-danger text-center">Oops! Error in sending you email.  Please try again later!!!</div>');
					 redirect('admin/registerform');
				}
			}
			else
			{
				// error
				$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error.  Please try again later!!! but the sign -up is done</div>');
				 redirect('admin/registerform');
			}
		}
	}
	
	 public function addnewuser2()
    {
         	$createdat = Date('Y-m-d H:i:s') ;
					
		  	  $firstname = $this->input->post('firstname');
				 $lastname = $this->input->post('lastname');
				 $surname =$this->input->post("surname");
		  	  	  	    $password = $this->input->post("password");
				
				 $phone = $this->input->post('phone');
				 $email = $this->input->post('email');
				 $idno =$this->input->post('idno');
				 $country = $this->input->post('country');
				 $usertype =$this->input->post('usertype');
				 $gender = $this->input->post('gender');
				

			
		$this->form_validation->set_rules('firstname', 'firstname Name', 'trim|required|min_length[3]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|min_length[3]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[users.email]');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|md5');
		
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('pmsdata/allusers',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_user') == "user")
					   {
					
		  	  	  	
				
			
		
				
								$data=array(		
			'firstname'=>$firstname,
		  	'lastname'=>$lastname,
		  	'email'=>$email,
		  	'surname'=>$surname,
		  	'phone'=>$phone,
		'idno'=>$idno,
			'country'=>$country,
				'usertype'=>$usertype,
		  		'gender'=>$gender,
				'createdat' => $createdat
			
								);
							$usr_result = $this->accomodationmodel->sigadmin($data);
							
							//check if surname 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 Adde new User!</div>');
								
								 redirect('admin/displayallusers');
							}
							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 surname already exist! Just login</div>');
								
								 redirect('admin/displayallusers');
							}
					   }
					   else
					   {
							redirect('admin');
					   }
	    }
    }
	
	

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

   
 	$data['id'] = $session_data['id'];
        
		 $userid = $data['id'];
		 
		  $data['companyid'] = $session_data['companyid'];
	 $companyid = $data['companyid'];
		 $data['usertype'] = $session_data['usertype'];
	 $usertype = $data['usertype'];	
		
		$createddate=date('Y-m-d');
        	 $surname = trim($this->input->post("surname"));
		   	  $othername = trim($this->input->post("othername"));
		  	 $email = trim($this->input->post("email"));
         	 $service = trim($this->input->post("service"));
			  $usertype =$this->input->post('usertype');
			  $phone = trim($this->input->post("phone"));
         	 $password = trim($this->input->post("password"));
			          	 $cpassword = trim($this->input->post("cpassword"));
 $gender = $this->input->post('gender');

							$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[3]|max_length[100]|xss_clean');
							$this->form_validation->set_rules('cpassword', 'Confirm password', 'trim|required|min_length[3]|max_length[100]|xss_clean');
							$this->form_validation->set_rules('phone', 'Phone Number', 'trim|required|min_length[6]|max_length[100]|xss_clean');

							$this->form_validation->set_rules('surname', 'Surname', 'trim|required|min_length[2]|max_length[25]|xss_clean');
							//$this->form_validation->set_rules('othername', 'Other name', 'trim|required|min_length[2]|max_length[35]|xss_clean');
			$this->form_validation->set_rules('email', 'Email Account', 'trim|required|valid_email|min_length[5]');


			$data['errors'] = validation_errors();
			
			
			
			
											   $confirmaccount= $this->usermodel->confirmaccountcode($companyid);

				   if ($confirmaccount ==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 Entry Number  does not exist in our database. Make sure you contact us through :0780655987 or info@robisearch.com  for full/unlimited (premium) account or enter TEST-2017002 as Entry Number for test (limited) account to signup.</div>');
								
								 //redirect("login");
      	$this->load->view("template/headerpagemin");
		
		$this->load->view('signupuser',$data);
		$this->load->view("template/footerpage");
						   
						   return false;
						   }
									$mycompanyid=$confirmaccount[0]->id;
									
			
			
			
			
          if ($this->form_validation->run() == FALSE)
        {
			$this->load->view("template/headerpagemin");
		
		 $this->load->view('pmsdata/allusers',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_user') == "user")
					   {
						   
						   $confirmemail = $this->usermodel->confirmemail($email);
						   
						  
						   if ($confirmemail ==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>That email exist in our database. Just proceed to login or try again.</div>');
								
								
								 redirect('admin/displayallusers');
						   
						   return false;
						   }

						   if($phone!=""){
							   						   $confirmphone = $this->usermodel->confirmphone($phone);

       		   if ($confirmphone ==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>That Phone Number exist in our database. Just proceed to login or try again.</div>');
								


								 redirect('admin/displayallusers');
						   
						   return false;
						   }
	   		 }
						   
						   
						   
						   
						   
						   
						   
						   
						   
						   
   			 if($password!=$cpassword){
       		 //return "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>Password dont match...Try again</div>');
         redirect('admin/displayallusers');
	   		 }else
	   			 {
								
								$data=array(
								'firstname'=>$othername,
								'email'=>trim($email),
								'surname'=>$surname,
								'password'=>$password,
									'createddate'=>$createddate,
								'phone'=>$phone,
								'usertype'=>$usertype,

								'service'=>$service,
							'companyid'=>trim($mycompanyid),
							'gender'=>$gender,
								
								);
								$usr_result = $this->usermodel->signup($data);
							
							if ($usr_result ==TRUE) //active user record is present
							{
								   //$this->sendEmail($email);
								
						 $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 created account with Robisearch. You can just now login!</div>');
							
								 redirect('admin/displayallusers');
								
							}
							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> Account not created.. That email  exisist! Just Proceed to  login</div>');
								
								 redirect('admin/displayallusers');
							}
					   }
					   }
					   else
					   {
							 redirect('admin/displayallusers');
					   }
	    }
    }
	
	
	


	
	
	
			 public function updateuser()
    {
         $id = $this->input->post('id');
		  	  $firstname = $this->input->post('firstname');
				 $surname =$this->input->post("surname");
		  	  	  	    $password = $this->input->post("password");
				
				 $phone = $this->input->post('phone');
				 $email = $this->input->post('email');
				 $idno =$this->input->post('idno');
				 $country = $this->input->post('country');
				 $usertype =$this->input->post('usertype');
				 $gender = $this->input->post('gender');
				

			
		$this->form_validation->set_rules('firstname', 'firstname Name', 'trim|required|min_length[3]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('surname', 'Last Name', 'trim|required|min_length[3]|max_length[30]|xss_clean');
		$this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|md5');
		
			$data['errors'] = validation_errors();
          if ($this->form_validation->run() == FALSE)
        {
      	$this->load->view("template/headerpagemin");
		
		 $this->load->view('admindata/adminpage',$data);
		$this->load->view("template/footerpage");
		}
		 else
		{
					   //validation succeeds
					   if ($this->input->post('btn_updateuser') == "user")
					   {
					
		  	  	  	
				
			
		
				
								$data=array(		
			'firstname'=>$firstname,
		  	'email'=>$email,
		  	'surname'=>$surname,
		  	'phone'=>$phone,
		'idno'=>$idno,
			'country'=>$country,
				'usertype'=>$usertype,
		  		'gender'=>$gender,
			
								);
							$usr_result = $this->accomodationmodel->Updateusers($data,$id);
							
							//check if surname 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 Adde new User!</div>');
								
								 redirect('admin/displayallusers');
							}
							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 surname already exist! Just login</div>');
								
								 redirect('admin/displayallusers');
							}
					   }
					   else
					   {
							redirect('admin');
					   }
	    }
    }


	
function sendEmail($email)
{
$email = $this->input->post("email");
  $lastname = $this->input->post("lastname");
      $password = $this->input->post("password");
		$message = 'Dear '. $lastname .',<br /> Your login credentials are: <br/> password :'. $password. ' <br/> surname: '. $email .'<br/>Please click on the below activation link to verify your email address.<br /><br />  http://www.robisearch.com/Maincontrollerpage/verify/' . md5($email) . '<br />.<br /><br />Thanks<br />For choosing robiseach limited';
		
  
    $this->load->library('email'); // load email library
    $this->email->from('info@robisearch.com', 'Email Activation (Robisearch limited)');
    $this->email->to($email);
    $this->email->cc('robisearch@gmail.com'); 
    $this->email->subject('Verify Your Email Address');
    $this->email->message($message);
   // $this->email->attach('/path/to/file1.png'); // attach file
   // $this->email->attach('/path/to/file2.pdf');
     return $this->email->send();
   
}





public function uploadimage($view, $img_id,$userid) {
    
    $file= $_FILES["photo"]['name'];

if($file!=""){
		
	  
	  
	  

		$config['upload_path'] = is_dir($file).'docs/';
  		$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['overwrite'] = FALSE;
        $config["allowed_types"] = 'jpg|jpeg|png|gif|pdf|doc|docx|xlsx|xls|csv|xlsm|xltx|xltm';
        $config["max_size"] = 3024;
        $config['encrypt_name'] = FALSE;
      $this->load->library('upload', $config);
	  
	 

        if(!$this->upload->do_upload('photo')) {               
           echo  $this->data['error'] = $this->upload->display_errors();
           $this->session->set_flashdata('imagemsg', '<div class="alert alert-danger fade in">
						 <a href="#" class="close" data-dismiss="alert">&times;</a>
						  <strong>Error!</strong>Document could not be uploaded.. Please select correct image type  .e.g jpg,jpeg,png,gif.
						  </div>');
             redirect($view);
         
       
        } else {
				$data1=array(		
			'name'=>$new_name,
		  	'img_id'=>$img_id,
				'userid'=>$userid,
			
								);
		$usr_result1 = $this->usermodel->add($data1,'alldocuments');
         if($usr_result1 ==TRUE){
		 		$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 Added adocument!</div>');
 redirect($view);
		 }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>Document could not be uploaded.. Please try again..
						  </div>');
		  redirect($view);
		 }
        



        }  


}



		
		}

	
	












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

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