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

class Driver extends CI_Controller {

    public function __construct(){
        
		parent::__construct();
		 $this->load->helper('email');
		 $this->load->helper('common');
		 $this->load->model('Apidriver_model');
		 $this->load->model('Login_model');
		 
		 $this->output
             ->set_content_type('application/json', 'utf-8')
             ->set_header('Access-Control-Allow-Origin: *')
             ->set_header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE')
             ->set_header('Access-Control-Allow-Headers: Content-Type, Authorization');
        $api_auth = $this->db->get('tbl_api_auth')->row_array();
        if(isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW'])){
			if(($_SERVER['PHP_AUTH_USER'] != $api_auth['username']) || ($_SERVER['PHP_AUTH_PW'] != $api_auth['password']))
			{
				outputJSON(400, 'error', 'Authentication failed');
				return;
			}
	    }else{
			outputJSON(400, 'error', 'Authentication Username and password not set');
			return;
		}
 
    }
    

	public function phone_login(){
	    
	    
	    
         header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
       
        $f_tokan = $data->f_tokan;
        $phone = $data->phone;
        
        if(isset($phone) )
        {
            if($phone)
            {
                $mobilewithcode = $phone;
                $exist= $this->Apidriver_model->is_registered1($mobilewithcode);
                $active= $this->Apidriver_model->activeuser($mobilewithcode);
                
                
                if(!$exist)
                {
                        $status='error';
                        $message='Record Not Found';
                        $statusCode=400;
                }
               
                else
                {
                    
                     if( $active->status == '0')
                      {
                        $status='error';
                        $message='Your account not active..! contact admin';
                        $statusCode=400;
                   }else{
                    
                        $record = $this->db->query("SELECT * FROM `tbl_driver` WHERE `mobile_no`='$mobilewithcode'");
                        $result = $record->row();
                        $user_id= $result->driver_id;
                        $otpinsertornot=$this->db->query("SELECT user_id FROM mobile_otp WHERE user_id='$user_id'")->row_array();

                        if($otpinsertornot==""){
                            
                         if($user_id=='Delivery100'){
                             
                                 $otpdata=array(
                                 'otp'=>'123654',
                                 'user_id'=>$user_id,
                               );
                               
                         }else{
                                $otp= random_int(100000, 999999);
                                 $otpdata=array(
                                                 'otp'=>$otp,
                                                 'user_id'=>$user_id,
                                );
                         }
                        
                    
                        $this->db->insert('mobile_otp',$otpdata);
                        $id=$this->db->insert_id();
                        
                        }
                              
                        $this->Apidriver_model->set_f_token_app($user_id, $f_tokan);
                       
                         $response['driver_id']=$result->driver_id;
                         $response['driver_name']=$result->driver_name;
                         $response['email']=$result->email;
                         $response['mobile_no']=$result->mobile_no;
                         $response['password']=$result->password;
                         $response['gender']=$result->gender;
                         $response['address']=$result->address .' '. $result->city .' '. $result->state.' '. $result->pin_code;
                         $response['latitude']=$result->latitude;
                         $response['logitude']=$result->logitude;
                         
                         if($result->driver_profile_pic !='' ){
                            $response['profile_image']=IMAGE_URL.$result->driver_profile_pic;
                         }else{
                            $response['profile_image']= IMAGE_URL.'assets/img/no-image-available.png'; 
                         }
                         
                        if($result->driving_license_image !='' ){
                           $response['driving_license_image']=IMAGE_URL.$result->driving_license_image;
                        }else{
                            $response['driving_license_image']= IMAGE_URL.'assets/img/no-image-available.png'; 
                        } 
                        if($result->driving_license_status =='0' ){
                           $response['driving_license_status']="Pending";
                        }
                        else  if($result->driving_license_status =='1' ){
                            $response['driving_license_status']="Approved";
                        }
                        else  if($result->driving_license_status =='2' ){
                            $response['driving_license_status']="Rejected";
                        }
                    
                         
                        $status='success';
                        $message='success';
                       // $detail='success';
                        $statusCode=200;
                    
                   }
                }
            }
            else
            {
                $status='error';
                $message='Please fill all required fields';
                $statusCode=400;
            }
        }
        else
        {
            $status='error';
            $message='Please fill all required fields';
            $statusCode=400;
        }
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
		echo json_encode($response);
    }
	
	
	
    private function send_request($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
	
	
	
	
	public function send_otp(){
	    
         header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);

        $otploginid = $data->user_id;
      
        if(isset($otploginid))
        {
            if($otploginid)
            {
                
                $user=$this->db->query("SELECT user_id FROM mobile_otp WHERE user_id='$otploginid'")->row_array();
                
                if(!empty($user))
                {
                         if($otploginid =='Driver100-Drv'){
                              $otp= 123654;
                                 $data=array(
                                 'otp'=>'123654',
                                 
                               );
                         }else{
                             $otp= random_int(100000, 999999);
                             
                            $data=array(
                                'otp'=>$otp,
                            );
                         }
        
                    $this->db->where('user_id',$otploginid);
                    $this->db->update('mobile_otp',$data);
                    $user_id=$user['user_id'];
                    
                     $delivernameuser=$this->db->query("SELECT * FROM tbl_driver WHERE driver_id='$user_id'")->row_array();
                         $phone = $delivernameuser['mobile_no'];
                         
                       
                        
                		
                           // $data = $this->Apidriver_model->getotp($payid); 
	   
                	
                		$user_name = $delivernameuser['driver_name'];
                		
                
                		$otp_now = $otp;
                		
                		
                		
                		 //  new version of the otp
                           $api_url = $this->Apidriver_model->get_api_url();
                         $api_url = str_replace(['mobile_number', 'user_name', 'otp_now'], [urlencode($phone), urlencode($user_name), $otp_now], $api_url);

                        //  
                
                	
                
                		$db_data = array(
                		'phone' => $phone,
                		'otp' => $otp_now ,
                		'user_id' => $user_name,
                		'added_by_web' => $_SERVER['HTTP_HOST'] ,
                		);
                
                		$insert_id = $this->Apidriver_model->Insert('all_otp',$db_data);
                
                		  $api_response = $this->send_request($api_url);   
                		  
                		  
                		  if(!empty($api_response)){
                    
                
                $response['otp']=$otp_now;
                    $response['user_id']=$otploginid;

                    $status='success';
                    $message='OTP has been sent successfully.';
                    $statusCode=200;
                }else{
                      $status='failed';
                $message='OTP not send';
                $statusCode=400;
                }
        
                    
                }
                else
                {
                    $status='error';
                    $message='Invalid Request.';
                    $statusCode=400;
                }
                
                
                
            }
            else
            {
                $status='error';
                $message='Please fill all required fields';
                $statusCode=400;
            }
        }
        else
        {
            $status='error';
            $message='Please fill all required fields';
            $statusCode=400;
        }
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    public function verify_otp(){
        
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		} 
		$input = inputJson();
		$rules = [
			['field' => 'user_id', 'label' => 'user id', 'rules' => 'required|trim'],
			['field' => 'otp', 'label' => 'Otp', 'rules' => 'required|trim|numeric']
		];
		checkValidation($input,$rules);

        $otp=$input['otp'];
        $otploginid=$input['user_id'];
     
		$verify=$this->Apidriver_model->verifyotp($otploginid);
		
		if(!empty($verify))
		{
			if($otp==$verify['otp'])
			{
				$response['id']=$verify['id'];
				$response['driver_name']=$verify['driver_name'];
				$response['driver_id']=$verify['driver_id'];
				$response['email']=$verify['email'];
				$response['mobile_no']=$verify['mobile_no'];
				$response['gender']=$verify['gender'];
				$response['pin_code']=$verify['pin_code'];
				$response['city']=$verify['city'];
				$response['state']=$verify['state'];
				outputJSON(200, 'success', 'Otp verified successfully.',$response);
			}
			else
			{
				outputJSON(400, 'error', 'Invalid OTP.');
			}
		}
		else
		{
			outputJSON(404, 'error', 'Record not found. Invalid user ID.');
		}
    }

 

	public function register(){
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}
		$input = inputJson(); 

		$rules = [
			['field' => 'driver_name', 'label' => 'Driver Name', 'rules' => 'required|trim|min_length[3]'],
			['field' => 'email', 'label' => 'Email', 'rules' => 'required|trim|valid_email'],
			['field' => 'mobile_no', 'label' => 'Mobile', 'rules' => 'required|trim|exact_length[10]|numeric'],
			['field' => 'address', 'label' => 'Address', 'rules' => 'required|trim'],
			['field' => 'city', 'label' => 'City', 'rules' => 'required|trim'],
			['field' => 'state', 'label' => 'State', 'rules' => 'required|trim'],
			['field' => 'gender', 'label' => 'gender', 'rules' => 'required|trim'],
			['field' => 'pin_code', 'label' => 'Pincode', 'rules' => 'required|trim|min_length[6]']
		];
		checkValidation($input,$rules);
       
        $name=$input['driver_name'];
        $phone=$input['mobile_no'];
        $email=$input['email'];
        $pin_code=$input['pin_code'];
        $address=$input['address'];
        $city=$input['city'];
        $state=$input['state'];
      	$gender=$input['gender'];
      
    
       
		$checkEmail = $this->db->get_where('tbl_driver', ['email' => $email])->num_rows();

		if ($checkEmail) {
			outputJSON(409, 'error', 'Email already registered.');
			return;
		}
		$checkMobile = $this->db->get_where('tbl_driver', ['mobile_no' => $phone])->num_rows();

		if ($checkMobile) {
			outputJSON(409, 'error', 'Mobile number already registered.');
			return;
		}
	   
		$data=array(
			'driver_name'=>$name,
			'email'=>$email,
			'pin_code'=>$pin_code,
			'address'=>$address,
			'city'=>$city,
			'state'=>$state,
			 'gender' => $gender,
			'mobile_no'=>$phone,
			'password'=>$phone,
			'status'=> 0,
		);

