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

class Vehicle extends CI_Controller {  
     public function __construct() {
        parent::__construct();  
        date_default_timezone_set('Asia/Kolkata');
         $this->load->database();
         $this->load->model('Login_model');
          $this->load->helper('email');
          
//               $ip = $this->input->ip_address();

// $sql = "SELECT ip_adr FROM  allowed_ip where status = '0' and  ip_adr = '$ip' ";	
	
//         $rs = $this->Login_model->Execute($sql, array())->result_array();


//         if(empty($rs)){
            
//             echo '<div style= "text-align:center;background-color:red;color:white; margin-top:30px;"><h1>Your are not allowed to access this website.Please Contact Administration.</h1></div>';
            
            
//             die;
//         }
      
    }
    
   public function type(){
        if ($this->session->userdata('admin_login_id') == "" ) {
              redirect('Base/login/');
        } else {
        $this->load->view('header');
        $this->load->view('admin/vehicletype_list');
        $this->load->view('footer');
       }
    }
   
  
   public function type_add_old()
   {
        $name=$_POST['name'];
        $description=$_POST['description'];
        $status=$_POST['status'];
        
        
		$image=$_FILES['vehicle_image']['name'];
		$active_image=$_FILES['vehicle_active_image']['name'];
		
		
		if($_POST['formevent']=="submit")
		{
			$edate=date('Y-m-d H:i:s');
			if($name && $description && $image && $active_image)
			{
				$validate1 = $this->Login_model->select_column_where(['*'],'tbl_vehicletype',['name' => $name]);

				if(!empty($validate1))
				{
					$data=$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/type');
				}
				else
				{
					
					$time=time();
					
					$ext = pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
					$img_name='uploads/images/Vehicle/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['vehicle_image']);
					if ( $this->my_upload->uploaded == true  ) 
					{
						$this->my_upload->allowed         		= array('image/*');
						$this->my_upload->file_new_name_body    = 'img_'.$time;
						//$this->my_upload->image_convert 		= 'jpg';
						$this->my_upload->jpeg_quality 			= 100;	
						$this->my_upload->image_resize          = true;
						$this->my_upload->image_ratio_fill   = true;
						$this->my_upload->image_x               = 270;
						$this->my_upload->image_y         		= 168;

						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
						$this->my_upload->process('uploads/images/Vehicle/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}

					$ext = pathinfo($_FILES['vehicle_active_image']['name'], PATHINFO_EXTENSION);
					$activeimg_name='uploads/images/VehicleActive/img_'.$time.".".$ext;
					$this->my_upload->upload($_FILES['vehicle_active_image']);
					if ( $this->my_upload->uploaded == true  ) 
					{
						$this->my_upload->allowed         		= array('image/*');
						$this->my_upload->file_new_name_body    = 'img_'.$time;
						//$this->my_upload->image_convert 		= 'jpg';
						$this->my_upload->jpeg_quality 			= 100;	
						$this->my_upload->image_resize          = true;
						$this->my_upload->image_ratio_fill   = true;
						$this->my_upload->image_x               = 270;
						$this->my_upload->image_y         		= 168;

						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
						$this->my_upload->process('uploads/images/VehicleActive/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}

					$data = array(
					"name" => $name,
					"description"=>$description,
					"status"=>$status,
					"image"=>$img_name,
					"active_image"=>$activeimg_name,
					"entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehicletype',$data);

					$this->session->set_flashdata('success','Data inserted successfully');
					redirect('Vehicle/type');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/type');
			}
		}
		else if($_POST['formevent']=="update")
		{
			$id=$_POST['id'];
			if($name && $description)
			{
			    
			    $qry="SELECT * FROM tbl_vehicletype WHERE name = '$name' AND id <> '$id'";
			    $validate1=$this->db->query($qry)->row_array();
				
				if(!empty($validate1))
				{
					$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/type');
				}
				else
				{
				    
					$result_row=$this->Login_model->select_column_where(['*'],'tbl_vehicletype',['id'=>$id]);
					
					$result=$result_row[0];
					$img_name=$result['image'];
					$activeimg_name=$result['active_image'];
					$time=time();
					if($image)
					{
						unlink($result['image']);
						$ext = pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
    					$img_name='uploads/images/Vehicle/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['vehicle_image']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 270;
    						$this->my_upload->image_y         		= 168;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process('uploads/images/Vehicle/');
    						if ( $this->my_upload->processed == true ) 
    						{
    							$this->my_upload->clean();  
    						} 
    						
    					}
					}

					if($active_image)
					{
						if($result['active_image'])
						{
							unlink($result['active_image']);
						}
						
						$ext = pathinfo($_FILES['vehicle_active_image']['name'], PATHINFO_EXTENSION);
    					$activeimg_name='uploads/images/VehicleActive/img_'.$time.".".$ext;
    					$this->my_upload->upload($_FILES['vehicle_active_image']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 270;
    						$this->my_upload->image_y         		= 168;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process('uploads/images/VehicleActive/');
    						if ( $this->my_upload->processed == true ) 
    						{
    							$this->my_upload->clean();  
    						} 
    						
    					}
					}
					
					$data = array(
					"name" => $name,
					"description"=>$description,
					"status"=>$status,
					"image"=>$img_name,
					"active_image"=>$activeimg_name,
				    );
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehicletype',$data);

					$this->session->set_flashdata('success','Data updated successfully');    
					redirect('Vehicle/type');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/type');
			}
		}
		
		
   }
   
   
   public function type_add()
   {
        $name=$_POST['name'];
        $description=$_POST['description'];
        $status=$_POST['status'];
        
        
		$image=$_FILES['vehicle_image']['name'];
		$active_image=$_FILES['vehicle_active_image']['name'];
		
		
		if($_POST['formevent']=="submit")
		{
			$edate=date('Y-m-d H:i:s');
			if($name && $description && $image && $active_image)
			{
				$validate1 = $this->Login_model->select_column_where(['*'],'tbl_vehicletype',['name' => $name]);

				if(!empty($validate1))
				{
					$data=$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/type');
				}
				else
				{
					
					$time = time();
                    $upload_dir = 'uploads/images/Vehicle/';
                    $imageName = 'img_' . $time;
                    $file_ext = pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
                    $img_name = '';
					
					$this->my_upload->upload($_FILES['vehicle_image']);
					if ( $this->my_upload->uploaded == true  ) 
					{
						$this->my_upload->allowed         		= array('image/*');
						$this->my_upload->file_new_name_body    = 'img_'.$time;
						//$this->my_upload->image_convert 		= 'jpg';
						$this->my_upload->jpeg_quality 			= 100;	
						$this->my_upload->image_resize          = true;
						$this->my_upload->image_ratio_fill   = true;
						$this->my_upload->image_x               = 270;
						$this->my_upload->image_y         		= 168;

						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
						$this->my_upload->process($upload_dir);
						
						if ($this->my_upload->processed) 
						{
                            $uploaded_file_path = $upload_dir . $this->my_upload->file_dst_name;
                            $file_ext = pathinfo($uploaded_file_path, PATHINFO_EXTENSION);
                    
                            // Convert to WebP if necessary
                            if (strtolower($file_ext) != 'webp') {
                                $output_path = $upload_dir . $imageName . '.webp';
                                
                                if (convert_to_webp_image($uploaded_file_path, $output_path)) {
                                    unlink($uploaded_file_path);
                                    $img_name = $output_path;
                                } else {
                                    $img_name = $uploaded_file_path;
                                }
                            } else {
                                $img_name = $uploaded_file_path;
                            }
                            $this->my_upload->clean();
                        }
					}
					
					
					
                    $upload_dir = 'uploads/images/VehicleActive/';
                    $imageName = 'img_' . $time;
                    $file_ext = pathinfo($_FILES['vehicle_active_image']['name'], PATHINFO_EXTENSION);
                    $activeimg_name = '';
                    
					$this->my_upload->upload($_FILES['vehicle_active_image']);
					if ( $this->my_upload->uploaded == true  ) 
					{
						$this->my_upload->allowed         		= array('image/*');
						$this->my_upload->file_new_name_body    = 'img_'.$time;
						//$this->my_upload->image_convert 		= 'jpg';
						$this->my_upload->jpeg_quality 			= 100;	
						$this->my_upload->image_resize          = true;
						$this->my_upload->image_ratio_fill   = true;
						$this->my_upload->image_x               = 270;
						$this->my_upload->image_y         		= 168;

						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
						$this->my_upload->process($upload_dir);
						
						if ($this->my_upload->processed) 
						{
                            $uploaded_file_path = $upload_dir . $this->my_upload->file_dst_name;
                            $file_ext = pathinfo($uploaded_file_path, PATHINFO_EXTENSION);
                    
                            // Convert to WebP if necessary
                            if (strtolower($file_ext) != 'webp') {
                                $output_path = $upload_dir . $imageName . '.webp';
                                
                                if (convert_to_webp_image($uploaded_file_path, $output_path)) {
                                    unlink($uploaded_file_path);
                                    $activeimg_name = $output_path;
                                } else {
                                    $activeimg_name = $uploaded_file_path;
                                }
                            } else {
                                $activeimg_name = $uploaded_file_path;
                            }
                            $this->my_upload->clean();
                        }
					}

					$data = array(
					"name" => $name,
					"description"=>$description,
					"status"=>$status,
					"image"=>$img_name,
					"active_image"=>$activeimg_name,
					"entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehicletype',$data);

					$this->session->set_flashdata('success','Data inserted successfully');
					redirect('Vehicle/type');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/type');
			}
		}
		else if($_POST['formevent']=="update")
		{
			$id=$_POST['id'];
			if($name && $description)
			{
			    
			    $qry="SELECT * FROM tbl_vehicletype WHERE name = '$name' AND id <> '$id'";
			    $validate1=$this->db->query($qry)->row_array();
				
				if(!empty($validate1))
				{
					$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/type');
				}
				else
				{
				    
					$result_row=$this->Login_model->select_column_where(['*'],'tbl_vehicletype',['id'=>$id]);
					
					$result=$result_row[0];
					$img_name=$result['image'];
					$activeimg_name=$result['active_image'];
					$time=time();
					if($image)
					{
						unlink($result['image']);
						
    					$upload_dir = 'uploads/images/Vehicle/';
                        $imageName = 'img_' . $time;
                        $file_ext = pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
                        $img_name = '';
    					
    					$this->my_upload->upload($_FILES['vehicle_image']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 270;
    						$this->my_upload->image_y         		= 168;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process($upload_dir);
    						
    						if ($this->my_upload->processed) 
    						{
                                $uploaded_file_path = $upload_dir . $this->my_upload->file_dst_name;
                                $file_ext = pathinfo($uploaded_file_path, PATHINFO_EXTENSION);
                        
                                // Convert to WebP if necessary
                                if (strtolower($file_ext) != 'webp') {
                                    $output_path = $upload_dir . $imageName . '.webp';
                                    
                                    if (convert_to_webp_image($uploaded_file_path, $output_path)) {
                                        unlink($uploaded_file_path);
                                        $img_name = $output_path;
                                    } else {
                                        $img_name = $uploaded_file_path;
                                    }
                                } else {
                                    $img_name = $uploaded_file_path;
                                }
                                $this->my_upload->clean();
                            }
    					}
    					
    					
					}

					if($active_image)
					{
						if($result['active_image'])
						{
							unlink($result['active_image']);
						}
    					
    					$upload_dir = 'uploads/images/VehicleActive/';
                        $imageName = 'img_' . $time;
                        $file_ext = pathinfo($_FILES['vehicle_active_image']['name'], PATHINFO_EXTENSION);
                        $activeimg_name = '';
                        $this->my_upload->upload($_FILES['vehicle_active_image']);
    					
    					if ($this->my_upload->uploaded == true  ) 
					    {
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 270;
    						$this->my_upload->image_y         		= 168;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process($upload_dir);
    						if ($this->my_upload->processed) 
    						{
                                $uploaded_file_path = $upload_dir . $this->my_upload->file_dst_name;
                                $file_ext = pathinfo($uploaded_file_path, PATHINFO_EXTENSION);
                        
                                // Convert to WebP if necessary
                                if (strtolower($file_ext) != 'webp') {
                                    $output_path = $upload_dir . $imageName . '.webp';
                                    
                                    if (convert_to_webp_image($uploaded_file_path, $output_path)) {
                                        unlink($uploaded_file_path);
                                        $activeimg_name = $output_path;
                                    } else {
                                        $activeimg_name = $uploaded_file_path;
                                    }
                                } else {
                                    $activeimg_name = $uploaded_file_path;
                                }
                                $this->my_upload->clean();
                            }
						
						
						
					    }
    					
    					
    					
					}
					
					$data = array(
					"name" => $name,
					"description"=>$description,
					"status"=>$status,
					"image"=>$img_name,
					"active_image"=>$activeimg_name,
				    );
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehicletype',$data);

					$this->session->set_flashdata('success','Data updated successfully');    
					redirect('Vehicle/type');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/type');
			}
		}
		
		
   }
   
   
   public function get_typelist()
   {
       
          $draw=$_POST['draw'];       
          $fltstatus=$_POST['fltstatus'];
          $startdate='';
          $enddate='';
          
          if($_POST['daterange'])
          {
              $ex=explode(" - ",$_POST['daterange']);
              if(!empty($ex))
              {
                  $fromdate=$ex[0];
                  $todate=$ex[1];
              
                  $date = str_replace('/', '-', $fromdate);
                  $startdate=date('Y-m-d', strtotime($date));
                  
          
                  $date1 = str_replace('/', '-', $todate);
                  $enddate=date('Y-m-d', strtotime($date1));
              }
          }
          
          
          $datefilter_qry="";
          if($startdate && $enddate)
          {
            $datefilter_qry=" AND STR_TO_DATE(entry_date,'%Y-%m-%d') BETWEEN '$startdate' AND '$enddate'";
          }          
        
          $search_qry="";      
        
          $extra_qry='';
          if($_POST['searchvalue'])
          {
              $searchValue=trim($_POST['searchvalue']);      
            
              $search_qry=" AND (name = '$searchValue' OR description = '$searchValue')";    
           
          }

            
          
           $sql = "SELECT * FROM tbl_vehicletype WHERE status LIKE '$fltstatus' $datefilter_qry $search_qry ORDER BY id DESC";
           
          
            $limit=" LIMIT ".$_REQUEST['start']." ,".$_REQUEST['length'];
            $totalRecords =$this->db->query($sql)->num_rows();
            $result=$this->db->query($sql.$limit)->result();
          
          if(!empty($result))
          {
              $i=0;
              $minus_length=0;
              if($_REQUEST['start'] > 0)
              {
                  $minus_length=$_REQUEST['start'];
              }
              $index=$totalRecords-$minus_length;
              
              foreach($result as $r)
              {         
                  
                  if($r->status==1){
                      
                       $sts = '<span class="text-success">Active</span>';
                  }else{
                      $sts = '<span class="text-danger">Inactive</span>';
                  }
               
               
                $response['list'][$i]['i']=$index;
                $response['list'][$i]['name']=$r->name;
                $response['list'][$i]['description']=$r->description;
                $response['list'][$i]['image']='<a href="'.base_url().$r->image.'" target="_blank"><img src="'.base_url().$r->image.'" width="120px" height="80px"></a>';
                $response['list'][$i]['active_image']='<a href="'.base_url().$r->active_image.'" target="_blank"><img src="'.base_url().$r->active_image.'" width="120px" height="80px"></a>';
                $response['list'][$i]['entry_date']=date("d-m-Y h:i:s a", strtotime(trim($r->entry_date)));  
                $response['list'][$i]['status']=$sts;
                
                $action='<a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="Update" onclick="editdata('.$r->id.')" aria-hidden="true" style="color:#007bff;font-size:27px">
						 <i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
						<a href="javascript:void(0);" class="delete" aria-hidden="true" data-toggle="tooltip" onclick="deletedata('.$r->id.');" title="Delete" style="color:red;font-size:27px;margin-left:3px;" >
								<i class="fa fa-times-circle"></i>
								</a>';
								
								
                $response['list'][$i]['action']=$action;
                
                  $i++;
                  $index--;
              }
          }
          else
          {
              $response['list']=[];
          }
          
          
          $json_data = array(
          "draw"            => intval( $_REQUEST['draw'] ),   
          "recordsTotal"    => intval($totalRecords ),  
          "recordsFiltered" => intval($totalRecords),
          "data"            => $response['list']   // total data array
          );
          
          echo json_encode($json_data);
      
   }
   
    public function delete_type($id)
   {
       
       $result = $this->Login_model->select_column_where(['image','active_image'],
        'tbl_vehicletype',['id' => $id]);
        
      
       if(!empty($result))
       {
    		if($result[0]['image'])
    		{
    			unlink($result[0]['image']);
    		}
    
    		if($result[0]['active_image'])
    		{
    			unlink($result[0]['active_image']);
    		}
    		
    		$this->db->where('id',$id);
    		$this->db->delete('tbl_vehicletype');
    		$this->session->set_flashdata('success','Data successfully deleted');
       }
    		redirect('Vehicle/type');
   }
   
   public function edit_type()
   {
        header("Access-Control-Allow-Origin: *");
    	header("Content-Type: application/json; charset=UTF-8");
    	$status=0;
    	$message='Invalid Request';
    	
    	$id=$_POST['id'];
    	if($id)
    	{
    		 $result = $this->Login_model->select_column_where(['*'],
            'tbl_vehicletype',['id' => $id]);
    		
    		if(!empty($result))
    		{
    		    $response['id']=$result[0]['id'];
    		    $response['name']=$result[0]['name'];
    		    $response['description']=$result[0]['description'];
    		    $response['image']=$result[0]['image'];
    		    $response['active_image']=$result[0]['active_image'];
    		    $response['status']=$result[0]['status'];
    		}
    		
    		
    		$status=1;
    		$message='success';
    			
    		
    	}
    	$response['status']=$status;
    	$response['message']=$message;
    	echo json_encode($response);
   }
    
      
   public function make(){
        if ($this->session->userdata('admin_login_id') == "" ) {
              redirect('Base/login/');
        } else {
        $this->load->view('header');
        $this->load->view('admin/vehiclemake_list');
        $this->load->view('footer');
       }
    }
    
    public function driver_bookinghistory($id='')
    {
        if ($this->session->userdata('admin_login_id') == "" ) {
              redirect('Base/login/');
        } else {
            
             $qry="SELECT v.*,dr.*,tv.number,dr.id as driver_autoid,md.user_id,md.f_name  
                FROM tbl_booking v
              INNER JOIN  tbl_user md ON md.id=v.user_id
              INNER JOIN tbl_vehicle tv ON tv.driver_id = v.driver_id
              LEFT JOIN tbl_driver dr ON v.driver_id = dr.id
              WHERE v.driver_id = $id";
              $data['result']=$this->db->query($qry)->result_array();
              $data['id']=$id;
        $this->load->view('header');
        $this->load->view('admin/driver_history',$data);
        $this->load->view('footer');
       }
        
    }
   
    
   public function make_add()
   {
        $name=$_POST['name'];
        $status=$_POST['status'];
        
        
		if($_POST['formevent']=="submit")
		{
			$edate=date('Y-m-d H:i:s');
			if($name)
			{
				$validate1 = $this->Login_model->select_column_where(['*'],'tbl_vehiclemake',['name' => $name]);

				if(!empty($validate1))
				{
					$data=$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/make');
				}
				else
				{
					
					$data = array(
					"name" => $name,
					"status"=>$status,
				    "entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehiclemake',$data);

					$this->session->set_flashdata('success','Data inserted successfully');
					redirect('Vehicle/make');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/make');
			}
		}
		else if($_POST['formevent']=="update")
		{
			$id=$_POST['id'];
			if($name)
			{
			    
			    $qry="SELECT * FROM tbl_vehiclemake WHERE name = '$name' AND id <> '$id'";
			    $validate1=$this->db->query($qry)->row_array();
				
				if(!empty($validate1))
				{
					$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/make');
				}
				else
				{
				    
					$data = array(
					"name" => $name,
				    "status"=>$status,
					);
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehiclemake',$data);

					$this->session->set_flashdata('success','Data updated successfully');    
					redirect('Vehicle/make');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/make');
			}
		}
   }
   
   public function get_makelist()
   {
       
          $draw=$_POST['draw'];       
          $fltstatus=$_POST['fltstatus'];
          $startdate='';
          $enddate='';
          
          if($_POST['daterange'])
          {
              $ex=explode(" - ",$_POST['daterange']);
              if(!empty($ex))
              {
                  $fromdate=$ex[0];
                  $todate=$ex[1];
              
                  $date = str_replace('/', '-', $fromdate);
                  $startdate=date('Y-m-d', strtotime($date));
                  
          
                  $date1 = str_replace('/', '-', $todate);
                  $enddate=date('Y-m-d', strtotime($date1));
              }
          }
          
          
          $datefilter_qry="";
          if($startdate && $enddate)
          {
            $datefilter_qry=" AND STR_TO_DATE(entry_date,'%Y-%m-%d') BETWEEN '$startdate' AND '$enddate'";
          }          
        
          $search_qry="";      
        
          $extra_qry='';
          if($_POST['searchvalue'])
          {
              $searchValue=trim($_POST['searchvalue']);      
            
              $search_qry=" AND (name = '$searchValue')";    
           
          }

            
          
           $sql = "SELECT * FROM tbl_vehiclemake WHERE status LIKE '$fltstatus' $datefilter_qry $search_qry ORDER BY id DESC";
           
          
            $limit=" LIMIT ".$_REQUEST['start']." ,".$_REQUEST['length'];
            $totalRecords =$this->db->query($sql)->num_rows();
            $result=$this->db->query($sql.$limit)->result();
          
          if(!empty($result))
          {
              $i=0;
              $minus_length=0;
              if($_REQUEST['start'] > 0)
              {
                  $minus_length=$_REQUEST['start'];
              }
              $index=$totalRecords-$minus_length;
              
              foreach($result as $r)
              {         
                  
                  if($r->status==1){
                      
                       $sts = '<span class="text-success">Active</span>';
                  }else{
                      $sts = '<span class="text-danger">Inactive</span>';
                  }
               
               
                $response['list'][$i]['i']=$index;
                $response['list'][$i]['name']=$r->name;
                $response['list'][$i]['entry_date']=date("d-m-Y h:i:s a", strtotime(trim($r->entry_date)));  
                $response['list'][$i]['status']=$sts;
                
                $action='<a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="Update" onclick="editdata('.$r->id.',\''.$r->name.'\','.$r->status.')" aria-hidden="true" style="color:#007bff;font-size:27px">
						 <i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
						<a href="javascript:void(0);" class="delete" aria-hidden="true" data-toggle="tooltip" onclick="deletedata('.$r->id.');" title="Delete" style="color:red;font-size:27px;margin-left:3px;" >
								<i class="fa fa-times-circle"></i>
								</a>';
								
								
                $response['list'][$i]['action']=$action;
                
                  $i++;
                  $index--;
              }
          }
          else
          {
              $response['list']=[];
          }
          
          
          $json_data = array(
          "draw"            => intval( $_REQUEST['draw'] ),   
          "recordsTotal"    => intval($totalRecords ),  
          "recordsFiltered" => intval($totalRecords),
          "data"            => $response['list']   // total data array
          );
          
          echo json_encode($json_data);
      
   }  
   
    public function delete_make($id)
   {
       
      
       	$this->db->where('id',$id);
		$this->db->delete('tbl_vehiclemake');
		$this->session->set_flashdata('success','Data successfully deleted');
   
    		redirect('Vehicle/make');
   }
   
   
    public function model(){
        if ($this->session->userdata('admin_login_id') == "" ) {
              redirect('Base/login/');
        } else {
            
            $makelist = $this->Login_model->select_column_where(['*'],'tbl_vehiclemake',['status' => 1]);
            
            $data=array(
                'makelist'=>$makelist
                );
        $this->load->view('header');
        $this->load->view('admin/vehiclemodel_list',$data);
        $this->load->view('footer');
       }
    }
    
    
    public function model_add()
   {
        $make_id=$_POST['make_id'];
        $name=$_POST['name'];
        $status=$_POST['status'];
        
        
		if($_POST['formevent']=="submit")
		{
			$edate=date('Y-m-d H:i:s');
			if($make_id && $name)
			{
				$validate1 = $this->Login_model->select_column_where(['*'],'tbl_vehiclemodel',['model_name' => $name]);

				if(!empty($validate1))
				{
					$data=$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/model');
				}
				else
				{
					
					$data = array(
					"make_id" => $make_id,
					"model_name" => $name,
					"status"=>$status,
				    "entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehiclemodel',$data);

					$this->session->set_flashdata('success','Data inserted successfully');
					redirect('Vehicle/model');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/model');
			}
		}
		else if($_POST['formevent']=="update")
		{
			$id=$_POST['id'];
			if($name)
			{
			    
			    $qry="SELECT * FROM tbl_vehiclemodel WHERE model_name = '$name' AND id <> '$id'";
			   
			    $validate1=$this->db->query($qry)->row_array();
				
				if(!empty($validate1))
				{
					$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/model');
				}
				else
				{
				    
					$data = array(
					"make_id" => $make_id,
					"model_name" => $name,
					"status"=>$status,
					);
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehiclemodel',$data);
                   
					$this->session->set_flashdata('success','Data updated successfully');    
					redirect('Vehicle/model');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/model');
			}
		}
   }
   
   public function get_modellist()
   {
       
          $draw=$_POST['draw'];       
          $fltstatus=$_POST['fltstatus'];
          $startdate='';
          $enddate='';
          
          if($_POST['daterange'])
          {
              $ex=explode(" - ",$_POST['daterange']);
              if(!empty($ex))
              {
                  $fromdate=$ex[0];
                  $todate=$ex[1];
              
                  $date = str_replace('/', '-', $fromdate);
                  $startdate=date('Y-m-d', strtotime($date));
                  
          
                  $date1 = str_replace('/', '-', $todate);
                  $enddate=date('Y-m-d', strtotime($date1));
              }
          }
          
          
          $datefilter_qry="";
          if($startdate && $enddate)
          {
            $datefilter_qry=" AND STR_TO_DATE(md.entry_date,'%Y-%m-%d') BETWEEN '$startdate' AND '$enddate'";
          }          
        
          $search_qry="";      
        
          $extra_qry='';
          if($_POST['searchvalue'])
          {
              $searchValue=trim($_POST['searchvalue']);      
            
              $search_qry=" AND (md.model_name = '$searchValue')";    
           
          }

            
          
           $sql = "SELECT md.*,mk.name FROM tbl_vehiclemodel md
           INNER JOIN tbl_vehiclemake mk ON mk.id=md.make_id
           WHERE md.status LIKE '$fltstatus' $datefilter_qry $search_qry ORDER BY md.id DESC";
           
          
            $limit=" LIMIT ".$_REQUEST['start']." ,".$_REQUEST['length'];
            $totalRecords =$this->db->query($sql)->num_rows();
            $result=$this->db->query($sql.$limit)->result();
          
          if(!empty($result))
          {
              $i=0;
              $minus_length=0;
              if($_REQUEST['start'] > 0)
              {
                  $minus_length=$_REQUEST['start'];
              }
              $index=$totalRecords-$minus_length;
              
              foreach($result as $r)
              {         
                  
                  if($r->status==1){
                      
                       $sts = '<span class="text-success">Active</span>';
                  }else{
                      $sts = '<span class="text-danger">Inactive</span>';
                  }
               
               
                $response['list'][$i]['i']=$index;
                $response['list'][$i]['make_name']=$r->name;
                $response['list'][$i]['model_name']=$r->model_name;
                $response['list'][$i]['entry_date']=date("d-m-Y h:i:s a", strtotime(trim($r->entry_date)));  
                $response['list'][$i]['status']=$sts;
                
                $action='<a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="Update" onclick="editdata('.$r->id.','.$r->make_id.',\''.$r->model_name.'\','.$r->status.')" aria-hidden="true" style="color:#007bff;font-size:27px">
						 <i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
						<a href="javascript:void(0);" class="delete" aria-hidden="true" data-toggle="tooltip" onclick="deletedata('.$r->id.');" title="Delete" style="color:red;font-size:27px;margin-left:3px;" >
								<i class="fa fa-times-circle"></i>
								</a>';
								
								
                $response['list'][$i]['action']=$action;
                
                  $i++;
                  $index--;
              }
          }
          else
          {
              $response['list']=[];
          }
          
          
          $json_data = array(
          "draw"            => intval( $_REQUEST['draw'] ),   
          "recordsTotal"    => intval($totalRecords ),  
          "recordsFiltered" => intval($totalRecords),
          "data"            => $response['list']   // total data array
          );
          
          echo json_encode($json_data);
      
   }  
   
   public function delete_model($id)
   {
       
      
       	$this->db->where('id',$id);
		$this->db->delete('tbl_vehiclemodel');
		$this->session->set_flashdata('success','Data successfully deleted');
   
    		redirect('Vehicle/model');
   }
   
   
    public function manage(){
        if ($this->session->userdata('admin_login_id') == "" ) {
              redirect('Base/login/');
        } else {
            
             $makelist = $this->Login_model->select_column_where(['*'],'tbl_vehiclemake',['status' => 1]);
             $driverlist = $this->Login_model->select_column_where(['*'],'tbl_driver',['status' => 1]);
             $typelist = $this->Login_model->select_column_where(['*'],'tbl_vehicletype',['status' => 1]);
             $data=array(
                'makelist'=>$makelist,
                'driverlist'=>$driverlist,
                'typelist'=>$typelist
            );
                
            $this->load->view('header');
            $this->load->view('admin/vehiclemanage_list',$data);
            $this->load->view('footer');
       }
    }
   
   
   public function makewise_model()
   {
       $make_id=$_POST['make_id'];
        ?>
        <option selected="selected" value="">Select</option>
        <?php
       if($make_id)
       {
            $modellist = $this->Login_model->select_column_where(['*'],'tbl_vehiclemodel',['make_id' => $make_id,'status'=>1]);
            
            if(!empty($modellist))
            {
               
                foreach($modellist as $row)
                {
                    ?>
                    <option value="<?php echo $row['id']?>"><?php echo $row['model_name'] ?></option>
                    <?php
                }
            }
       }
   }
   
   
   public function add_old()
   {
        $driver_id=$_POST['driver_id'];
        $status=$_POST['status'];
        $make_id=$_POST['make_id'];
        $model_id=$_POST['model_id'];
        $vehicle_type=$_POST['vehicle_type'];
        $handicap=$_POST['handicap'];
        $childseat=$_POST['childseat'];
        
        $vehicle_number=$_POST['vehicle_number'];
        
        $vehicle_color=$_POST['vehicle_color'];
        $vehicle_year=$_POST['vehicle_year'];
        $insurance_status=$_POST['insurance_status'];
        
		$insurance_img=$_FILES['insurance']['name'];
		$edate=date('Y-m-d H:i:s');

		if($_POST['formevent']=="submit")
		{
			
			if($driver_id && $make_id && $model_id && (sizeof($vehicle_type) > 0) 
			&& $vehicle_number && $vehicle_color && $vehicle_year)
			{
				$validate1 = $this->Login_model->select_column_where(['*'],'tbl_vehicle',['driver_id' => $driver_id]);

				if(!empty($validate1))
				{
					$data=$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/manage');
				}
				else
				{
					
					$time=time();
					$img_name='';
					if($insurance_img)
					{
    					$ext = pathinfo($_FILES['insurance']['name'], PATHINFO_EXTENSION);
    					$img_name='uploads/images/Insurance/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['insurance']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 1000;
    						$this->my_upload->image_y         		= 1000;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process('uploads/images/Insurance/');
    						if ( $this->my_upload->processed == true ) 
    						{
    							$this->my_upload->clean();  
    						} 
    						
    					}

					}
					
					$data = array(
					"driver_id" => $driver_id,
					"make_id"=>$make_id,
					"model_id"=>$model_id,
				// 	"handicap"=>$handicap,
				// 	"childseat"=>$childseat,
					"number"=>$vehicle_number,
					"color"=>$vehicle_color,
					"year"=>$vehicle_year,
					"status"=>$status,
					"insurance_image"=>$img_name,
					"insurance_status"=>$insurance_status,
					"entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehicle',$data);
                    $vehicle_id=$this->db->insert_id();
        
                    if(sizeof($vehicle_type) > 0)
                    {
                        for($i=0;$i<sizeof($vehicle_type);$i++)
                        {
                            $data_sub = array(
        					"vehicle_id" => $vehicle_id,
        					"type_id"=>$vehicle_type[$i],
        					"entry_date"=>$edate,
        					);
        
        					$this->Login_model->insert('tbl_map_vehicletype',$data_sub);
                        }
                    }
					$this->session->set_flashdata('success','Data inserted successfully');
					redirect('Vehicle/manage');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/manage');
			}
		}
		else if($_POST['formevent']=="update")
		{
			$id=$_POST['id'];
			if($driver_id && $make_id && $model_id && (sizeof($vehicle_type) > 0)
			&& $vehicle_number && $vehicle_color && $vehicle_year)
			{
			    
			    $qry="SELECT * FROM tbl_vehicle WHERE driver_id = '$driver_id' AND id <> '$id'";
			    $validate1=$this->db->query($qry)->row_array();
				
				if(!empty($validate1))
				{
					$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/manage');
				}
				else
				{
				    
					$result_row=$this->Login_model->select_column_where(['*'],'tbl_vehicle',['id'=>$id]);
					
					$result=$result_row[0];
					$img_name=$result['insurance_image'];
					
					$time=time();
					if($insurance_img)
					{
						unlink($result['insurance_image']);
						$ext = pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
    					$img_name='uploads/images/Insurance/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['insurance']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 1000;
						    $this->my_upload->image_y         		= 1000;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process('uploads/images/Insurance/');
    						if ( $this->my_upload->processed == true ) 
    						{
    							$this->my_upload->clean();  
    						} 
    						
    					}
					}

					
					$data = array(
				    "driver_id" => $driver_id,
					"make_id"=>$make_id,
					"model_id"=>$model_id,
				// 	"handicap"=>$handicap,
				// 	"childseat"=>$childseat,
					"number"=>$vehicle_number,
					"color"=>$vehicle_color,
					"year"=>$vehicle_year,
					"status"=>$status,
					"insurance_image"=>$img_name,
					"insurance_status"=>$insurance_status,
				    );
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehicle',$data);

                    $this->db->where('vehicle_id',$id);
    		        $this->db->delete('tbl_map_vehicletype');
    		
                    if(sizeof($vehicle_type) > 0)
                    {
                        for($i=0;$i<sizeof($vehicle_type);$i++)
                        {
                            $data_sub = array(
        					"vehicle_id" => $id,
        					"type_id"=>$vehicle_type[$i],
        					"entry_date"=>$edate,
        					);
        
        					$this->Login_model->insert('tbl_map_vehicletype',$data_sub);
                        }
                    }
                    
					$this->session->set_flashdata('success','Data updated successfully'); 
					
					$previous_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
					
					redirect($previous_url);
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				
				
				
				
				
				redirect('Vehicle/manage');
			}
		}
   }
   
   public function add()
   {
        $driver_id=$_POST['driver_id'];
        $status=$_POST['status'];
        $make_id=$_POST['make_id'];
        $model_id=$_POST['model_id'];
        $vehicle_type=$_POST['vehicle_type'];
        $handicap=$_POST['handicap'];
        $childseat=$_POST['childseat'];
        
        $vehicle_number=$_POST['vehicle_number'];
        
        $vehicle_color=$_POST['vehicle_color'];
        $vehicle_year=$_POST['vehicle_year'];
        $insurance_status=$_POST['insurance_status'];
        
		$insurance_img=$_FILES['insurance']['name'];
		$edate=date('Y-m-d H:i:s');

		if($_POST['formevent']=="submit")
		{
			
			if($driver_id && $make_id && $model_id && (sizeof($vehicle_type) > 0) 
			&& $vehicle_number && $vehicle_color && $vehicle_year)
			{
				$validate1 = $this->Login_model->select_column_where(['*'],'tbl_vehicle',['driver_id' => $driver_id]);

				if(!empty($validate1))
				{
					$data=$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/manage');
				}
				else
				{
					
					$time=time();
					$img_name='';
					if($insurance_img)
					{
					    
					    
					    $upload_dir = 'uploads/images/Insurance/';
                        $imageName = 'img_' . $time;
                        $file_ext = pathinfo($_FILES['insurance']['name'], PATHINFO_EXTENSION);
    					
    					$this->my_upload->upload($_FILES['insurance']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 1000;
    						$this->my_upload->image_y         		= 1000;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process($upload_dir);
                    
                            if ($this->my_upload->processed) {
                                $uploaded_file_path = $upload_dir . $this->my_upload->file_dst_name;
                                $file_ext = pathinfo($uploaded_file_path, PATHINFO_EXTENSION);
                        
                                // Convert to WebP if necessary
                                if (strtolower($file_ext) != 'webp') {
                                    $output_path = $upload_dir . $imageName . '.webp';
                                    
                                    if (convert_to_webp_image($uploaded_file_path, $output_path)) {
                                        // Remove the original file after conversion
                                        unlink($uploaded_file_path);
                                        $img_name = $output_path;
                                    } else {
                                        // If conversion fails, keep the original file
                                        $img_name = $uploaded_file_path;
                                    }
                                } else {
                                    // If the uploaded file is already a WebP image
                                    $img_name = $uploaded_file_path;
                                }
                        
                                // Clean up the upload object
                                $this->my_upload->clean();
                            }
                        }
					}
					
					$data = array(
					"driver_id" => $driver_id,
					"make_id"=>$make_id,
					"model_id"=>$model_id,
				// 	"handicap"=>$handicap,
				// 	"childseat"=>$childseat,
					"number"=>$vehicle_number,
					"color"=>$vehicle_color,
					"year"=>$vehicle_year,
					"status"=>$status,
					"insurance_image"=>$img_name,
					"insurance_status"=>$insurance_status,
					"entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehicle',$data);
                    $vehicle_id=$this->db->insert_id();
        
                    if(sizeof($vehicle_type) > 0)
                    {
                        for($i=0;$i<sizeof($vehicle_type);$i++)
                        {
                            $data_sub = array(
        					"vehicle_id" => $vehicle_id,
        					"type_id"=>$vehicle_type[$i],
        					"entry_date"=>$edate,
        					);
        
        					$this->Login_model->insert('tbl_map_vehicletype',$data_sub);
                        }
                    }
					$this->session->set_flashdata('success','Data inserted successfully');
					redirect('Vehicle/manage');
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				redirect('Vehicle/manage');
			}
		}
		else if($_POST['formevent']=="update")
		{
			$id=$_POST['id'];
			if($driver_id && $make_id && $model_id && (sizeof($vehicle_type) > 0)
			&& $vehicle_number && $vehicle_color && $vehicle_year)
			{
			    
			    $qry="SELECT * FROM tbl_vehicle WHERE driver_id = '$driver_id' AND id <> '$id'";
			    $validate1=$this->db->query($qry)->row_array();
				
				if(!empty($validate1))
				{
					$this->session->set_flashdata('error','Data already exist');
					redirect('Vehicle/manage');
				}
				else
				{
				    
					$result_row=$this->Login_model->select_column_where(['*'],'tbl_vehicle',['id'=>$id]);
					
					$result=$result_row[0];
					$img_name=$result['insurance_image'];
					
					$time=time();
					if($insurance_img)
					{
						unlink($result['insurance_image']);
						
						$upload_dir = 'uploads/images/Insurance/';
                        $imageName = 'img_' . $time;
                        $file_ext = pathinfo($_FILES['vehicle_image']['name'], PATHINFO_EXTENSION);
                        
                        $img_name='';
    					
    					$this->my_upload->upload($_FILES['insurance']);
    					if ( $this->my_upload->uploaded == true  ) 
    					{
    						$this->my_upload->allowed         		= array('image/*');
    						$this->my_upload->file_new_name_body    = 'img_'.$time;
    						//$this->my_upload->image_convert 		= 'jpg';
    						$this->my_upload->jpeg_quality 			= 100;	
    						$this->my_upload->image_resize          = true;
    						$this->my_upload->image_ratio_fill   = true;
    						$this->my_upload->image_x               = 1000;
						    $this->my_upload->image_y         		= 1000;
    
    						//	DON'T FORGET TO CREATE A FOLDER IMAGES (same level of 'application')
    						$this->my_upload->process($upload_dir);
                    
                            if ($this->my_upload->processed) {
                                $uploaded_file_path = $upload_dir . $this->my_upload->file_dst_name;
                                $file_ext = pathinfo($uploaded_file_path, PATHINFO_EXTENSION);
                        
                                // Convert to WebP if necessary
                                if (strtolower($file_ext) != 'webp') {
                                    $output_path = $upload_dir . $imageName . '.webp';
                                    
                                    if (convert_to_webp_image($uploaded_file_path, $output_path)) {
                                        // Remove the original file after conversion
                                        unlink($uploaded_file_path);
                                        $img_name = $output_path;
                                    } else {
                                        // If conversion fails, keep the original file
                                        $img_name = $uploaded_file_path;
                                    }
                                } else {
                                    // If the uploaded file is already a WebP image
                                    $img_name = $uploaded_file_path;
                                }
                        
                                // Clean up the upload object
                                $this->my_upload->clean();
                            }
                        }
    					
    					
    					
    					
					}

					
					$data = array(
				    "driver_id" => $driver_id,
					"make_id"=>$make_id,
					"model_id"=>$model_id,
				// 	"handicap"=>$handicap,
				// 	"childseat"=>$childseat,
					"number"=>$vehicle_number,
					"color"=>$vehicle_color,
					"year"=>$vehicle_year,
					"status"=>$status,
					"insurance_image"=>$img_name,
					"insurance_status"=>$insurance_status,
				    );
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehicle',$data);

                    $this->db->where('vehicle_id',$id);
    		        $this->db->delete('tbl_map_vehicletype');
    		
                    if(sizeof($vehicle_type) > 0)
                    {
                        for($i=0;$i<sizeof($vehicle_type);$i++)
                        {
                            $data_sub = array(
        					"vehicle_id" => $id,
        					"type_id"=>$vehicle_type[$i],
        					"entry_date"=>$edate,
        					);
        
        					$this->Login_model->insert('tbl_map_vehicletype',$data_sub);
                        }
                    }
                    
					$this->session->set_flashdata('success','Data updated successfully'); 
					
					$previous_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
					
					redirect($previous_url);
				}
			}
			else
			{
				$this->session->set_flashdata('error','Please fill in all required field');
				
				
				
				
				
				redirect('Vehicle/manage');
			}
		}
   }
   
   public function list()
   {
       
          $draw=$_POST['draw'];       
          $fltstatus=$_POST['fltstatus'];
          $startdate='';
          $enddate='';
          
          
          
          if($_POST['daterange'])
          {
              $ex=explode(" - ",$_POST['daterange']);
              if(!empty($ex))
              {
                  $fromdate=$ex[0];
                  $todate=$ex[1];
              
                  $date = str_replace('/', '-', $fromdate);
                  $startdate=date('Y-m-d', strtotime($date));
                  
          
                  $date1 = str_replace('/', '-', $todate);
                  $enddate=date('Y-m-d', strtotime($date1));
              }
          }
          
          
          $datefilter_qry="";
          if($startdate && $enddate)
          {
            $datefilter_qry=" AND STR_TO_DATE(v.entry_date,'%Y-%m-%d') BETWEEN '$startdate' AND '$enddate'";
          }          
        
          $search_qry="";      
        
          $extra_qry='';
          if($_POST['searchvalue'])
          {
              $searchValue=trim($_POST['searchvalue']);      
            
              $search_qry=" WHERE (tmp.model_name LIKE '%$searchValue%' OR tmp.make_name LIKE '%$searchValue%' OR tmp.type LIKE '%$searchValue%' OR tmp.driver_name LIKE '%$searchValue%' OR tmp.driverid LIKE '%$searchValue%')";    
           
          }

            
          
          $sql = "SELECT tmp.* FROM ( SELECT v.*,mk.name as make_name,md.model_name,d.driver_name,d.id As driverautoid,d.driver_id AS driverid,GROUP_CONCAT(t.name) AS type
          FROM tbl_vehicle v
          INNER JOIN tbl_vehiclemodel md ON md.id=v.model_id
          INNER JOIN tbl_vehiclemake mk ON mk.id=v.make_id
          INNER JOIN tbl_driver d ON d.id=v.driver_id
          INNER JOIN tbl_map_vehicletype mv ON mv.vehicle_id=v.id
          INNER JOIN tbl_vehicletype t ON t.id=mv.type_id
          WHERE md.status LIKE '$fltstatus' $datefilter_qry GROUP BY v.id,d.id ) AS tmp $search_qry ORDER BY tmp.id DESC";

          
            $limit=" LIMIT ".$_REQUEST['start']." ,".$_REQUEST['length'];
            $totalRecords =$this->db->query($sql)->num_rows();
            $result=$this->db->query($sql.$limit)->result();
          
          if(!empty($result))
          {
              $i=0;
              $minus_length=0;
              if($_REQUEST['start'] > 0)
              {
                  $minus_length=$_REQUEST['start'];
              }
              $index=$totalRecords-$minus_length;
              
              foreach($result as $r)
              {         
                  
                  if($r->status==1){
                      
                       $sts = '<span class="text-success">Active</span>';
                  }else{
                      $sts = '<span class="text-danger">Inactive</span>';
                  }
               
               
                $response['list'][$i]['i']=$index;
                $response['list'][$i]['makemodel']=$r->make_name." ".$r->model_name;
                $response['list'][$i]['driver_name']=$r->driver_name;
                $response['list'][$i]['driver_id']=$r->driverid;
                $response['list'][$i]['type']=$r->type;
                
                $response['list'][$i]['number']=$r->number;
                
                $response['list'][$i]['entry_date']=date("d-m-Y h:i:s a", strtotime(trim($r->entry_date)));  
                $response['list'][$i]['status']=$sts;
                
                $action='<a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="View Details" onclick="view_detail('.$r->id.')" aria-hidden="true" style="color:#0e2b05ed;font-size:27px">
						 <i class="fa fa-eye" aria-hidden="true"></i></a>
                <a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="Update" onclick="editdata('.$r->id.')" aria-hidden="true" style="color:#007bff;font-size:27px">
				<i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
				<a href="javascript:void(0);" class="delete" aria-hidden="true" data-toggle="tooltip" onclick="deletedata('.$r->id.');" title="Delete" style="color:red;font-size:27px;margin-left:3px;" >
				<i class="fa fa-times-circle"></i>
				</a>';
				
				
				 $button = '<a href="' . base_url('Vehicle/driver_bookinghistory/' . $r->driverautoid) . '" class="delete" data-toggle="tooltip" title="Booking Details" 
                            aria-hidden="true" style="color:blue; font-size:27px" target="_blank">
                            <i class="fa fa-plus" aria-hidden="true"></i>
                          </a>';
								
								
                $response['list'][$i]['action']=$action.$button;
                
                  $i++;
                  $index--;
              }
          }
          else
          {
              $response['list']=[];
          }
          
          
          $json_data = array(
          "draw"            => intval( $_REQUEST['draw'] ),   
          "recordsTotal"    => intval($totalRecords ),  
          "recordsFiltered" => intval($totalRecords),
          "data"            => $response['list']   // total data array
          );
          
          echo json_encode($json_data);
      
   } 
   
   
   public function driver_bookinglist()
   {
       
          $draw=$_POST['draw'];       
          $fltstatus=$_POST['fltstatus'];
          $startdate='';
          $enddate='';
          
          $id=$_POST['id'];
          
          if($_POST['daterange'])
          {
              $ex=explode(" - ",$_POST['daterange']);
              if(!empty($ex))
              {
                  $fromdate=$ex[0];
                  $todate=$ex[1];
              
                  $date = str_replace('/', '-', $fromdate);
                  $startdate=date('Y-m-d', strtotime($date));
                  
          
                  $date1 = str_replace('/', '-', $todate);
                  $enddate=date('Y-m-d', strtotime($date1));
              }
          }
          
          
          $datefilter_qry="";
          if($startdate && $enddate)
          {
            $datefilter_qry=" AND STR_TO_DATE(v.entry_date,'%Y-%m-%d') BETWEEN '$startdate' AND '$enddate'";
          }          
        
          $search_qry="";      
        
          $extra_qry='';
          if($_POST['searchvalue'])
          {
              $searchValue=trim($_POST['searchvalue']);    
           
              
              $search_qry=" AND (v.book_id LIKE '%$searchValue%' OR md.user_id LIKE '%$searchValue%' 
              OR md.f_name LIKE '%$searchValue%'OR tv.number LIKE '%$searchValue%' 
              )"; 
           
          }
          
          
          $sql="SELECT v.*,dr.*,tv.number,dr.id as driver_autoid,md.user_id,md.f_name  
                FROM tbl_booking v
              INNER JOIN  tbl_user md ON md.id=v.user_id
              INNER JOIN tbl_vehicle tv ON tv.driver_id = v.driver_id
              LEFT JOIN tbl_driver dr ON v.driver_id = dr.id
              WHERE v.driver_id = '$id' $datefilter_qry $search_qry ";
           
          
            $limit=" LIMIT ".$_REQUEST['start']." ,".$_REQUEST['length'];
            $totalRecords =$this->db->query($sql)->num_rows();
            $result=$this->db->query($sql.$limit)->result();
            
          
          if(!empty($result))
          {
              $i=0;
              $minus_length=0;
              if($_REQUEST['start'] > 0)
              {
                  $minus_length=$_REQUEST['start'];
              }
              $index=$totalRecords-$minus_length;
              
              foreach($result as $r)
              {     
                 
                 
                 if($r->ride_status==0){
                      
                       $sts = '<span class="text-warning">Pending</span>';
                  }else if($r->ride_status==1){
                      $sts = '<span class="text-info">start</span>';
                  }else if($r->ride_status== 2){
                       $sts = '<span class="text-success">Completed</span>';
                  }else if($r->ride_status==3){
                       $sts = '<span class="text-danger">Cancel</span>';
                  }
               
                $response['list'][$i]['i']=$index;
                $response['list'][$i]['f_name']=$r->f_name;
                $response['list'][$i]['user_id']=$r->user_id;
                 $response['list'][$i]['book']=$r->book_id;
                $response['list'][$i]['dist']=$r->user_journey_distance;
                $response['list'][$i]['fare']=$r->total_fare;
                $response['list'][$i]['drop']=$r->drop_address;
                $response['list'][$i]['pick']=$r->pickup_address;
                $response['list'][$i]['entry_date']=date("d-m-Y h:i:s a", strtotime(trim($r->entry_date)));  
                $response['list'][$i]['status']=$sts;
                
                $collect_cash='';
                $collect_total_cash=0;
                if($r->ride_status==2)
                {
                    if($r->post_paymenttype == 'COD')
                    {   
                       $collect_total_cash=round($r->total_fare+$r->total_wait_charge,2);
                       $collect_cash='<a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="Collect cash" onclick="collectcash('.$r->id.')" aria-hidden="true" style="color:green;font-size:27px">
    						 <i class="fa fa-check-square" aria-hidden="true"></i></a>';     
                    }
                    else if($r->post_paymenttype == 'COD' && $r->post_paymenttype != 'COD')
                    {
                        $collect_total_cash=round($r->total_wait_charge,2);
                    }
                }
               
                $response['list'][$i]['collect_total_cash']=$collect_total_cash;
                
                $action='<a href="javascript:void(0);" class="delete" data-toggle="tooltip" title="View Details" 
                onclick="view_detail('.$r->id.')" aria-hidden="true" style="color:#0e2b05ed;font-size:27px">
						 <i class="fa fa-eye" aria-hidden="true"></i></a>'.$collect_cash;
								
						
                // $response['list'][$i]['action']=$action;
                
                  $i++;
                  $index--;
              }
          }
          else
          {
              $response['list']=[];
          }
          
          
          $json_data = array(
          "draw"            => intval( $_REQUEST['draw'] ),   
          "recordsTotal"    => intval($totalRecords ),  
          "recordsFiltered" => intval($totalRecords),
          "data"            => $response['list']   // total data array
          );
          
          echo json_encode($json_data);
      
   }
   
   public function delete_vehicle($id)
   {
       
       $result = $this->Login_model->select_column_where(['insurance_image'],
        'tbl_vehicle',['id' => $id]);
        
      
       if(!empty($result))
       {
    		if($result[0]['insurance_image'])
    		{
    			unlink($result[0]['insurance_image']);
    		}
    
    	
    		$this->db->where('id',$id);
    		$this->db->delete('tbl_vehicle');
    		
    		$this->db->where('vehicle_id',$id);
    		$this->db->delete('tbl_map_vehicletype');
    		$this->session->set_flashdata('success','Data successfully deleted');
       }
    		redirect('Vehicle/type');
   }
   
   
   public function edit()
   {
       header("Access-Control-Allow-Origin: *");
    	header("Content-Type: application/json; charset=UTF-8");
    	$status=0;
    	$message='Invalid Request';
    	
    	$id=$_POST['id'];
    	if($id)
    	{
    		 $result = $this->Login_model->select_column_where(['*'],
            'tbl_vehicle',['id' => $id]);
    		
    		if(!empty($result))
    		{
    		    $response['id']=$result[0]['id'];
    		    $response['driver_id']=$result[0]['driver_id'];
    		    $response['make_id']=$result[0]['make_id'];
    		    $response['model_id']=$result[0]['model_id'];
    		    $response['handicap']=$result[0]['handicap'];
    		    $response['childseat']=$result[0]['childseat'];
    		    $response['number']=$result[0]['number'];
    		    $response['color']=$result[0]['color'];
    		    $response['year']=$result[0]['year'];
    		    $response['status']=$result[0]['status'];
    		    $response['insurance_image']=$result[0]['insurance_image'];
    		    $response['insurance_status']=$result[0]['insurance_status'];
    		    
    		    
    		    $sub_result = $this->Login_model->select_column_where(['*'],
                'tbl_map_vehicletype',['vehicle_id' => $id]);
                
                if(!empty($sub_result))
    		    {
    		        $a=0;
    		        foreach($sub_result as $row)
    		        {
    		            $response['type'][$a]['type_id']=$row['type_id'];
    		            $a++;
    		        }
    		    }
    		    else
    		    {
    		        $response['type']=[];
    		    }
    		}
    		
    		
    		$status=1;
    		$message='success';
    			
    		
    	}
    	$response['status']=$status;
    	$response['message']=$message;
    	echo json_encode($response);
   }
   
   
   public function view()
   {
       $id=$_POST['id'];
    	if($id)
    	{
    	   $qry="SELECT v.*,mk.name as make_name,md.model_name,d.driver_name,d.driver_type,d.driver_id AS driverid,GROUP_CONCAT(t.name) AS type
           FROM tbl_vehicle v
           INNER JOIN tbl_vehiclemodel md ON md.id=v.model_id
           INNER JOIN tbl_vehiclemake mk ON mk.id=v.make_id
           INNER JOIN tbl_driver d ON d.id=v.driver_id
           INNER JOIN tbl_map_vehicletype mv ON mv.vehicle_id=v.id
           INNER JOIN tbl_vehicletype t ON t.id=mv.type_id WHERE v.id = $id";
           $row=$this->db->query($qry)->row_array();
           
           
           if(!empty($row))
           {
               ?>
            
               <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
				    <table id="tblsizewiserate" class="table table-striped table-bordered jambo_table bulk_action" style="width:100%;margin-bottom:20px;">
    					<tbody>
    						<tr>
    							<th style="width:15%">Driver Name</th>
    							<td style="width:30%"><?php echo $row['driver_type']."-".$row['driver_name']." (".$row['driverid'].")"?></td>
    							<th style="width:15%">Vehicle Make</th>
    							<td style="width:30%"><?php echo $row['make_name']?></td>
    						</tr>
    						<tr>
    							<th style="width:15%">Vehicle Model</th>
    							<td style="width:30%"><?php echo $row['model_name']?></td>
    							<th style="width:15%">Vehicle Type</th>
    							<td style="width:30%"><?php echo $row['type']?></td>
    						</tr>
    						<tr>
    							<th style="width:15%">Handicap Accessibility Available</th>
    							<td style="width:30%"><?php echo $row['handicap']?></td>
    							<th style="width:15%">Child Seat Accessibility Available </th>
    							<td style="width:30%"><?php echo $row['childseat']?></td>
    						</tr>
    						<tr>
    							<th style="width:15%">Vehicle Number</th>
    							<td style="width:30%"><?php echo $row['number']?></td>
    							<th style="width:15%">vehicle_color </th>
    							<td style="width:30%"><?php echo $row['color']?></td>
    						</tr>
    						<tr>
    							<th style="width:15%">Vehicle Year</th>
    							<td style="width:30%"><?php echo $row['year']?></td>
    							<th style="width:15%">Insurance </th>
    							<td style="width:30%"><a href="<?php echo base_url().$row['insurance_image'] ?>" target="_blank"><img src="<?php echo base_url().$row['insurance_image'] ?>" width="80px" height="80px"></a></td>
    						</tr>
    						<tr>
    							<th style="width:15%">Vehicle Status</th>
    							<td style="width:30%"><?php 
    							
    							if($row['status']==1)
    							{
    							    echo "Active";
    							}
    							else
    							{
    							    echo "inactive";
    							}
    							?></td>
    							<th style="width:15%">Insurance </th>
    							<td style="width:30%"><?php echo $row['insurance_status']?></td>
    						</tr>
    					</tbody>
					</table>
				</div>
               <?php
           }
           else
           {
               echo "Data not found";
           }
    	}
   }
}