		$this->db->insert('tbl_driver',$data);
		$id=$this->db->insert_id(); 
		if($id){
			$names = str_replace(' ', '', $name);
			$driver_id=$names.$id."-Drv";
			$this->db->update('tbl_driver',['driver_id'=>$driver_id],['id'=>$id]);
			outputJSON(201, 'success', 'Register completed successfully.',['user_id'=>$driver_id]);
		}else{
			outputJSON(400, 'error', 'Register not completed. Please try again...');
		}            
    }
    
    
     public function profile_data(){
        
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);

        $user_id=$data->user_id;
       
       
        if(isset($user_id))
        {
            if($user_id )
            {
                
               
            $userdata=$this->db->query("SELECT * FROM  tbl_driver  where driver_id = '$user_id'")->row();
                
                if(!empty($userdata))
                {

                         $response['id']=$userdata->id;
                         $response['driver_id']=$userdata->driver_id;
                         $response['driver_name']=$userdata->driver_name;
                         $response['email']=$userdata->email;
                         $response['mobile_no']=$userdata->mobile_no;
                         $response['password']=$userdata->password;
                         $response['gender']=$userdata->gender;
                         $response['address']=$userdata->address .' '. $userdata->city .' '. $userdata->state.' '. $userdata->pin_code;
                         $response['latitude']=$userdata->latitude;
                         $response['logitude']=$userdata->logitude;
                         
                          if($userdata->expire_date != null|| $userdata->expire_date !='' ){
                              $response['expire_date']=$userdata->expire_date ;
                            }else{
                                $response['expire_date']= 'NA'; 
                            }
                         
                         if($userdata->driver_profile_pic !='' ){
                            $response['profile_image']=IMAGE_URL.$userdata->driver_profile_pic;
                         }else{
                            $response['profile_image']= IMAGE_URL.'assets/img/no-image-available.png'; 
                         }
                         
                        if($userdata->driving_license_image !='' ){
                           $response['driving_license_image']=IMAGE_URL.$userdata->driving_license_image;
                        }else{
                            $response['driving_license_image']= IMAGE_URL.'assets/img/no-image-available.png'; 
                        }
                        
                        if($userdata->driving_license_status =='0' ){
                           $response['driving_license_status']="Pending";
                        }
                        else  if($userdata->driving_license_status =='1' ){
                            $response['driving_license_status']="Approved";
                        }
                        else  if($userdata->driving_license_status =='2' ){
                            $response['driving_license_status']="Rejected";
                        }
                    
                   
                   
                  
                    $message='Profile data';
                    $status='success';
                    $statusCode=200;
                }else{
                
                $status='error';
                $message='Data Not Found';
                $statusCode=400;
               }
            }
            else
            {
                $status='error';
                $message='Please fill all required fields';
                $statusCode=400;
            }
        }
        else
        {
            $status='error';
            $message='Please fill all required fields';
            $statusCode=400;
        }
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
    }
    
    
    
     public function profiledata_update(){
        
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);

        $user_id=$data->user_id;
        $name=$data->driver_name;
        $email=$data->email;
        $phone=$data->mobile_no;
        $address=$data->address;
        $gender=$data->gender;
        $pin_code=$data->pin_code;
        $city=$data->city;
        $state=$data->state;
        $driving_license_status=$data->driving_license_status;
        $expired_date=$data->expired_date;
       
        if(isset($user_id) && isset($name)  && isset($email) && isset($phone) && isset($address) && isset($pin_code) && isset($gender) )
        {
            if($user_id  && $name  && $email  && $phone  && $address  && $pin_code && $gender)
            {
                 $data=array('driver_name'=>$name,
                             'email'=>$email,
                             'mobile_no'=>$phone,
                             'address'=>$address,
                             'pin_code'=>$pin_code,
                             'city'=>$city,
                             'state'=>$state,
                             'gender'=>$gender,
                             'expire_date' => $expired_date,
                             'driving_license_status' => $driving_license_status,
                             );
               
                 $this->Apidriver_model->update_data('tbl_driver','driver_id',$user_id,$data);
                  
                    $message='profile update';
                    $status='success';
                    $statusCode=200;
            }
            else
            {
                $status='error';
                $message='Please fill all required fields';
                $statusCode=400;
            }
        }
        else
        {
            $status='error';
            $message='Please fill all required fields';
            $statusCode=400;
        }
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
    } 
    
     public function image_update(){
            
         header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
 
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
       
        $user_id = $this->input->post('driver_id');
      
       
         if(!empty($user_id))
        {
            $time=time();
					
					$ext = pathinfo($_FILES['driver_file']['name'], PATHINFO_EXTENSION);
					$img_name='uploads/images/Licence/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['driver_file']);
					
						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;

						
						$this->my_upload->process('uploads/images/Licence/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}
					
					
						$ext = pathinfo($_FILES['driver_photo']['name'], PATHINFO_EXTENSION);
					$profile_img='uploads/images/DriverProfile/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['driver_photo']);
					
						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;

						
						$this->my_upload->process('uploads/images/DriverProfile/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}
                     
                    $data=array(
    					'driving_license_image' => $img_name,
    					'driver_profile_pic' => $profile_img,
                    );

              $this->Apidriver_model->update_data('tbl_driver','driver_id',$user_id,$data);
              $record = $this->db->query("SELECT id,driver_id,driver_profile_pic,driving_license_image FROM `tbl_driver` WHERE `driver_id`='$user_id'");
                    $result = $record->row_array(); 
 
                   
                     $response['record']['id']=$result['id'];
                     $response['record']['driver_id']=$result['driver_id'];
                    $response['record']['driving_license_image']=IMAGE_URL.$result['driving_license_image'];
                    $response['record']['driver_profile_pic']=IMAGE_URL.$result['driver_profile_pic'];
                    
                    $status='success';
                    $message='add success';
                    $statusCode=200;
        }
        else
        {
            $status='error';
            $message='Please fill all required fields';
            $statusCode=400;
        }
 
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
                              
              
        }
        
        
     public function upload_documents(){
            
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
 
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
       
        $user_id = $this->input->post('driver_id');
       
         if(!empty($user_id))
        {
            $time=time();
					
					$ext = pathinfo($_FILES['pancard']['name'], PATHINFO_EXTENSION);
					$pancardimg='uploads/images/Pan/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['pancard']);
					
					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;

						
						$this->my_upload->process('uploads/images/Pan/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}
					
					
					$ext = pathinfo($_FILES['driving_licence_']['name'], PATHINFO_EXTENSION);
					$drivinglicence__img='uploads/images/Licence/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['driving_licence_']);
					
					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;

						
						$this->my_upload->process('uploads/images/Licence/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}
					
					
					$ext = pathinfo($_FILES['vehicle_rc']['name'], PATHINFO_EXTENSION);
					$vehicle_rc_img='uploads/images/Rc/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['vehicle_rc']);
					
					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;

						
						$this->my_upload->process('uploads/images/Rc/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}
					
					
					$ext = pathinfo($_FILES['vehicle_endurance']['name'], PATHINFO_EXTENSION);
					$vehicle_endurance_img='uploads/images/Rc/img_'.$time.".".$ext;
					
					$this->my_upload->upload($_FILES['vehicle_endurance']);
					
					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;

						
						$this->my_upload->process('uploads/images/Insurance/');
						if ( $this->my_upload->processed == true ) 
						{
							$this->my_upload->clean();  
						} 
						
					}
                     
                    $data=array(
    					'driving_license_image' => $drivinglicence__img,
    					'driver_pancard' => $pancardimg,
    					'vehicle_rc' => $vehicle_rc_img,
    					'vehicle_endurance' => $vehicle_endurance_img,
                    );
                    
                   

              $this->Apidriver_model->update_data('tbl_driver','driver_id',$user_id,$data);
              $record = $this->db->query("SELECT id,driver_id,driver_pancard,vehicle_rc,vehicle_endurance,driving_license_image FROM `tbl_driver` 
              WHERE `driver_id`='$user_id'");
              $result = $record->row_array(); 
                   
                    $response['record']['id']=$result['id'];
                    $response['record']['driver_id']=$result['driver_id'];
                    $response['record']['driving_license_image']=IMAGE_URL.$result['driving_license_image'];
                    $response['record']['driver_pancard']=IMAGE_URL.$result['driver_pancard'];
                    $response['record']['vehicle_rc']=IMAGE_URL.$result['vehicle_rc'];
                    $response['record']['vehicle_endurance']=IMAGE_URL.$result['vehicle_endurance'];
                    
                    $status='success';
                    $message='add success';
                    $statusCode=200;
        }
        else
        {
            $status='error';
            $message='Please fill all required fields';
            $statusCode=400;
        }
 
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
                              
              
        }
    


    public function updateDriverLocation()
    {
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}
		$input = inputJson(); 
        $rules = [
			['field' => 'driver_id', 'label' => 'Driver ID', 'rules' => 'required|trim|numeric'],
			['field' => 'current_lat', 'label' => 'Current latitude', 'rules' => 'required|trim'],
			['field' => 'current_long', 'label' => 'Current longitude', 'rules' => 'required|trim']
		];
		checkValidation($input,$rules);
        $driver_id=$input['driver_id'];
    	$current_lat=$input['current_lat'];
    	$current_long=$input['current_long'];
        $data=[
			'driver_id'=>$driver_id,
			'curr_lat'=>$current_lat,
			'curr_long'=>$current_long,
			'entry_date'=>date('Y-m-d H:i:s'),
		 ];
    	$check=$this->db->get_where('tbl_driver_currentLocation', ['driver_id' => $driver_id])->num_rows();
		
		if($check==0){
			$res=$this->db->insert('tbl_driver_currentLocation',$data);
		}else{
			$res=$this->db->update('tbl_driver_currentLocation',$data,['driver_id'=>$driver_id]);
		}
    	
		if($res){
			outputJSON(200, 'success', 'Location updated successfully'); 
		}else{
			outputJSON(500, 'error', 'Failed to update location. Please try again.');
		}
    }
    
    public function AcceptUserRequest()
    {
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}

		$input = inputJson();
		$rules = [
			['field' => 'request_id', 'label' => 'request id', 'rules' => 'required|trim'],
			['field' => 'gen_request_id', 'label' => 'gen request ID', 'rules' => 'required|trim'],
			['field' => 'driver_id', 'label' => 'Driver ID', 'rules' => 'required|trim']
		];
		checkValidation($input,$rules);
        
        $request_id=$input['request_id'];
    	$req_id=$input['gen_request_id'];
    	$driver_id=$input['driver_id'];
    	
		$qry="SELECT * FROM tbl_userwise_cabrequest 
		WHERE status=1 AND is_latest_request=1 AND req_id='$req_id'";
		$result=$this->db->query($qry)->row_array();
		
		if(!empty($result))
		{
			
			$data=array('status'=>3);
			$this->db->where('req_id',$req_id);
			$this->db->update('tbl_userwise_cabrequest',$data);
			
			outputJSON(400, 'error', 'Request already accepted by other driver.');
		}
		else
		{
			$datetime=date('Y-m-d H:i:s');
			
			
			$this->db->where('id',$driver_id);
			$this->db->update('tbl_driver',array('accepted_request_time'=>$datetime));
			
			$data=array('status'=>1);
			$this->db->where('id',$request_id);
			$this->db->update('tbl_userwise_cabrequest',$data);
			
		    outputJSON(200, 'success', 'Request has been accepted successfully.'); 
		}
    	
    }
    
    public function RejectUserRequest()
    {
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}

		$input = inputJson();
		$rules = [
			['field' => 'request_id', 'label' => 'request id', 'rules' => 'required|trim'],
			['field' => 'reason', 'label' => 'reason', 'rules' => 'required|trim']
		];
		checkValidation($input,$rules);
        
        $request_id=$input['request_id'];
    	$reason=$input['reason'];
    	
		$data=array('status'=>2,'reject_reason'=>$reason);
		
		$this->db->where('req_id',$request_id);
		$this->db->update('tbl_userwise_cabrequest',$data);
	   
		outputJSON(200, 'success', 'Request has been rejected successfully.');
    }
    
    
    // new cab request 
    
    
    public function CabRequestList_change()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
    
        $response = [
            'status' => 'error',
            'message' => 'Invalid Request',
            'statusCode' => 400,
            'list' => []
        ];
    
        // Get and decode JSON input
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
    
        // Check if driver_id is provided and valid
        if (isset($data->driver_id) && !empty($data->driver_id) && empty($data->booking_type)) 
        {
            $driver_id = $data->driver_id;
    
            // Prepare SQL query to get cab requests for the driver
            $qry = "SELECT r.*, DATE_FORMAT(r.entry_date, '%d/%m/%Y %h:%i %p') as requestdate, vt.name as vehicle_type, 
                          u.f_name as user_name, u.mobile_no as user_mobileno, u.email_id as user_email 
                    FROM tbl_userwise_cabrequest r 
                    INNER JOIN tbl_user u ON u.id = r.user_id
                    INNER JOIN tbl_vehicletype vt ON vt.id = r.type_id
                    WHERE r.driver_id = ? 
                    ORDER BY r.id DESC";
                    
            $result = $this->db->query($qry, [$driver_id])->result_array();
    
            if (!empty($result)) {
                foreach ($result as $i => $row) {
                    $status = 'Pending';
                    if ($row['status'] == 1 && $row['driver_id'] == $driver_id) {
                        $status = 'Accepted';
                    } elseif ($row['status'] == 1 && $row['driver_id'] != $driver_id) {
                        $status = 'Accepted by other';
                    } elseif ($row['status'] == 2 && $row['driver_id'] == $driver_id) {
                        $status = 'Rejected';
                    }
    
                    // Calculate total fare
                    $total_fare = (int) round($row['user_journey_distance'] * $row['per_km_fare']);
    
                    // Add cab request details to the response
                    $response['list'][] = [
                        'id' => $row['id'],
                        'req_id' => $row['req_id'],
                        'booking_type' => $row['booking_type'],
                        'pickup_address' => $row['pickup_address'],
                        'pickup_lat' => $row['pickup_lat'],
                        'pickup_long' => $row['pickup_long'],
                        'drop_address' => $row['drop_address'],
                        'drop_lat' => $row['drop_lat'],
                        'drop_long' => $row['drop_long'],
                        'user_journey_distance' => $row['user_journey_distance'],
                        'per_km_fare' => $row['per_km_fare'],
                        'user_name' => $row['user_name'],
                        'user_mobileno' => $row['user_mobileno'],
                        'user_email' => $row['user_email'],
                        'total_fare' => $total_fare,
                        'vehicle_type' => $row['vehicle_type'],
                        'request_date' => $row['requestdate'],
                        'status' => $status
                    ];
                }
    
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            } else {
                // No requests found for the given driver
                $response['status'] = 'success';
                $response['message'] = 'No requests found for this driver';
                $response['statusCode'] = 200;
            }
        } 
        if (isset($data->driver_id) && ($data->booking_type=='recuring')) 
        {
            $driver_id = $data->driver_id;
    
            // Prepare SQL query to get cab requests for the driver
            $qry = "SELECT r.*, DATE_FORMAT(r.entry_date, '%d/%m/%Y %h:%i %p') as requestdate, vt.name as vehicle_type, 
                           u.f_name as user_name, u.mobile_no as user_mobileno, u.email_id as user_email 
                    FROM tbl_userwise_cabrequest r 
                    INNER JOIN tbl_user u ON u.id = r.user_id
                    INNER JOIN tbl_vehicletype vt ON vt.id = r.type_id
                    WHERE r.driver_id = ? AND r.booking_type='recuring'
                    ORDER BY r.id DESC";
                    
            $result = $this->db->query($qry, [$driver_id])->result_array();
    
            if (!empty($result)) {
                foreach ($result as $i => $row) {
                    $status = 'Pending';
                    if ($row['status'] == 1 && $row['driver_id'] == $driver_id) {
                        $status = 'Accepted';
                    } elseif ($row['status'] == 1 && $row['driver_id'] != $driver_id) {
                        $status = 'Accepted by other';
                    } elseif ($row['status'] == 2 && $row['driver_id'] == $driver_id) {
                        $status = 'Rejected';
                    }
    
                    // Calculate total fare
                    $total_fare = (int) round($row['user_journey_distance'] * $row['per_km_fare']);
    
                    // Add cab request details to the response
                    $response['list'][] = [
                        'id' => $row['id'],
                        'req_id' => $row['req_id'],
                        'booking_type' => $row['booking_type'],
                        'pickup_address' => $row['pickup_address'],
                        'pickup_lat' => $row['pickup_lat'],
                        'pickup_long' => $row['pickup_long'],
                        'drop_address' => $row['drop_address'],
                        'drop_lat' => $row['drop_lat'],
                        'drop_long' => $row['drop_long'],
                        'user_journey_distance' => $row['user_journey_distance'],
                        'per_km_fare' => $row['per_km_fare'],
                        'user_name' => $row['user_name'],
                        'user_mobileno' => $row['user_mobileno'],
                        'user_email' => $row['user_email'],
                        'total_fare' => $total_fare,
                        'vehicle_type' => $row['vehicle_type'],
                        'request_date' => $row['requestdate'],
                        'status' => $status
                    ];
                }
    
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            } else {
                // No requests found for the given driver
                $response['status'] = 'success';
                $response['message'] = 'No requests found for this driver';
                $response['statusCode'] = 200;
            }
        }
        if (isset($data->driver_id) && ($data->booking_type=='rental')) 
        {
            $driver_id = $data->driver_id;
    
            // Prepare SQL query to get cab requests for the driver
            $qry = "SELECT r.*, DATE_FORMAT(r.entry_date, '%d/%m/%Y %h:%i %p') as requestdate, vt.name as vehicle_type, 
                           u.f_name as user_name, u.mobile_no as user_mobileno, u.email_id as user_email 
                    FROM tbl_userwise_cabrequest r 
                    INNER JOIN tbl_user u ON u.id = r.user_id
                    INNER JOIN tbl_vehicletype vt ON vt.id = r.type_id
                    WHERE r.driver_id = ? AND r.booking_type='rental'
                    ORDER BY r.id DESC";
                    
            $result = $this->db->query($qry, [$driver_id])->result_array();
    
            if (!empty($result)) {
                foreach ($result as $i => $row) {
                    $status = 'Pending';
                    if ($row['status'] == 1 && $row['driver_id'] == $driver_id) {
                        $status = 'Accepted';
                    } elseif ($row['status'] == 1 && $row['driver_id'] != $driver_id) {
                        $status = 'Accepted by other';
                    } elseif ($row['status'] == 2 && $row['driver_id'] == $driver_id) {
                        $status = 'Rejected';
                    }
    
                    // Calculate total fare
                    $total_fare = (int) round($row['user_journey_distance'] * $row['per_km_fare']);
    
                    // Add cab request details to the response
                    $response['list'][] = [
                        'id' => $row['id'],
                        'req_id' => $row['req_id'],
                        'booking_type' => $row['booking_type'],
                        'pickup_address' => $row['pickup_address'],
                        'pickup_lat' => $row['pickup_lat'],
                        'pickup_long' => $row['pickup_long'],
                        'drop_address' => $row['drop_address'],
                        'drop_lat' => $row['drop_lat'],
                        'drop_long' => $row['drop_long'],
                        'user_journey_distance' => $row['user_journey_distance'],
                        'per_km_fare' => $row['per_km_fare'],
                        'user_name' => $row['user_name'],
                        'user_mobileno' => $row['user_mobileno'],
                        'user_email' => $row['user_email'],
                        'total_fare' => $total_fare,
                        'vehicle_type' => $row['vehicle_type'],
                        'request_date' => $row['requestdate'],
                        'status' => $status
                    ];
                }
    
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            } else {
                // No requests found for the given driver
                $response['status'] = 'success';
                $response['message'] = 'No requests found for this driver';
                $response['statusCode'] = 200;
            }
        }
        else
        {
            // driver_id is missing or empty
            $response['status'] = 'error';
            $response['message'] = 'No Data Found';
            $response['statusCode'] = 400;
        }
    
        // Output JSON response
        echo json_encode($response);
}


    public function CabRequestList()
    {
   
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
    
        $response = [
            'status' => 'error',
            'message' => 'Invalid Request',
            'statusCode' => 400,
            'list' => []
        ];

            // Read and sanitize input
            $json = $this->security->xss_clean(file_get_contents('php://input'));
            $data = json_decode($json);

            if (isset($data->driver_id)) {
            $driver_id = $data->driver_id;
            $booking_type = isset($data->booking_type) ? $data->booking_type : null;

        
            $query = "SELECT r.*, DATE_FORMAT(r.entry_date, '%d/%m/%Y %h:%i %p') as requestdate, 
                             vt.name as vehicle_type, u.f_name as user_name, 
                             u.mobile_no as user_mobileno, u.email_id as user_email
                      FROM tbl_userwise_cabrequest r 
                      INNER JOIN tbl_user u ON u.id = r.user_id
                      INNER JOIN tbl_vehicletype vt ON vt.id = r.type_id
                      WHERE r.is_latest_request = 1 AND r.driver_id = '$driver_id'";

            if ($booking_type) {
                $query .= " AND r.booking_type = '$booking_type'";
            }

            $query .= " ORDER BY r.id DESC";
            $result = $this->db->query($query)->result_array();

            if (!empty($result)) {
                foreach ($result as $row) {
                    $dbstatus = 'Pending';
                    if ($row['status'] == 1 && $row['driver_id'] == $driver_id) {
                        $dbstatus = 'Accepted';
                    } elseif ($row['status'] == 1 && $row['driver_id'] != $driver_id) {
                        $dbstatus = 'Accepted by other';
                    } elseif ($row['status'] == 2 && $row['driver_id'] == $driver_id) {
                        $dbstatus = 'Rejected';
                    }
    
                    // Calculate total fare
                    $total_fare = (int) round($row['user_journey_distance'] * $row['per_km_fare']);
    
                    // Add cab request details to the response
                    $response['list'][] = [
                        'id' => $row['id'],
                        'req_id' => $row['req_id'],
                        'booking_type' => $row['booking_type'],
                        'pickup_address' => $row['pickup_address'],
                        'pickup_lat' => $row['pickup_lat'],
                        'pickup_long' => $row['pickup_long'],
                        'drop_address' => $row['drop_address'],
                        'drop_lat' => $row['drop_lat'],
                        'drop_long' => $row['drop_long'],
                        'user_journey_distance' => $row['user_journey_distance'],
                        'per_km_fare' => $row['per_km_fare'],
                        'user_name' => $row['user_name'],
                        'user_mobileno' => $row['user_mobileno'],
                        'user_email' => $row['user_email'],
                        'total_fare' => $total_fare,
                        'vehicle_type' => $row['vehicle_type'],
                        'request_date' => $row['requestdate'],
                        'selecteddate'=>$row['selecteddate'],
                        'selectedtime'=>$row['selectedtime'],
                        'reject_reason'=>$row['reject_reason'],
                        'status' => $dbstatus
                    ];
                }
    
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            } else {
                $response['status'] = 'success';
                $response['message'] = 'No data found';
                $response['statusCode'] = 200;
            }
        }

        // Return response as JSON
        echo json_encode($response);
}

    
    
    
    // 
    
    public function CabRequestList_old()
    {
        header("Access-Control-Allow-Origin: *");
    	header("Content-Type: application/json; charset=UTF-8");
    	
    	$status='error';
        $message='Invalid Request';
        $statusCode=400;
    		
    	$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        
        $driver_id=$data->driver_id;
    	if($driver_id)
    	{
    	    $qry="SELECT r.*,DATE_FORMAT(r.entry_date,'%d/%m/%Y %h:%i %p') as requestdate,vt.name,u.f_name,u.mobile_no,
    	    u.email_id FROM tbl_userwise_cabrequest r 
    	    INNER JOIN tbl_user u ON u.id=r.user_id
    	    INNER JOIN tbl_vehicletype vt ON vt.id=r.type_id
    	    WHERE r.is_latest_request=1 AND r.driver_id='$driver_id' ORDER BY r.id DESC";
    	    $result=$this->db->query($qry)->result_array();
    	    
    	    
    	    
    	    if(!empty($result))
    	    {
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['list'][$i]['id']=$row['id'];
    	            $response['list'][$i]['req_id']=$row['req_id'];
    	            $response['list'][$i]['pickup_address']=$row['pickup_address'];
    	            $response['list'][$i]['pickup_lat']=$row['pickup_lat'];
    	            $response['list'][$i]['pickup_long']=$row['pickup_long'];
    	            $response['list'][$i]['drop_address']=$row['drop_address'];
    	            $response['list'][$i]['drop_lat']=$row['drop_lat'];
    	            $response['list'][$i]['drop_long']=$row['drop_long'];
    	            $response['list'][$i]['user_journey_distance']=$row['user_journey_distance'];
    	            $response['list'][$i]['per_km_fare']=$row['per_km_fare'];
    	            $response['list'][$i]['user_name']=$row['f_name'];
    	            $response['list'][$i]['user_mobileno']=$row['mobile_no'];
    	            $response['list'][$i]['user_email']=$row['email_id'];
    	            $response['list'][$i]['total_fare']=(int)round($row['user_journey_distance']*$row['per_km_fare']);
    	            $response['list'][$i]['vehicle_type']=$row['name'];
    	            $response['list'][$i]['request_date']=$row['requestdate'];
    	            
    	            if($row['status']==0)
    	            {
    	                $status="Pending";
    	            }
    	            else if($row['status']==1 && $row['driver_id']==$driver_id)
    	            {
    	                $status="Accepted";
    	            }
    	            else if($row['status']==1 && $row['driver_id'] != $driver_id)
    	            {
    	                $status="Accepted by other";
    	            }
    	            else if($row['status']==2 && $row['driver_id']==$driver_id)
    	            {
    	                $status="Rejected";
    	            }
    	           
    	            $response['list'][$i]['status']=$status;
    	            $i++;
    	        }
    	        
    	       $status='success';
                $message='success';
                $statusCode=200;     
        	    
    	    }
    	    else
    	    {
    	        $response['list']=[]; 
        	    $status='success';
                $message='Data not found';
                $statusCode=200; 
    	    }
    	    
    	      
    	    
    	}
    	if (isset($data->driver_id) && ($data->booking_type=='recuring')) 
        {
            $driver_id = $data->driver_id;
    
            // Prepare SQL query to get cab requests for the driver
            $qry = "SELECT r.*, DATE_FORMAT(r.entry_date, '%d/%m/%Y %h:%i %p') as requestdate, vt.name as vehicle_type, 
                           u.f_name as user_name, u.mobile_no as user_mobileno, u.email_id as user_email 
                    FROM tbl_userwise_cabrequest r 
                    INNER JOIN tbl_user u ON u.id = r.user_id
                    INNER JOIN tbl_vehicletype vt ON vt.id = r.type_id
                    WHERE r.driver_id = ? AND r.booking_type='recuring'
                    ORDER BY r.id DESC";
                    
            $result = $this->db->query($qry, [$driver_id])->result_array();
    
            if (!empty($result)) {
                foreach ($result as $i => $row) {
                    $status = 'Pending';
                    if ($row['status'] == 1 && $row['driver_id'] == $driver_id) {
                        $status = 'Accepted';
                    } elseif ($row['status'] == 1 && $row['driver_id'] != $driver_id) {
                        $status = 'Accepted by other';
                    } elseif ($row['status'] == 2 && $row['driver_id'] == $driver_id) {
                        $status = 'Rejected';
                    }
    
                    // Calculate total fare
                    $total_fare = (int) round($row['user_journey_distance'] * $row['per_km_fare']);
    
                    // Add cab request details to the response
                    $response['list'][] = [
                        'id' => $row['id'],
                        'req_id' => $row['req_id'],
                        'booking_type' => $row['booking_type'],
                        'pickup_address' => $row['pickup_address'],
                        'pickup_lat' => $row['pickup_lat'],
                        'pickup_long' => $row['pickup_long'],
                        'drop_address' => $row['drop_address'],
                        'drop_lat' => $row['drop_lat'],
                        'drop_long' => $row['drop_long'],
                        'user_journey_distance' => $row['user_journey_distance'],
                        'per_km_fare' => $row['per_km_fare'],
                        'user_name' => $row['user_name'],
                        'user_mobileno' => $row['user_mobileno'],
                        'user_email' => $row['user_email'],
                        'total_fare' => $total_fare,
                        'vehicle_type' => $row['vehicle_type'],
                        'request_date' => $row['requestdate'],
                        'status' => $status
                    ];
                }
    
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            } else {
                // No requests found for the given driver
                $response['status'] = 'success';
                $response['message'] = 'No requests found for this driver';
                $response['statusCode'] = 200;
            }
        }
        if (isset($data->driver_id) && ($data->booking_type=='rental')) 
        {
            $driver_id = $data->driver_id;
    
            // Prepare SQL query to get cab requests for the driver
            $qry = "SELECT r.*, DATE_FORMAT(r.entry_date, '%d/%m/%Y %h:%i %p') as requestdate, vt.name as vehicle_type, 
                           u.f_name as user_name, u.mobile_no as user_mobileno, u.email_id as user_email 
                    FROM tbl_userwise_cabrequest r 
                    INNER JOIN tbl_user u ON u.id = r.user_id
                    INNER JOIN tbl_vehicletype vt ON vt.id = r.type_id
                    WHERE r.driver_id = ? AND r.booking_type='rental'
                    ORDER BY r.id DESC";
                    
            $result = $this->db->query($qry, [$driver_id])->result_array();
    
            if (!empty($result)) {
                foreach ($result as $i => $row) {
                    $status = 'Pending';
                    if ($row['status'] == 1 && $row['driver_id'] == $driver_id) {
                        $status = 'Accepted';
                    } elseif ($row['status'] == 1 && $row['driver_id'] != $driver_id) {
                        $status = 'Accepted by other';
                    } elseif ($row['status'] == 2 && $row['driver_id'] == $driver_id) {
                        $status = 'Rejected';
                    }
    
                    // Calculate total fare
                    $total_fare = (int) round($row['user_journey_distance'] * $row['per_km_fare']);
    
                    // Add cab request details to the response
                    $response['list'][] = [
                        'id' => $row['id'],
                        'req_id' => $row['req_id'],
                        'booking_type' => $row['booking_type'],
                        'pickup_address' => $row['pickup_address'],
                        'pickup_lat' => $row['pickup_lat'],
                        'pickup_long' => $row['pickup_long'],
                        'drop_address' => $row['drop_address'],
                        'drop_lat' => $row['drop_lat'],
                        'drop_long' => $row['drop_long'],
                        'user_journey_distance' => $row['user_journey_distance'],
                        'per_km_fare' => $row['per_km_fare'],
                        'user_name' => $row['user_name'],
                        'user_mobileno' => $row['user_mobileno'],
                        'user_email' => $row['user_email'],
                        'total_fare' => $total_fare,
                        'vehicle_type' => $row['vehicle_type'],
                        'request_date' => $row['requestdate'],
                        'status' => $status
                    ];
                }
    
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            } else {
                // No requests found for the given driver
                $response['status'] = 'success';
                $response['message'] = 'No requests found for this driver';
                $response['statusCode'] = 200;
            }
        }
    	
    	else
    	{
    	    $status='error';
            $message='Something went wrong';
            $statusCode=400;        
           
    	}
    	$response['status']=$status;
    	$response['message']=$message;
    	$response['statusCode']=$statusCode;
    	echo json_encode($response);
    }
    
    // public function Startride()
    // {
    //     header("Access-Control-Allow-Origin: *");
    // 	header("Content-Type: application/json; charset=UTF-8");
    	
    // 	$status='error';
    //     $message='Invalid Request';
    //     $statusCode=400;
    		
    // 	$json = $this->security->xss_clean(file_get_contents('php://input'));
    //     $data = json_decode($json);
        
    //     $booking_id=$data->booking_id;
    	
    // 	if($booking_id)
    // 	{
    	    
    // 	    $qry="SELECT id,is_cancle,cancle_reason FROM tbl_booking WHERE book_id='$booking_id'";
    // 	    $row=$this->db->query($qry)->row_array();
    // 	    if(!empty($row))
    // 	    {
    	        
    // 	        if($row['is_cancle']==0)
    // 	        {
    // 	            $data=array('ride_status'=>1);
    //         	    $this->db->where('book_id',$booking_id);
    //         	    $this->db->update('tbl_booking',$data);
            	    
    //         	    //booking ride history
            	    
    //         	    $data_sub=array(
    //         	        'booking_id'=>$row['id'],
    //         	        'status'=>1,
    //         	        'entry_date'=>date('Y-m-d H:i:s'),
    //         	        );
            	        
    //         	    $this->db->insert('tbl_booking_ridehistory',$data_sub);     
    //         	    $status='success';
    //                 $message='Ride has been start successfully';
    //                 $statusCode=200;      
    // 	        }
    // 	        else
    // 	        {
    // 	            $status='error';
    //                 $message='This cab canclled by users becuase of '.$row['cancle_reason'];
    //                 $statusCode=400;   
    // 	        }
    // 	    }
    // 	    else
    // 	    {
    // 	        $status='error';
    //             $message='Something went wrong';
    //             $statusCode=400;   
    // 	    }
    // 	}
    // 	else
    // 	{
    // 	    $status='error';
    //         $message='Something went wrong';
    //         $statusCode=400;        
           
    // 	}
    // 	$response['status']=$status;
    // 	$response['message']=$message;
    // 	$response['statusCode']=$statusCode;
    // 	echo json_encode($response);
    // }
    
    public function Completeride()
    {
        if (strtoupper($this->input->method()) !== 'GET') {
			outputJSON(405, 'error', 'Invalid request method. Please use GET.');
			return;
		}

		$input = inputJson();
		$booking_id = $input['booking_id'] ?? null;

		if (empty($booking_id)) {
			outputJSON(400, 'error', 'Booking ID (booking_id) is required.');
			return;
		} 
    	
    	    
		$qry="SELECT b.*,
		f.wait_charge,f.wait_time_limit
		FROM tbl_booking b
		INNER JOIN tbl_fare f ON f.vehicle_type=b.type_id
		WHERE b.book_id='$booking_id'";
		$row=$this->db->query($qry)->row_array();
		if(!empty($row))
		{
			
			if($row['is_cancle']==0)
			{
				if($row['payment_status']==0)   
				{
					 $total_payble=round(($row['per_km_fare']*$row['user_journey_distance'])+$row['conv_charge'],2); 
					 $total_payble=round($total_payble+$row['total_wait_charge']);
						
					$message='Please collect Rs.'.$total_payble.' payment from the user';
					outputJSON(400, 'error', $message);
				}
				else if($row['payment_status']==1 && $row['post_payment_status']==0 && $row['total_wait_charge']>0)
				{
					 $total_payble=0; 
					 $total_payble=round($total_payble+$row['total_wait_charge']);
						
					$message='Please collect Rs.'.$total_payble.' waiting charge from the user';
					outputJSON(400, 'error', $message);
				}
				else
				{
					//booking ride history
					 $data_update=array(
					   'ride_status'=>2,
					  );
					  
					$this->db->where('book_id',$booking_id);  
					$this->db->update('tbl_booking',$data_update);
					
					$data_sub=array(
						'booking_id'=>$row['id'],
						'status'=>2,
						'entry_date'=>date('Y-m-d H:i:s'),
					);
						
					$this->db->insert('tbl_booking_ridehistory',$data_sub);    
					
					outputJSON(200, 'success', 'Ride has been completed successfully');
				}
					 
			}
			else
			{
				$message='This cab canclled by users becuase of '.$row['cancle_reason'];
				outputJSON(400, 'error', $message);
			}
		}
		else
		{
			outputJSON(400, 'error', 'Record not found. Invalid booking ID');
			return;
		}
    }
    
    public function ride_history()
    {
        if (strtoupper($this->input->method()) !== 'GET') {
			outputJSON(405, 'error', 'Invalid request method. Please use GET.');
			return;
		}

		$input = inputJson();
	
		$rules = [
			['field' => 'driver_id', 'label' => 'driver id', 'rules' => 'required|trim|numeric']
		];
		checkValidation($input,$rules);
        $driver_id = $input['driver_id'];
		$booking_type = $input['booking_type'] ?? ''; 
        $pn = $input['page'] ?? 1; 
        // $driver_id=$data->driver_id;
         // $booking_type=$data->booking_type;
        // $pageno= $data->pageno;
        
        // if($driver_id)
        // {
             $limit = 10;    
             $start_from = ($pn-1) * $limit;
                
            $qry="SELECT b.*,DATE_FORMAT(b.entry_date,'%d/%m/%Y %H:%i %p') AS entrydate,vt.name as vehicle_name,
            tbc.selecteddate,tbc.selectedtime,tu.f_name,tu.mobile_no,tu.email_id
            FROM tbl_booking b
            INNER JOIN tbl_vehicletype vt ON vt.id=b.type_id 
            INNER JOIN tbl_userwise_cabrequest tbc ON tbc.driver_id=b.driver_id 
            INNER JOIN tbl_user tu ON tu.id=b.user_id 
            
            WHERE b.driver_id='$driver_id' AND b.booking_type='$booking_type' GROUP BY b.book_id";
            
            
            $limit_qry=" ORDER BY b.id DESC LIMIT $start_from,$limit";
            $result=$this->db->query($qry.$limit_qry)->result_array();
            
            
            $total=$this->db->query($qry)->num_rows();
          
            $number_of_page = ceil ($total / $limit); 
            
            if(!empty($result))
            {
                $i=0;
                foreach($result as $row)
                {
                    $response['list'][$i]['id']=$row['id'];
                    $response['list'][$i]['book_id']=$row['book_id'];
                    $response['list'][$i]['booking_type']=$row['booking_type'];
                    $response['list'][$i]['pickup_address']=$row['pickup_address'];
                    $response['list'][$i]['drop_address']=$row['drop_address'];
                    $response['list'][$i]['vehicle']=$row['vehicle_name'];
                    $response['list'][$i]['user_journey_distance']=$row['user_journey_distance'];
                    $response['list'][$i]['total_fare']=$row['total_fare'];
                    $response['list'][$i]['total_wait_charge']=$row['total_wait_charge'];
                    $response['list'][$i]['grand_total']=$row['grand_total'];
                    $response['list'][$i]['selectedtime']=$row['selectedtime'];
                    $response['list'][$i]['selecteddate']=$row['selecteddate'];
                    $response['list'][$i]['paymenttype']=$row['paymenttype'];
                    $response['list'][$i]['user_name']=$row['f_name'];
                    $response['list'][$i]['user_mobile']=$row['mobile_no'];
                    $response['list'][$i]['user_email']=$row['email_id'];
                    
                    
                    
                    if($row['ride_status']==0) 
                    {
                        $ride_status="Pending";
                    }
                    else if($row['ride_status']==1) 
                    {
                        $ride_status="Start";
                    }
                    else if($row['ride_status']==2) 
                    {
                        $ride_status="Completed";
                    } 
                    else if($row['is_cancle']==1) 
                    {
                        $ride_status="Cancelled";
                    }
                    $response['list'][$i]['ride_status']=$ride_status;
                    $response['list'][$i]['payment_status']=($row['payment_status']==0) ? 'Pending' : 'Paid';
                    $response['list'][$i]['is_cancle']=$row['is_cancle'];
                    $response['list'][$i]['cancle_date']=$row['cancle_date'];
                    $response['list'][$i]['cancle_reason']=$row['cancle_reason'];
                    $response['list'][$i]['entry_date']=$row['entrydate'];
                    $i++;
                }
                
                if($number_of_page > 1)
                {
                    if($number_of_page == $pn)
                    {
                        $response['nextpage']=0;
                    }
                    else
                    {
                        $response['nextpage']=$pn+1;
                    }
                }
                else
                {
                    $response['nextpage']=0;
                }
                
                $message='Data found';
                $status='success';
                $statusCode=200;
				$response['status']=$status;
				$response['statusCode']=$statusCode;
				$response['message']=$message;
				echo json_encode($response);
            }
            else
            {
                 $response['list']=[];
				 $message='Data Not found';
                 $status='success';
                 $statusCode=200;
				 $response['status']=$status;
				$response['statusCode']=$statusCode;
				$response['message']=$message;
				echo json_encode($response);
            }
            
            
        // }
        // else
        // {
            // $status='error';
            // $message='Please fill all required fields';
            // $statusCode=400;
        // }
        
        
    }
    
    
    public function arrivPickuplocation()
    {
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		} 
		$input = inputJson(); 
        $rules = [
			['field' => 'booking_id', 'label' => 'Booking ID', 'rules' => 'required|trim']
		];
		checkValidation($input,$rules);
        
        $booking_id=$input['booking_id'];
        // $driver_id=$data->driver_id;
        
			$row=$this->db->select('u.mobile_no, u.f_name, u.f_token_app')->from('tbl_booking b')->join('tbl_user u', 'u.id = b.user_id')->where('b.book_id', $booking_id)->get()->row_array();

            if(!empty($row))
            {
				$query=$this->db->select('*')->from('sms_template')->where('status', '0')->where('type', 'send_otp')->get();

				if ($query->num_rows() == 0) {
					outputJSON(404, 'error', 'Message template not found! Please contact admin.');
					return;
				}
				$exist = $query->result();
				$d_msg = $exist[0]->body ;

                $user_name = trim($row['f_name']);
                
                $user_name = str_replace(' ', '', $user_name);
                
                $user_name = htmlspecialchars($user_name);

                $otp_now = $otp = sprintf("%06d", mt_rand(0, 999999));

                $msg = str_replace("mobile_number", $row['mobile_no'] ,$d_msg) ;

                $msg = str_replace("user_name", $user_name ,$msg) ;

                $msg = str_replace("otp_now", $otp_now ,$msg) ;

                $update_array=array(
                    'otp'=>$otp_now,
                    'is_arrive'=>1
                    );
                $this->db->Update('tbl_booking',$update_array,array('book_id' => $booking_id));
                if (isset($msg) && is_string($msg)) {
                    $api_url = trim($msg);
                 }
                 
                //send_text_msg($msg);
                 
                $res=send_text_msg_new($api_url);
                if($row['f_token_app'])
                {
                    $body="Driver has been arrived at your pickup location";
    	            $title="Driver arrived";
    	            sendNotificationapp($row['f_token_app'],$body,$title);
                }
				outputJSON(200, 'success', 'OTP has been sent successfully.');
            }
            else
            {
                outputJSON(400, 'error', 'Something went wrong.'); 
            }
    }
    
    public function Verifybookingotp()
    {
        if (strtoupper($this->input->method()) !== 'POST') {
			outputJSON(405, 'error', 'Invalid request method. Please use POST.');
			return;
		}
		$input = inputJson(); 
        $rules = [
			['field' => 'booking_id', 'label' => 'Booking ID', 'rules' => 'required|trim'],
			['field' => 'otp', 'label' => 'OTP', 'rules' => 'required|trim|numeric']
		];
		checkValidation($input,$rules);
       
		$otp=$input['otp'];
		$booking_id=$input['booking_id'];
		
		$query = $this->db->select('otp, otp_verify_status')->from('tbl_booking')->where('book_id', $booking_id)->get();

		if($query->num_rows()==0){
			outputJSON(404, 'error', 'Booking records not found, Invalid Booking ID.');
			return; 
		}
		$verify=$query->row_array();
		if($otp==$verify['otp'])
		{
			if($verify['otp_verify_status']==0)
			{
				 $data=array(
					'otp_verify_status'=>1
				);
				$this->db->Where('book_id',$booking_id);
				$this->db->update('tbl_booking',$data);
				outputJSON(200, 'success', 'OTP has been verified successfully');
			}
			else
			{
				outputJSON(400, 'error', 'OTP already verified');
			}
		}
		else
		{
			outputJSON(400, 'error', 'Invalid OTP.');
			return;
		}
		     
    }
    
    public function trip_history_details()
    {
        if (strtoupper($this->input->method()) !== 'GET') {
			outputJSON(405, 'error', 'Invalid request method. Please use GET.');
			return;
		}

		$input = inputJson();
		$booking_id = $input['booking_id'] ?? null;

		if (empty($booking_id)) {
			outputJSON(400, 'error', 'Booking ID (booking_id) is required.');
			return;
		}
        
		$qry="SELECT b.*,DATE_FORMAT(b.entry_date,'%d/%m/%Y %H:%i %p') AS entrydate,
		vt.name as vehicle_name,vt.image as vehicle_image,
		u.f_name as user_name,u.mobile_no as user_mobno,v.number
		FROM tbl_booking b 
		INNER JOIN tbl_vehicletype vt ON vt.id=b.type_id 
		INNER JOIN tbl_vehicle v ON v.driver_id=b.driver_id
		INNER JOIN  tbl_user u ON u.id = b.user_id  WHERE b.book_id='$booking_id'";
		
		$row=$this->db->query($qry)->row_array();
	   
		if(!empty($row))
		{
			
			$response['id']=$row['id'];
			$response['book_id']=$row['book_id'];
			$response['booking_type']=$row['booking_type'];
			$response['pickup_address']=$row['pickup_address'];
			$response['pickup_lat']=$row['pickup_lat'];
			$response['pickup_long']=$row['pickup_long'];
			$response['drop_address']=$row['drop_address'];
			$response['drop_lat']=$row['drop_lat'];
			$response['drop_long']=$row['drop_long'];
			$response['vehicle']=$row['vehicle_name'];
			$response['vehicle_image']=base_url().$row['vehicle_image'];
			$response['user_journey_distance']=$row['user_journey_distance'];
			$response['total_fare']=$row['total_fare'];
			$response['total_wait_charge']=$row['total_wait_charge'];
			$response['grand_total']=$row['grand_total'];
			$response['user_name']=$row['user_name'];
		   
			$response['user_mobile_no']=$row['user_mobno'];
			
		   
			if($row['ride_status']==0) 
			{
				$ride_status="Pending";
			}
			else if($row['ride_status']==1) 
			{
				$ride_status="Start";
			}
			else if($row['ride_status']==2) 
			{
				$ride_status="Completed";
			}
			else if($row['is_cancle']==1) 
			{
				$ride_status="Cancelled";
			}
			$response['ride_status']=$ride_status;
			$response['payment_status']=($row['payment_status']==0) ? 'Pending' : 'Paid';
			$response['is_cancle']=$row['is_cancle'];
			$response['paymenttype']=$row['paymenttype'];
			$response['cancle_date']=$row['cancle_date'];
			$response['cancle_reason']=$row['cancle_reason'];
			$response['entry_date']=$row['entrydate'];
			
			$response['is_arrive']=$row['is_arrive'];
			
			$response['conv_charge']=$row['conv_charge'];
			$response['post_paymenttype']=$row['post_paymenttype'];
			$response['final_grandtotal']=$row['final_grandtotal'];
			$response['vehical_number']=$row['number'];
			$message='Data found';
			$status='success';
			$statusCode=200;
		}
		else
		{
			
			$message='Data Not found';
			 $status='success';
			 $statusCode=400;
		}
        
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
		echo json_encode($response);
    } 
    
    
    public function driver_online_offline()
    {
        if (strtoupper($this->input->method()) !== 'GET') {
			outputJSON(405, 'error', 'Invalid request method. Please use GET.');
			return;
		}

		$input = inputJson();
		$driver_id = $input['driver_id'] ?? null;

		if (empty($driver_id)) {
			outputJSON(400, 'error', 'driver ID (driver_id) is required.');
			return;
		}
        
		$sql="SELECT is_online FROM tbl_driver WHERE id='$driver_id'";
		$row = $this->db->query($sql)->row_array(); 
		
		
		if(!empty($row))
		{
			if($row['is_online']==1)
			{
				$data=array(
					'is_online'=>0
				);
			}
			else
			{
				 $data=array(
					'is_online'=>1
				);
			}
			
			$this->db->Where('id',$driver_id);
			$this->db->update('tbl_driver',$data);
			
			outputJSON(200, 'success', 'Status has been updated successfully');
		}
		else
		{
			outputJSON(400, 'error', 'Record not found. Invalid Driver ID.');
		}
            
    }
    
    public function completeridewith_cod()
    {
        header("Access-Control-Allow-Origin: *");
    	header("Content-Type: application/json; charset=UTF-8");
    	
    	$status='error';
        $message='Invalid Request';
        $statusCode=400;
    		
    	$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        
        $booking_id=$data->booking_id;
        $total_waitingtime=isset($data->total_waitingtime)?$data->total_waitingtime:'';
       
    	
    	if($booking_id)
    	{
    	    $qry="SELECT * FROM tbl_booking WHERE book_id='$booking_id'";
            $row=$this->db->query($qry)->row_array();
            
            if(!empty($row))
            {
    	        
    	        if($row['payment_status']==0)
    	        {
    	            $total_payble=round(($row['per_km_fare']*$row['user_journey_distance'])+$row['conv_charge'],2); 
    	            $total_payble=round($total_payble+$row['total_wait_charge']);
    	        }
                else
                {
                    $total_payble=round($row['total_wait_charge']);
                   
                }
                
    	        
                $data_update=array(
                   'ride_status'=>2,
                   'final_grandtotal'=>$total_payble,
                   'payment_status'=>1,
                   'post_paymenttype'=>'COD',
                   'post_payment_status'=>1,
                   'total_waiting_time'=>$total_waitingtime,
                  );
                  
                $this->db->where('book_id',$booking_id);  
                $this->db->update('tbl_booking',$data_update);
                
                 $data_sub=array(
        	        'booking_id'=>$row['id'],
        	        'status'=>2,
        	        'entry_date'=>date('Y-m-d H:i:s'),
        	    );
        	        
        	    $this->db->insert('tbl_booking_ridehistory',$data_sub);   
                
                
                //collect cod
              
                if($total_payble > 0)
                {
                     $data_cod=array(
            	        'book_id'=>$row['book_id'],
            	        'driver_id'=>$row['driver_id'],
            	        'cod_amt'=>$total_payble,
            	        'status'=>0,
            	        'created_at'=>date('Y-m-d H:i:s'),
            	    );
            	        
            	    $this->db->insert('tbl_cod_collection',$data_cod);
                }
                
              
                $message='Ride has been collect successfully.';
                $status='success';
                $statusCode=200;
    	    }
    	    else
    	    {
    	        $status='error';
                $message='This booking not valid';
                $statusCode=400;  
    	    }
    	}
    	else
    	{
    	    $status='error';
            $message='Booking id required';
            $statusCode=400;    
    	}
    	
        $response['status']=$status;
    	$response['message']=$message;
    	$response['statusCode']=$statusCode;
    	echo json_encode($response);
    }
    
    
    public function addvehicle()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        
        $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_rc=$_POST['vehicle_rc'];
        
        $vehicle_color=$_POST['vehicle_color'];
        $vehicle_year=$_POST['vehicle_year'];
        $insurance_status=$_POST['insurance_status'];
		$insurance_img=$_FILES['insurance']['name'];
		
		$vehicle_rc=$_POST['vehicle_rc'];
		$vehicle_rc_image=$_FILES['vehicle_rc_image']['name'];
        $pollution_certificate_image=$_FILES['pollution_certificate']['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))
				{
					$status='error';
                    $message='Data already exist';
                    $statusCode=400;
				}
				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();  
    						} 
    						
    					}

					}
					
					
					$vehrc_image='';
					if($vehicle_rc_image)
					{
    					$ext = pathinfo($_FILES['vehicle_rc_image']['name'], PATHINFO_EXTENSION);
    					$vehrc_image='uploads/images/Rc/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['vehicle_rc_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               = 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/Rc/');
    						if ( $this->my_upload->processed == true ) 
    						{
    							$this->my_upload->clean();  
    						} 
    						
    					}

					}
					
					$pollcert_image='';
					if($pollution_certificate_image)
					{
    					$ext = pathinfo($_FILES['pollution_certificate']['name'], PATHINFO_EXTENSION);
    					$pollcert_image='uploads/images/Pollution/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['pollution_certificate']);
    					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/Pollution/');
    						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,
					"vehicle_rc"=>$vehicle_rc,
					"vehicle_rc_image"=>$vehrc_image,
					"pollution_certificate"=>$pollcert_image,
					"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);
                        }
                    }
                    $response['id']=$vehicle_id;
                    $status='success';
                    $message='Data Saved successfully';
                    $statusCode=200;
				}
			}
			else
			{
			    
			        $status='error';
                    $message='Please fill in all required field';
                    $statusCode=200;
			}
			
			
			$response['status']=$status;
            $response['statusCode']=$statusCode;
    		$response['message']=$message;
    		echo json_encode($response);
			
			
		}
		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))
				{
				    
				    $status='error';
                    $message='Data already exist';
                    $statusCode=400;
				}
				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();  
    						} 
    						
    					}
					}
					
					$vehrc_image='';
					if($vehicle_rc_image)
					{
    					$ext = pathinfo($_FILES['vehicle_rc_image']['name'], PATHINFO_EXTENSION);
    					$vehrc_image='uploads/images/Rc/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['vehicle_rc_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               = 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/Rc/');
    						if ( $this->my_upload->processed == true ) 
    						{
    							$this->my_upload->clean();  
    						} 
    						
    					}

					}
					
					$pollcert_image='';
					if($pollution_certificate_image)
					{
    					$ext = pathinfo($_FILES['pollution_certificate_image']['name'], PATHINFO_EXTENSION);
    					$pollcert_image='uploads/images/Pollution/img_'.$time.".".$ext;
    					
    					$this->my_upload->upload($_FILES['pollution_certificate_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               = 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/Pollution/');
    						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,
					"vehicle_rc"=>$vehicle_rc,
					"vehicle_rc_image"=>$vehrc_image,
					"pollution_certificate_image"=>$pollcert_image,
				    );
				    
				  
					$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);
                        }
                    }
                    
                    
                    $status='success';
                    $message='Data updated successfully';
                    $statusCode=200;
				}
			}
			else
			{
			    
                $status='error';
                $message='Please fill in all required field';
                $statusCode=200;
				
			
			}
			$response['status']=$status;
            $response['statusCode']=$statusCode;
    		$response['message']=$message;
    		echo json_encode($response);
			
		}
        

    }
    
    public function delete_vehicle()
    {
       
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $id=$data->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');
    		
    		
            $status='succcess';
            $message='Data Deleted Successfully';
            $statusCode=200;
    	
    		
    		
            
       }
       
            $response['status']=$status;
            $response['statusCode']=$statusCode;
    		$response['message']=$message;
            echo json_encode($response);	
   }
    
    
    public function vehiclelist()
    {  
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $fltstatus='%';
        
            $startdate='';
            $enddate='';
          
            if($data->daterange)
            {
              $ex=explode(" - ",$data->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($data->searchvalue)
            {
            $searchValue=trim($data->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.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 ) AS tmp $search_qry ORDER BY tmp.id DESC ";
        
            
           
         
            $limit = 10;  
            $pageno = isset($data->pageno) ? $data->pageno : 1;  
            $offset = ($pageno - 1) * $limit;
            
            $totalRecords = $this->db->query($sql)->num_rows();
            $number_of_page = ceil($totalRecords / $limit);
          
            $sqlWithLimit = $sql . " LIMIT $limit OFFSET $offset";
              
            $result=$this->db->query($sqlWithLimit)->result(); 
  
          if(!empty($result))
            {
                $i=0;
                foreach($result as $r)
                { 
                   
                       if($r->status==1){
                          
                           $sts = 'Active';
                      }else{
                          $sts = 'Inactive';
                      }
                
                    $response['list'][$i]['id']=$r->id;
                    $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;
                  
                    $i++;
                }

                if($number_of_page > 1)
                {
                    if($number_of_page == $pageno)
                    {
                        $response['nextpage']=0;
                    }
                    else
                    {
                        $response['nextpage']=$pageno+1;
                    }
                }
                else
                {
                    $response['nextpage']=0;
                }
                $status='success';
                $statusCode=200;
                $message='Data found';
            }
            else
            {
                $status='error';
                $statusCode=400;
                $message='Data not found';
            }
    
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
      
        

    }
    
    public function type_add()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $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))
				{
				    
				    $response['status']='error';
                    $response['statusCode']=204;
                    $response['message']='Data already exist';
				}
				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);
					
					$response['status']='success';
                    $response['statusCode']=200;
                    $response['message']='Data inserted successfully';
					
				}
			}
			else
			{
			    
		        $response['status']='error';
                $response['statusCode']=200;
                $response['message']='Please fill in all required field';
			}
			
			$response['status']=$status;
            $response['statusCode']=$statusCode;
            $response['message']=$message;
            echo json_encode($response);
			
		}
		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))
				{
				    
				    $response['status']='error';
                    $response['statusCode']=204;
                    $response['message']='Data already exist';
				}
				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);
					
					$response['status']='success';
                    $response['statusCode']=200;
                    $response['message']='Data updated successfully';
				}
			}
			else
			{
			    
                $response['status']='error';
                $response['statusCode']=200;
                $response['message']='Please fill in all required field';
			
			}
			
			$response['status']=$status;
            $response['statusCode']=$statusCode;
            $response['message']=$message;
            echo json_encode($response);
			
			
		}
		
		
    }
    
     public function get_typelist()
     {  
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $fltstatus='%';
        
            $startdate='';
            $enddate='';
          
            if($data->daterange)
            {
              $ex=explode(" - ",$data->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($data->searchvalue)
            {
            $searchValue=trim($data->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 = 10;  
            $pageno = isset($data->pageno) ? $data->pageno : 1;  
            $offset = ($pageno - 1) * $limit;
            
            $totalRecords = $this->db->query($sql)->num_rows();
            $number_of_page = ceil($totalRecords / $limit);
          
            $sqlWithLimit = $sql . " LIMIT $limit OFFSET $offset";
              
            $result=$this->db->query($sqlWithLimit)->result(); 
  
            if(!empty($result))
            {
                $i=0;
                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']=$r->id;
                    $response['list'][$i]['name']=$r->name;
                    $response['list'][$i]['description']=$r->description;
                    $response['list'][$i]['image']=base_url().$r->image;
                    $response['list'][$i]['active_image']=base_url().$r->active_image;
                    $response['list'][$i]['entry_date']=date("d-m-Y h:i:s a", strtotime(trim($r->entry_date)));  
                    $response['list'][$i]['status']=$sts;
                  
                    $i++;
                }

                if($number_of_page > 1)
                {
                    if($number_of_page == $pageno)
                    {
                        $response['nextpage']=0;
                    }
                    else
                    {
                        $response['nextpage']=$pageno+1;
                    }
                }
                else
                {
                    $response['nextpage']=0;
                }
                $status='success';
                $statusCode=200;
                $message='Data found';
            }
            else
            {
                $status='error';
                $statusCode=400;
                $message='Data not found';
            }
    
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
      
        

    }
    
    
    public function delete_type()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $id=$data->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');
    		
    		$status='succcess';
            $message='Data Deleted Successfully';
            $statusCode=200;
            
       }
       
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
        echo json_encode($response);
    		
    		
   }
   
   public function make_add()
   {
       
       header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
       
        $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))
				{
				    
				    $status='error';
                    $message='Data already exist';
                    $statusCode=204;
                    
				}
				else
				{
					
					$data = array(
					"name" => $name,
					"status"=>$status,
				    "entry_date"=>$edate,
					"added_by_web"=>$_SERVER['HTTP_HOST'],
					);

					$this->Login_model->insert('tbl_vehiclemake',$data);
					
					 $status='success';
                    $message='Data inserted successfully';
                    $statusCode=200;
				}
			}
			else
			{
			        $status='error';
                    $message='Please fill in all required field';
                    $statusCode=200;
				
			}
			
			$response['status']=$status;
            $response['statusCode']=$statusCode;
    		$response['message']=$message;
            echo json_encode($response);
			
			
		}
		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))
				{
				    
				    $status='error';
                    $message='Data already exist';
                    $statusCode=204;
				}
				else
				{
				    
					$data = array(
					"name" => $name,
				    "status"=>$status,
					);
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehiclemake',$data);
					
					$status='success';
                    $message='Data updated successfully';
                    $statusCode=200;

					
				}
			}
			else
			{
			    
                $status='error';
                $message='Please fill in all required field';
                $statusCode=204;
			    
				
			}
			
			$response['status']=$status;
            $response['statusCode']=$statusCode;
    		$response['message']=$message;
            echo json_encode($response);
			
			
		}
   }
   
    public function get_makelist()
     {  
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $fltstatus='%';
        
            $startdate='';
            $enddate='';
          
            if($data->daterange)
            {
              $ex=explode(" - ",$data->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($data->searchvalue)
            {
            $searchValue=trim($data->searchvalue);      
            
                $search_qry=" AND (name = '$searchValue')";  
            
            }
            
            
            $sql = "SELECT * FROM tbl_vehiclemake WHERE status LIKE '$fltstatus' $datefilter_qry $search_qry ORDER BY id DESC";
        
            
           
         
            $limit = 10;  
            $pageno = isset($data->pageno) ? $data->pageno : 1;  
            $offset = ($pageno - 1) * $limit;
            
            $totalRecords = $this->db->query($sql)->num_rows();
            $number_of_page = ceil($totalRecords / $limit);
          
            $sqlWithLimit = $sql . " LIMIT $limit OFFSET $offset";
              
            $result=$this->db->query($sqlWithLimit)->result(); 
  
            if(!empty($result))
            {
                $i=0;
                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']=$r->id;
                $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;
                  
                    $i++;
                }

                if($number_of_page > 1)
                {
                    if($number_of_page == $pageno)
                    {
                        $response['nextpage']=0;
                    }
                    else
                    {
                        $response['nextpage']=$pageno+1;
                    }
                }
                else
                {
                    $response['nextpage']=0;
                }
                $status='success';
                $statusCode=200;
                $message='Data found';
            }
            else
            {
                $status='error';
                $statusCode=400;
                $message='Data not found';
            }
    
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
      
        

    }
    
    public function delete_make()
    {
       
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $id=$data->id;
       
      
       	$this->db->where('id',$id);
		$this->db->delete('tbl_vehiclemake');
		
		$status='succcess';
        $message='Data Deleted Successfully';
        $statusCode=200;
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
        echo json_encode($response);
        
    }
    
    
    public function model_add()
    {
       
       header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
       
        $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))
				{
				    
                    $status='error';
                    $message='Data already exist';
                    $statusCode=204;
					
				}
				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);
					
					$status='succcess';
                    $message='Data inserted Successfully';
                    $statusCode=200;
				}
			}
			else
			{
			    
			        $status='error';
                    $message='Please fill in all required field';
                    $statusCode=204;
			}
			
			    $response['status']=$status;
                $response['statusCode']=$statusCode;
        		$response['message']=$message;
                echo json_encode($response);
			
			
		}
		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))
				{
				    
				    $status='error';
                    $message='Data already exist';
                    $statusCode=204;
				}
				else
				{
				    
					$data = array(
					"make_id" => $make_id,
					"model_name" => $name,
					"status"=>$status,
					);
				    
				  
					$this->db->Where('id',$id);
					$this->db->update('tbl_vehiclemodel',$data);
					
					$status='success';
                    $message='Data updated successfully';
                    $statusCode=204;
				}
			}
			else
			{
			    
                $status='error';
                $message='Please fill in all required field';
                $statusCode=204;
			
			}
			
            $response['status']=$status;
            $response['statusCode']=$statusCode;
            $response['message']=$message;
            echo json_encode($response);

			
		}
		
		
    }
    
    
    public function get_modellist()
     {  
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $fltstatus='%';
        
            $startdate='';
            $enddate='';
          
            if($data->daterange)
            {
              $ex=explode(" - ",$data->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($data->searchvalue)
            {
            $searchValue=trim($data->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 = 10;  
            $pageno = isset($data->pageno) ? $data->pageno : 1;  
            $offset = ($pageno - 1) * $limit;
            
            $totalRecords = $this->db->query($sql)->num_rows();
            $number_of_page = ceil($totalRecords / $limit);
          
            $sqlWithLimit = $sql . " LIMIT $limit OFFSET $offset";
              
            $result=$this->db->query($sqlWithLimit)->result(); 
  
            if(!empty($result))
            {
                $i=0;
                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']=$r->id;
                    $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;
                  
                    $i++;
                }

                if($number_of_page > 1)
                {
                    if($number_of_page == $pageno)
                    {
                        $response['nextpage']=0;
                    }
                    else
                    {
                        $response['nextpage']=$pageno+1;
                    }
                }
                else
                {
                    $response['nextpage']=0;
                }
                $status='success';
                $statusCode=200;
                $message='Data found';
            }
            else
            {
                $status='error';
                $statusCode=400;
                $message='Data not found';
            }
    
        $response['status']=$status;
        $response['statusCode']=$statusCode;
        $response['message']=$message;
        echo json_encode($response);
      
        

    }
    
    public function delete_model()
   {
       
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $id=$data->id;
      
       	$this->db->where('id',$id);
		$this->db->delete('tbl_vehiclemodel');
		
		$status='succcess';
        $message='Data Deleted Successfully';
        $statusCode=200;
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
        echo json_encode($response);
   }
   
   
   public function get_makewise_model()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $make_id=$data->make_id;
        
        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)
                {
                    $response['list'][$i]['vehiclemodel_id']=$row['id'];
                    $response['list'][$i]['model_name']=$row['model_name'];
                }
                
                
                 $response['status']='success';
            	$response['message']='Data found';
            	$response['statusCode']=200;
                
                
            }
            
            $response['status']='error';
            $response['message']='Data not found';
            $response['statusCode']=200;
            
        }
        
        $response['status']=$status;
    	$response['message']=$message;
    	$response['statusCode']=$statusCode;
    	echo json_encode($response);
        
        
        
    }
    
    
    public function getvehicle()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
            $sql="SELECT * FROM  tbl_vehicle_types ORDER BY id ";
            
            $result=$this->db->query($sql)->result_array();
            
            if(!empty($result))
            {
                $i=0;
                foreach($result as $row)
                {
                    $response['list'][$i]['vehicle_id']=$row['id'];
                    $response['list'][$i]['type_name']=$row['type_name'];
                    
                    $i++;
                }
                
                
                $status='success';
            	$message='Data found';
            	$statusCode=200;
                
                
            }
            
            $response['status']=$status;
            $response['message']=$message;
            $response['statusCode']=$statusCode;
            echo json_encode($response);
            
        }
    
    
    public function getvehicle_companies()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $vehicle_id=$data->vehicle_id;
        
        if($vehicle_id)
        {
            $sql="SELECT id,company_name FROM  tbl_companies WHERE vehicle_type_id=$vehicle_id ORDER BY id ";
            
            $result=$this->db->query($sql)->result_array();
            
            if(!empty($result))
            {
                $i=0;
                foreach($result as $row)
                {
                    $response['list'][$i]['companies_id']=$row['id'];
                    $response['list'][$i]['company_name']=$row['company_name'];
                    
                    $i++;
                }
                
                
                $status='success';
            	$message='Data found';
            	$statusCode=200;
                
                
            }
            
        }
            
        $response['status']=$status;
        $response['message']=$message;
        $response['statusCode']=$statusCode;
        echo json_encode($response);
            
        }
    
    
    public function getvehicle_modals()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $companies_id=$data->companies_id;
        
        if($companies_id)
        {
            $sql="SELECT id,model_name FROM  tbl_modals WHERE company_id=$companies_id ORDER BY id ";
            
            $result=$this->db->query($sql)->result_array();
            
            if(!empty($result))
            {
                $i=0;
                foreach($result as $row)
                {
                    $response['list'][$i]['id']=$row['id'];
                    $response['list'][$i]['model_name']=$row['model_name'];
                    
                    $i++;
                }
                
                
                $status='success';
            	$message='Data found';
            	$statusCode=200;
                
                
            }
            
        }
            
        $response['status']=$status;
        $response['message']=$message;
        $response['statusCode']=$statusCode;
        echo json_encode($response);
            
        }
        
        
    //states and cities api
    
    
    public function get_state()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        
            $sql="SELECT name,id FROM  states  ORDER BY id ";
            
            $result=$this->db->query($sql)->result_array();
            
            if(!empty($result))
            {
                $i=0;
                foreach($result as $row)
                {
                    $response['list'][$i]['state_id']=$row['id'];
                    $response['list'][$i]['state_name']=$row['name'];
                    
                    $i++;
                }
                
                
                $status='success';
            	$message='Data found';
            	$statusCode=200;
                
                
            }
            
        
            
        $response['status']=$status;
        $response['message']=$message;
        $response['statusCode']=$statusCode;
        echo json_encode($response);
            
        }
        
    public function get_city()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        $json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        $state_id=$data->state_id;
        if($state_id )
        {
            $sql="SELECT name FROM  cities WHERE state_id=$state_id ORDER BY id ";
            
            $result=$this->db->query($sql)->result_array();
            
            if(!empty($result))
            {
                $i=0;
                foreach($result as $row)
                {
                    // $response['list'][$i]['id']=$row['id'];
                    $response['list'][$i]['city_name']=$row['name'];
                    
                    $i++;
                }
                
                
                $status='success';
            	$message='Data found';
            	$statusCode=200;
                
                
            }
            
        }
            
        $response['status']=$status;
        $response['message']=$message;
        $response['statusCode']=$statusCode;
        echo json_encode($response);
            
        }
    
   
    
        
        
        
        
    
   
 
    
    
    
    
    
    
    
    
    
}
?>