<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class User extends CI_Controller {

    public function __construct(){
        
		parent::__construct();
		
		$this->load->helper('email'); 
		$this->load->helper('common'); 
		
		$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->query("SELECT * FROM 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 getvehicle()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
			
		$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        
		$pickup_lat=$data->pickup_lat;
		$pickup_long=$data->pickup_long;
	    $drop_lat=$data->drop_lat;
		$drop_long=$data->drop_long;
		
		
		if($pickup_lat && $pickup_long)
		{
		    $get_hours=date('H');
		    
		    $qry="SELECT tmp.*,vt.id,vt.image,vt.name,vt.description,vt.type,vt.seat,
		    prmo.promo_code_discount,prmo.status as promo_status,
		    f.per_km FROM (SELECT driver_id,
    	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
            cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
     	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
     	    INNER JOIN tbl_vehicletype vt ON vt.id=dmt.type_id
     	    INNER JOIN promocode prmo ON prmo.vehicletype_id=vt.id
     	    INNER JOIN tbl_fare f ON f.vehicle_type=vt.id WHERE vt.status=1 AND d.is_online=1 AND d.status=1
     	    
     	    AND tmp.distance <= '".DEFAULT_NEARBY_DRIVER_AREA."' GROUP BY vt.id ORDER BY tmp.distance,f.per_km ASC";
    	    
    	    $result=$this->db->query($qry)->result_array();
    	    
    	   // echo $qry;
    	   // die;
    	    
    	   // echo "<pre>";
    	   // print_r($result);
    	   // die;
    	    
    	    if(!empty($result))
    	    {
    	        $total_distance=$this->distance($pickup_lat,$pickup_long,$drop_lat,$drop_long,'K');
    	        
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['vehicle'][$i]['id']=$row['id'];
    	            $response['vehicle'][$i]['name']=$row['name'];
    	            $response['vehicle'][$i]['image']=base_url().$row['image'];
    	            $response['vehicle'][$i]['description']=$row['description'];
    	             $response['vehicle'][$i]['type']=$row['type'];
    	              $response['vehicle'][$i]['seat']=$row['seat'];
    	             $response['vehicle'][$i]['promocode_status']=$row['promo_status'];
    	             $response['vehicle'][$i]['distance']=$total_distance;
    	            
    	            if($total_distance > 0) 
    	            {
    	                    $fare = round($total_distance*$row['per_km'],2);
    	                    
    	                    if($row['promo_status']=='APPLIED')
    	                    {
                                $discountfare = round($fare * ($row['promo_code_discount'] / 100), 2);
                                $netfare=round($fare-$discountfare,2);
                                
                                $response['vehicle'][$i]['fare']=round($total_distance*$row['per_km'],2);
        	                    $response['vehicle'][$i]['discount']=$row['promo_code_discount'].'%';
        	                    $response['vehicle'][$i]['net_fare']=$netfare;
                                
    	                    }
    	                    else
    	                    {
    	                       $response['vehicle'][$i]['fare']=round($total_distance*$row['per_km'],2);
        	                    $response['vehicle'][$i]['discount']=$row['promo_code_discount'].'%';
        	                    $response['vehicle'][$i]['net_fare']=$fare;
    	                    }
                            
    	                    
    	            }
    	            else
    	            {
    	                $response['vehicle'][$i]['fare']=$row['per_km'];
    	            }
    	            
    	           
    	            
    	            $i++;
    	        }
    	        
    	        
    	        $status='success';
                $message='Data found';
                $statusCode=200;   
    	        
    	    }
    	    else
    	    {
    	        $status='error';
                $message='No any cab found near by you';
                $statusCode=400;     
    	    }
		}
		else
		{
		    $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;        
           
		}
		
		 }else{
		     	$status='error';
        $message='Invalid Request';
        $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    
    public function getvehicle_on_location()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
			
		$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        
		$pickup_lat=$data->pickup_lat;
		$pickup_long=$data->pickup_long;
		
		if($pickup_lat && $pickup_long)
		{
		    $get_hours=date('H');
		    
		    $qry="SELECT tmp.*,d.id as driver_id,vt.id,vt.image,vt.name,vt.description,vt.type,tmp.curr_lat,tmp.curr_long,
		    f.per_km FROM (SELECT driver_id,curr_lat, curr_long,
    	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
            cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
     	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
     	    INNER JOIN tbl_vehicletype vt ON vt.id=dmt.type_id
     	    INNER JOIN tbl_fare f ON f.vehicle_type=vt.id WHERE vt.status=1 AND d.is_online=1 AND d.status=1
     	    
     	    AND tmp.distance <= d.pickup_radius GROUP BY vt.id ORDER BY tmp.distance,f.per_km ASC";
    	    
    	    $result=$this->db->query($qry)->result_array();
    	  
    	    if(!empty($result))
    	    {
    	        
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['vehicle'][$i]['id']=$row['id'];
    	            $response['vehicle'][$i]['driver_id']=$row['driver_id'];
    	            $response['vehicle'][$i]['name']=$row['name'];
    	            $response['vehicle'][$i]['image']=base_url().$row['image'];
    	            $response['vehicle'][$i]['description']=$row['description'];
    	            $response['vehicle'][$i]['type']=$row['type'];
    	            $response['vehicle'][$i]['curr_lat']=$row['curr_lat'];
    	            $response['vehicle'][$i]['curr_long']=$row['curr_long'];
    	            
    	            $i++;
    	        }
    	        
    	        
    	        $status='success';
                $message='Data found';
                $statusCode=200;   
    	        
    	    }
    	    else
    	    {
    	        $status='error';
                $message='No any cab found near by you';
                $statusCode=400;     
    	    }
		}
		else
		{
		    $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;        
           
		}
		
		 }else{
		     	$status='error';
        $message='Invalid Request';
        $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }


     public function getnotes()
     {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		if ($_SERVER['REQUEST_METHOD'] == 'GET')
		{
	
			
    		$json = $this->security->xss_clean(file_get_contents('php://input'));
            $data = json_decode($json);
    		
    		    
    		    $qry="SELECT * FROM  tbl_pickup_notes ORDER BY id ";
        	    
        	    $result=$this->db->query($qry)->result_array();
        	    
        	    if($result)
        	    {
        	        $response = [];
                    $deliveryNotes = [
                        'notes' => [],
                        'additional_instructions' => []
                    ];
                    $otherNotes = [];
                    
                    foreach ($result as $row) {
                      
                        if (!empty($row['delivery_option'])) {
                            $deliveryNotes['notes'][] = $row['delivery_option'];
                        }
                    
                       
                        if (!empty($row['additional_instructions'])) {
                            $deliveryNotes['additional_instructions'][] = $row['additional_instructions'];
                        }
                    
                        
                        // if (!empty($row['custom_note'])) {
                        //     $otherNotes[] = [
                        //         'id' => $row['id'],
                        //         'custom_note' => $row['custom_note'],
                        //     ];
                        // }
                        
                    }

                   
                    $response['delivery_notes'] = $deliveryNotes;
                    // $response['other_notes'] = $otherNotes;
        	        
        	        
        	       
        	        $status='success';
                    $message='Data found';
                    $statusCode=200;  
                
        	    }
        	    else
        	    {
                    $status='failed';
                    $message='No data found';
                    $statusCode=400; 
        	        
        	    }
        	    
    		
		
		 }else{
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function get_rental_vehicle()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
			
		$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        
		$pickup_lat=$data->pickup_lat;
		$pickup_long=$data->pickup_long;
	    $hours=$data->hours;
		$kms=$data->kms;
		
		
		if($pickup_lat && $pickup_long && $hours && $kms)
		{
		    $get_hours=date('H');
		    
		    $qry="SELECT tmp.*,vt.id,vt.image,vt.name,vt.description,vt.type,
		    prmo.promo_code_discount,prmo.status as promo_status,
		    f.per_km FROM (SELECT driver_id,
    	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
            cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
     	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
     	    INNER JOIN tbl_vehicletype vt ON vt.id=dmt.type_id
     	    INNER JOIN promocode prmo ON prmo.vehicletype_id=vt.id
     	    INNER JOIN tbl_fare f ON f.vehicle_type=vt.id WHERE vt.status=1 AND d.is_online=1 AND d.status=1
     	    
     	    AND tmp.distance <= '".DEFAULT_NEARBY_DRIVER_AREA."' GROUP BY vt.id ORDER BY tmp.distance,f.per_km ASC";
    	    
    	    $result=$this->db->query($qry)->result_array();
    	    
    	    if(!empty($result))
    	    {
    	       // $total_distance=$this->distance($pickup_lat,$pickup_long,$drop_lat,$drop_long,'K');
    	       
    	         $total_distance=$kms;
    	        
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['vehicle'][$i]['id']=$row['id'];
    	            $response['vehicle'][$i]['name']=$row['name'];
    	            $response['vehicle'][$i]['image']=base_url().$row['image'];
    	            $response['vehicle'][$i]['description']=$row['description'];
    	             $response['vehicle'][$i]['type']=$row['type'];
    	             $response['vehicle'][$i]['promocode_status']=$row['promo_status'];
    	            
    	            if($total_distance > 0) 
    	            {
    	                    $fare = round($total_distance*$row['per_km'],2);
    	                    
    	                   $discountfare = round($fare * ($row['promo_code_discount'] / 100));
    	                  
    	                    
    	                    if($row['promo_status']=='APPLIED')
    	                    {
                                $netfare=round($fare-$discountfare,2);
                                
                                $response['vehicle'][$i]['fare']=round($total_distance*$row['per_km'],2);
        	                    $response['vehicle'][$i]['discount']=$row['promo_code_discount'].'%';
        	                    $response['vehicle'][$i]['net_fare']=$netfare;
                                
    	                    }
    	                    else
    	                    {
    	                       $response['vehicle'][$i]['fare']=round($total_distance*$row['per_km'],2);
        	                    $response['vehicle'][$i]['discount']=$row['promo_code_discount'].'%';;
        	                    $response['vehicle'][$i]['net_fare']=$fare;
    	                    }
                            
    	                    
    	            }
    	            else
    	            {
    	                $response['vehicle'][$i]['fare']=$row['per_km'];
    	            }
    	            
    	           
    	            
    	            $i++;
    	        }
    	        
    	        
    	        $status='success';
                $message='Data found';
                $statusCode=200;   
    	        
    	    }
    	    else
    	    {
    	        $status='error';
                $message='No any cab found near by you';
                $statusCode=400;     
    	    }
		}
		else
		{
		    $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;        
           
		}
		
		 }else{
		     	$status='error';
        $message='Invalid Request';
        $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
     public function rental_booking()
     {
        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_type=$data->booking_type;
        
        if($booking_type=='rental')
        {
            // die;
            
                $pickup_lat=$data->pickup_lat;
        		$pickup_long=$data->pickup_long;
        		$user_id=$data->user_id;
        		$added_by_web=$data->added_by_web;
        		$pickup_address=$data->pickup_address;
        		$booking_type=$data->booking_type;
        		
        		
        		if($pickup_lat && $pickup_address && $booking_type && $user_id)
        		{
        		    $this->db->where('user_id',$user_id);
        		    $this->db->update('tbl_userwise_cabrequest',array('is_latest_request'=>0));
        		    
        		    
        		    $qry="SELECT tmp.*,dmt.type_id,f.per_km,
        		    
        		    d.f_token_app,TIMESTAMPDIFF(MINUTE,d.accepted_request_time,NOW())
        		    as driverreq_accepted_time FROM(SELECT driver_id,
            	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
                    cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
            	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
            	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
            	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
             	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
             	    INNER JOIN tbl_fare f ON f.vehicle_type=dmt.type_id
             	    WHERE d.is_online=1 AND d.status=1 AND tmp.distance <= ".DEFAULT_NEARBY_DRIVER_AREA." ORDER BY tmp.distance ASC";
             	    
        	        
        		    $result=$this->db->query($qry)->result_array();
        		  
        		  $qry1="SELECT * FROM tbl_rental_km_hrs ORDER BY id";
        		  
        		  $result1=$this->db->query($qry1)->result_array();
        		   
        		    if(!empty($result))
            	    {
            	        
            	        
            	       $request_id='REQ-'.sprintf("%08d", mt_rand(0, 999999));
            	       
            	       $response = [
                                'package' => ['km' => [], 'hr' => []]
                            ];
                            
                            foreach ($result1 as $sing) {
                                $response['package']['km'][] = intval($sing['km']);
                                $response['package']['hr'][] = intval($sing['hrs']);
                            }
            	       
            	       
        	           //   $response = [
                    //         'package' => ['km' => [],'hr' => []]];
                            
                    //     $response['package']['km'] = array_map('intval', explode(',', $result[0]['kms']));
                    //     $response['package']['hr'] = array_map('intval', explode(',', $result[0]['hours']));
        
            	        
            	        $i=0;
            	        foreach($result as $row)
            	        {
            	            
            	            $data=array(
                	                 'req_id'=>$request_id,
                	                 'pickup_address'=>$pickup_address,
                	                 'pickup_lat'=>$pickup_lat,
                	                 'pickup_long'=>$pickup_long,
                	                 'user_id'=>$user_id,
                	                 'driver_id'=>$row['driver_id'],
                	                 'type_id'=>$row['type_id'],
                	                 'driver_away'=>$row['distance'],
                	                 'per_km_fare'=>$row['per_km'],
                	                 'entry_date'=>date('Y-m-d H:i:s'),
                	                 'added_by_web'=>$added_by_web,
                                      'booking_type'=>$booking_type,
                	                );
                	       $this->db->insert('tbl_userwise_cabrequest',$data);
                	       
                	       if($row['f_token_app'])
            	            {
                	            //send notification
                	            $body="You have received a new ride request of pickup locaion ".$pickup_address." from a user .";
                	            $title="New Ride Request";
                	            sendNotificationFlutter($row['f_token_app'],$body,$title);
            	            }
            	            
            	            $i++;
            	        }
            	        
            	       // $response['package']['km'][] = (int)$result['kms'];
                    //     $response['package']['hr'][] = (int)$result['hours'];
                    
            
                    
                   
            	        
            	        
            	        $status='success';
                        $message='Data found';
                        $statusCode=200;   
            	        
            	    }
        		    
        		    else
        		    {
        		        $status='error';
                        $message='No any driver found near by you.';
                        $statusCode=400;    
                        
        		    }
        		}
        		else
        		{
        		    $status='error';
                    $message='Please fill in all required fields.';
                    $statusCode=400;        
                   
        		}
        		
        
        //rental booking
		
		
        }
        
        
        if($booking_type=='recuring')
        {
            // recuring booking
            
                $pickup_lat=$data->pickup_lat;
        		$pickup_long=$data->pickup_long;
        	    $drop_lat=$data->drop_lat;
        		$drop_long=$data->drop_long;
        		$user_id=$data->user_id;
        		$added_by_web=$data->added_by_web;
        		$pickup_address=$data->pickup_address;
        		$drop_address=$data->drop_address;
        		$booking_type=$data->booking_type;
		
		
		    if($pickup_lat && $pickup_long && $drop_lat && $drop_long && $pickup_address && $drop_address)
	    	{
    		    $this->db->where('user_id',$user_id);
    		    $this->db->update('tbl_userwise_cabrequest',array('is_latest_request'=>0));
		    
		    
    		    $qry="SELECT tmp.*,dmt.type_id,f.per_km,f.hours,f.kms,
    		    d.f_token_app,TIMESTAMPDIFF(MINUTE,d.accepted_request_time,NOW()) as driverreq_accepted_time FROM(SELECT driver_id,
        	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
                cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
        	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
        	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
        	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
         	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
         	    INNER JOIN tbl_fare f ON f.vehicle_type=dmt.type_id
         	    WHERE d.is_online=1 AND d.status=1 
         	    AND tmp.distance <= ".DEFAULT_NEARBY_DRIVER_AREA." ORDER BY tmp.distance ASC";
	        
		        $result=$this->db->query($qry)->result_array();
		    
    		    if(!empty($result))
    		    {
    		        $total_distance=$this->distance($pickup_lat,$pickup_long,$drop_lat,$drop_long,'K');
        	        $request_id='REQ-'.sprintf("%08d", mt_rand(0, 999999));
        	        
        	         $response = [
                        'package' => ['km' => [],'hr' => []]];
                            
                    $response['package']['km'] = array_map('intval', explode(',', $result[0]['kms']));
                    $response['package']['hr'] = array_map('intval', explode(',', $result[0]['hours']));
                    
                    $response['package']['distnace'] = round($total_distance,2);
        	        
        	        
    		        foreach($result as $row)
        	        {
        	           // if($row['driverreq_accepted_time'] > REQUESTEXPIRE_TIME)
        	           // {
            	            $data=array(
            	                 'req_id'=>$request_id,
            	                 'pickup_address'=>$pickup_address,
            	                 'drop_address'=>$drop_address,
            	                 'pickup_lat'=>$pickup_lat,
            	                 'pickup_long'=>$pickup_long,
            	                 'drop_lat'=>$drop_lat,
            	                 'drop_long'=>$drop_long,
            	                 'user_id'=>$user_id,
            	                 'driver_id'=>$row['driver_id'],
            	                 'type_id'=>$row['type_id'],
            	                 'driver_away'=>$row['distance'],
            	                 'user_journey_distance'=>round($total_distance,2),
            	                 'per_km_fare'=>$row['per_km'],
            	                 'entry_date'=>date('Y-m-d H:i:s'),
            	                 'added_by_web'=>$added_by_web,
                                'booking_type'=>$booking_type,
            	                );
            	            $this->db->insert('tbl_userwise_cabrequest',$data);
            	            
            	           
            	            if($row['f_token_app'])
            	            {
                	            //send notification
                	            $body="You have received a new ride request of pickup locaion ".$pickup_address." from a user .";
                	            $title="New Ride Request";
                	            sendNotificationFlutter($row['f_token_app'],$body,$title);
            	            }
            	            
            	           
        	           // }
        	        }
        	        
        	        
        	      
        	        $status='success1234';
                    $message='Request has been send successfully';
                    $statusCode=200;
                    
                    
                    
                    
    		    }
    		    else
    		    {
    		        $status='error';
                    $message='No any driver found near by you.';
                    $statusCode=400;   
    		    }
		    }
    		else
    		{
    		    $status='error';
                $message='Please fill in all required fields.';
                $statusCode=400;        
               
    		}
        		
        		
            
            
        }
		
		
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function booking_type_auth()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		$status='error';
        $message='Invalid Request';
        $statusCode=400;
        
        if ($_SERVER['REQUEST_METHOD'] == 'GET') 
        {
            $sql = "SELECT * FROM tbl_booking_mode_auth ORDER BY id";
            $result = $this->db->query($sql)->result_array();
            
            if (!empty($result))
            {
                $response['pre_booking'] = [];
                $response['rental'] = [];
                $response['book_now'] = [];
        
                foreach ($result as $row)
                {
                    $entry = [
                        // 'id' => $row['id'],
                        'status' => $row['status']
                    ];
                    
                    if ($row['booking_type'] == 'pre_booking') {
                        $response['pre_booking'][] = $entry;
                    } elseif ($row['booking_type'] == 'rental') {
                        $response['rental'][] = $entry;
                    } elseif ($row['booking_type'] == 'book_now') {
                        $response['book_now'][] = $entry;
                    }
                }
        
                $response['status'] = 'success';
                $response['message'] = 'Data found';
                $response['statusCode'] = 200;
            }
            else
            {
                $response['status'] = 'error';
                $response['message'] = 'No Data Found';
                $response['statusCode'] = 400;
            }
        
            // Return the JSON response
            echo json_encode($response);
        }
	
    }
    
    public function recuring_offers()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
       
		if ($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
		    
		    $startDate = DateTime::createFromFormat('d/m/Y', $data->startDate);
                $endDate = DateTime::createFromFormat('d/m/Y', $data->endDate);
                $interval = $startDate->diff($endDate);
                $no_of_days = $interval->days + 1; 
               
                $fare_per_day = $data->vehicleFare;
                $total_fare = $fare_per_day * $no_of_days;
                $booking_type = $data->bookingType;
		    
		    $qry="SELECT * FROM tbl_recuring_recharge_offers ORDER BY id DESC ";
    	    
    	    $result=$this->db->query($qry)->result_array();
    	    
    	    if(!empty($result))
    	    {
    	        
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['offers'][$i]['id']=$row['id'];
    	            $response['offers'][$i]['weeks']=intval($row['weeks']);
    	            $response['offers'][$i]['cashback_amount']=intval(round($row['cashback_amount'],2));
    	            $response['offers'][$i]['top_up_amount']=intval(round($row['top_up_amount'],2));
    	            $i++;
    	        }
    	        
    	        
                $response['data']['no_of_days']=$no_of_days;
                $response['data']['total_fare']=$total_fare;
                $response['data']['booking_type']=$booking_type;
                $response['data']['startdate']=$data->startDate;
                $response['data']['enddate']=$data->endDate;
                $response['data']['distance']=$data->distance;
                $response['data']['vehicleFare']=$data->vehicleFare;
    	     
    	        
    	        
    	        $status='success';
                $message='Data found';
                $statusCode=200;   
    	        
    	    }
    	    else
    	    {
    	        $status='error';
                $message='No any Recuring offers ';
                $statusCode=400;     
    	    }
		
		
		 }
		 else
		 {
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    
    public function dashboard()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
// 		$json = $this->security->xss_clean(file_get_contents('php://input'));
//         $data = json_decode($json);
       
		if ($_SERVER['REQUEST_METHOD'] == 'GET') 
		{
		    
		    $qry="SELECT * FROM main_banner WHERE status='Active' OR status='active' ORDER BY id DESC ";
    	    $result=$this->db->query($qry)->result_array();
    	    
    	    
    	    $sql1 = "SELECT * FROM tbl_booking_mode_auth ORDER BY id";
            $resultmode = $this->db->query($sql1)->result_array();
    	    
    	    if(!empty($result))
    	    {
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['banner'][$i]['id']=$row['id'];
    	            $response['banner'][$i]['banner_name']=$row['banner_name'];
    	            $response['banner'][$i]['appbanner_image']=base_url().$row['appbanner_image'];
    	            $response['banner'][$i]['link']=$row['link'];
    	             $response['banner'][$i]['status']=$row['status'];
    	            $i++;
    	        }
    	        
    	        foreach ($resultmode as $row)
                {
                    $entry = [
                        // 'id' => $row['id'],
                        'status' => $row['status']
                    ];
                    
                    if ($row['booking_type'] == 'pre_booking') {
                        $response['pre_booking'][] = $entry;
                    } elseif ($row['booking_type'] == 'rental') {
                        $response['rental'][] = $entry;
                    } elseif ($row['booking_type'] == 'book_now') {
                        $response['book_now'][] = $entry;
                    }
                }
    	        
    	        
    	        
    	        $status='success';
                $message='Data found';
                $statusCode=200;   
    	        
    	    }
    	    else
    	    {
    	        $status='error';
                $message='No data Found ';
                $statusCode=400;     
    	    }
		
		
		 }
		 else
		 {
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function cab_request_on_user_id()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
       
		if ($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
		    
		    $user_id=$data->user_id;
		    
		    
		   $qry="SELECT b.*,DATE_FORMAT(b.entry_date,'%d/%m/%Y %H:%i %p') AS entrydate,
            tbc.selecteddate,tbc.selectedtime,tu.f_name,tu.mobile_no,tu.email_id,dr.email as d_email,dr.driver_name as driver_name,
            dr.mobile_no as d_mobile_no,dr.gender as d_gender,dr.address as d_address,
            dr.driver_profile_pic as d_driver_profile_pic,feed.feedback as d_feedback,feed.rating as d_rating
            FROM tbl_booking b
            INNER JOIN tbl_userwise_cabrequest tbc ON tbc.user_id=b.user_id 
            INNER JOIN tbl_user tu ON tu.id=b.user_id 
            INNER JOIN tbl_driver dr ON dr.id=tbc.driver_id 
            INNER JOIN tbl_feedback_list feed ON feed.driver_id=tbc.driver_id 
            WHERE tbc.status=0 AND b.user_id='$user_id' GROUP BY b.book_id ORDER BY b.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]['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]['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'];
                    $response['list'][$i]['driver_name']=$row['driver_name'];
                    $response['list'][$i]['driver_email']=$row['d_email'];
                    $response['list'][$i]['driver_mobile_no']=$row['d_mobile_no'];
                    $response['list'][$i]['driver_gender']=$row['d_gender'];
                    $response['list'][$i]['driver_address']=$row['d_address'];
                    $response['list'][$i]['driver_driver_profile_pic']=base_url().$row['d_driver_profile_pic'];
                    $response['list'][$i]['driver_feedback']=$row['d_feedback'];
                    $response['list'][$i]['driver_rating']=$row['d_rating'];
                    $response['list'][$i]['pickup_lat']=$row['pickup_lat'];
                    $response['list'][$i]['pickup_long']=$row['pickup_long'];
                     $response['list'][$i]['drop_lat']=$row['drop_lat'];
                    $response['list'][$i]['drop_long']=$row['drop_long'];
                    
                    
                    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++;
                }
                
                
                $message='Data found';
                $status='success';
                $statusCode=200;
            }
    	    
    	    
    	    else
    	    {
    	        $status='error';
                $message='No data Found ';
                $statusCode=400;     
    	    }
		
		
		 }
		 else
		 {
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function get_offers()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
			
		$json = $this->security->xss_clean(file_get_contents('php://input'));
        $data = json_decode($json);
        
		$pickup_lat=$data->pickup_lat;
		$pickup_long=$data->pickup_long;
	    $drop_lat=$data->drop_lat;
		$drop_long=$data->drop_long;
		
		$vehicletype_id=$data->vehicletype_id;
		
		
		if($pickup_lat && $pickup_long && $drop_lat && $drop_long && $vehicletype_id) 
		{
		    $get_hours=date('H');
		    
		    $qry="SELECT tmp.*,vt.id,vt.image,vt.name,vt.description,vt.type,
		    prmo.promo_code_name,prmo.promo_code,prmo.image,prmo.promo_code_discription,prmo.promo_code_discount,
		    prmo.start_date,prmo.expiry_date,prmo.status,prmo.id as coupon_id,prmo.image as promo_img,
		    f.per_km FROM (SELECT driver_id,
    	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
            cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
     	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
     	    INNER JOIN tbl_vehicletype vt ON vt.id=dmt.type_id
     	    INNER JOIN promocode prmo ON prmo.vehicletype_id=vt.id
     	    INNER JOIN tbl_fare f ON f.vehicle_type=vt.id WHERE vt.status=1 AND d.is_online=1 AND d.status=1
     	    AND prmo.applied_status=0 AND prmo.vehicletype_id=$vehicletype_id
     	    AND tmp.distance <= '".DEFAULT_NEARBY_DRIVER_AREA."' GROUP BY vt.id ORDER BY tmp.distance,f.per_km ASC";
    	    
    	    $result=$this->db->query($qry)->result_array();
    	    
    	    if(!empty($result))
    	    {
    	        $total_distance=$this->distance($pickup_lat,$pickup_long,$drop_lat,$drop_long,'K');
    	        
    	        $i=0;
    	        foreach($result as $row)
    	        {
    	            $response['vehicle'][$i]['coupon_id']=$row['coupon_id'];
    	            $response['vehicle'][$i]['promocode_img']=$row['promo_img'];
    	            //$response['vehicle'][$i]['promo_code_name']=base_url().$row['promo_code_name'];
    	            $response['vehicle'][$i]['promo_code']=$row['promo_code'];
    	            $response['vehicle'][$i]['promo_code_discription']=$row['promo_code_discription'];
    	            $response['vehicle'][$i]['promo_code_discount']=$row['promo_code_discount'].'%';
    	            $response['vehicle'][$i]['start_date']=$row['start_date'];
    	            $response['vehicle'][$i]['expiry_date']=$row['expiry_date'];
    	            $response['vehicle'][$i]['coupon_status']=$row['status'];
    	            
    	            
    	            if($total_distance > 0) 
    	            {
    	                     $fare = round($total_distance*$row['per_km'],2);
                            $discountfare = round($fare * ($row['promo_code_discount'] / 100), 2);
                            $netfare=round($fare-$discountfare,2);
                            
    	                    $response['vehicle'][$i]['fare']=round($total_distance*$row['per_km'],2);
    	                    $response['vehicle'][$i]['discount']=$discountfare;
    	                    $response['vehicle'][$i]['net_fare']=$netfare;
    	            }
    	            else
    	            {
    	                $response['vehicle'][$i]['fare']=$row['per_km'];
    	                
    	            }
    	            
    	           
    	            
    	            $i++;
    	        }
    	        
    	        
    	        $status='success';
                $message='Data found';
                $statusCode=200;   
    	        
    	    }
    	    else
    	    {
    	        $status='error';
                $message='No anny coupon for this vehicle';
                $statusCode=400;     
    	    }
		}
		else
		{
		    $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;        
           
		}
		
		 }else{
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function apply_coupon()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		 if ($_SERVER['REQUEST_METHOD'] == 'POST') 
		 {
	
			
    		$json = $this->security->xss_clean(file_get_contents('php://input'));
            $data = json_decode($json);
        
	        $coupon_id=$data->coupon_id;
		
    		if($coupon_id) 
    		{
    		    
    		    $qry="SELECT * FROM promocode WHERE id= $coupon_id AND applied_status = 0 
    		    AND status LIKE 'Active'";
        	    
        	    $result=$this->db->query($qry)->row_array();
        	    
        	    if(!empty($result))
        	    {
        	        $updata=array(
        	            'applied_status'=>1,
        	            'status'=>'APPLIED',
        	        );
        	        
        	        $this->db->where('id',$coupon_id);
        	        $this->db->update('promocode',$updata);
        	        
        	        
        	        $status='success';
                    $message='Coupon Applied Successfully';
                    $statusCode=200;   
        	        
        	    }
        	    else
        	    {
        	        $status='error';
                    $message='Invalid Coupon Id';
                    $statusCode=400;     
        	    }
    		}
    		else
    		{
    		    $status='error';
                $message='Please fill in all required fields.';
                $statusCode=400;        
               
    		}
		
		 }
		 else
		 {
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function submit_feedback()
     {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		
		
		 if ($_SERVER['REQUEST_METHOD'] == 'POST') 
		 {
	
			
    		$json = $this->security->xss_clean(file_get_contents('php://input'));
            $data = json_decode($json);
        
            $user_id=$data->userid;
            $rating=$data->rating;
            $feedback=$data->feedback;
            $driver_id=$data->driver_id;
	           
		
    		if($user_id  && $driver_id) 
    		{
    		    
    		    $sql="SELECT * FROM tbl_feedback_list WHERE user_id = $user_id AND driver_id = $driver_id ";
    		    
    		    $rowdata=$this->db->query($sql)->row();
    		    
    		    if(empty($rowdata))
    		    {        		    $data=array(
        		        'rating'=>$rating,
        		        'user_id'=>$user_id,
        		        'feedback'=>$feedback,
        		        'driver_id'=>$driver_id,
        		        );
        		        
        		  $this->db->insert('tbl_feedback_list',$data);
        		  $insert_id = $this->db->insert_id();
    		  
    		    }
    		    else
    		    {
    		        
    		            $updata=array(
        		        'rating'=>$rating,
        		        'feedback'=>$feedback,
        		        'updated_at'=>date('Y-m-d H:i:s'),
        		        );
        		        
        		        
    		        $this->db->where('user_id',$user_id);
    		        $this->db->where('driver_id',$driver_id);
    		        $this->db->update('tbl_feedback_list',$updata);
    		        
    		    }
    		  
    		  
		        $status='success';
                $message='Feedback saved';
                $statusCode=200; 
    		    
    		    
    		}
    		else
    		{
    		    $status='error';
                $message='Please fill in all required fields.';
                $statusCode=400;        
               
    		}
		
		 }
		 else
		 {
		     	$status='error';
                $message='Invalid Request';
                $statusCode=400;
		 }
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    
    public function sendReqForfindDriver()
    {
        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);
        
		$pickup_lat=$data->pickup_lat;
		$pickup_long=$data->pickup_long;
	    $drop_lat=$data->drop_lat;
		$drop_long=$data->drop_long;
		$vehicle_type_id=$data->vehicle_type_id;
		$user_id=$data->user_id;
		$added_by_web=$data->added_by_web;
		
		$pickup_address=$data->pickup_address;
		$drop_address=$data->drop_address;
		$booking_type=$data->booking_type;
		
		
		if($pickup_lat && $pickup_long && $drop_lat && $drop_long && $vehicle_type_id && $pickup_address && $drop_address && $booking_type)
		{
		    $this->db->where('user_id',$user_id);
		    $this->db->update('tbl_userwise_cabrequest',array('is_latest_request'=>0));
		    
		    $qry="SELECT tmp.*,dmt.type_id,f.per_km,d.f_token_app,TIMESTAMPDIFF(MINUTE,d.accepted_request_time,NOW()) as driverreq_accepted_time FROM(SELECT driver_id,
    	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
            cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
     	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
     	    INNER JOIN tbl_fare f ON f.vehicle_type=dmt.type_id
     	    WHERE d.is_online=1 AND d.status=1 AND dmt.type_id=$vehicle_type_id AND tmp.distance <= ".DEFAULT_NEARBY_DRIVER_AREA." ORDER BY tmp.distance ASC";
	        
		    $result=$this->db->query($qry)->result_array();
		    
		    if(!empty($result))
		    {
		        $total_distance=$this->distance($pickup_lat,$pickup_long,$drop_lat,$drop_long,'K');
    	        $request_id='REQ-'.sprintf("%08d", mt_rand(0, 999999));
    	        
    	        
		        foreach($result as $row)
    	        {
    	           // if($row['driverreq_accepted_time'] > REQUESTEXPIRE_TIME)
    	           // {
        	            $data=array(
        	                 'req_id'=>$request_id,
        	                 'pickup_address'=>$pickup_address,
        	                 'drop_address'=>$drop_address,
        	                 'pickup_lat'=>$pickup_lat,
        	                 'pickup_long'=>$pickup_long,
        	                 'drop_lat'=>$drop_lat,
        	                 'drop_long'=>$drop_long,
        	                 'user_id'=>$user_id,
        	                 'booking_type'=>$booking_type,
        	                 'driver_id'=>$row['driver_id'],
        	                 'type_id'=>$row['type_id'],
        	                 'driver_away'=>$row['distance'],
        	                 'user_journey_distance'=>round($total_distance,2),
        	                 'per_km_fare'=>$row['per_km'],
        	                 'entry_date'=>date('Y-m-d H:i:s'),
        	                 'added_by_web'=>$added_by_web,
        	                );
        	            $this->db->insert('tbl_userwise_cabrequest',$data);
        	            
        	        $req_id = $this->db->insert_id();
        	        
        	        
        	            
        	           
        	            if($row['f_token_app'])
        	            {
            	            //send notification
            	            $body="You have received a new ride request of pickup locaion ".$pickup_address." from a user .";
            	            $title="New Ride Request";
            	            sendNotificationFlutter($row['f_token_app'],$body,$title);
        	            }
        	            
        	           
    	           // }
    	        }
    	        
    	        
    	        $response['vehicle_type_id']=$vehicle_type_id;
    	        $response['req_id']= $req_id;
    	        $status='success';
                $message='Request has been send successfully';
                $statusCode=200;
		    }
		    else
		    {
		        $status='error';
                $message='No any driver found near by you.';
                $statusCode=400;     
		    }
		}
		else
		{
		    $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;        
           
		}
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    
    public function findDriver()
    {
        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_type_id=$data->vehicle_type_id;
		$user_id=$data->user_id;
        if($vehicle_type_id && $user_id)
        {
            $qry="SELECT d.*,r.id as requestid,r.driver_away,r.user_journey_distance,r.per_km_fare,r.pickup_address,r.drop_address, 
            r.pickup_lat,r.pickup_long,r.drop_lat,r.drop_long,vt.name as vehiclename,vt.image as vehicleimage
            FROM tbl_userwise_cabrequest r
            INNER JOIN tbl_driver d ON d.id=r.driver_id
            INNER JOIN tbl_vehicletype vt ON vt.id=r.type_id
            WHERE r.user_id=$user_id AND r.type_id=$vehicle_type_id AND r.status=1 AND r.is_latest_request=1 ORDER BY id ASC";
            
            $result=$this->db->query($qry)->row_array();
            
            if(!empty($result))
            {
                $response['send_request_id']=$result['requestid'];
                $response['pickup_address']=$result['pickup_address'];
                $response['pickup_lat']=$result['pickup_lat'];
                $response['pickup_long']=$result['pickup_long'];
                $response['drop_address']=$result['drop_address'];
                $response['drop_lat']=$result['drop_lat'];
                $response['drop_long']=$result['drop_long'];
                
                $response['driver_name']=$result['driver_name'];
                $response['driver_id']=$result['driver_id'];
                $response['mobile_no']=$result['mobile_no'];
                $response['driver_profile_pic']=base_url().$result['driver_profile_pic'];
                $response['email']=$result['email'];
                $response['driver_away']=(int)$result['driver_away'];
                $response['user_journey_distance']=(int)$result['user_journey_distance'];
                $response['total_fare']=(int)round($result['user_journey_distance']*$result['per_km_fare'],2);
                
                $response['vehicle_name']=$result['vehiclename'];
                $response['vehicle_image']=base_url().$result['vehicleimage'];
                $status='success';
                $message='success';
                $statusCode=200;  
            }
            else
            {
                $status='error';
                $message='Request not accept from driver side.';
                $statusCode=400;  
            }
        }
        else
        {
            $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;  
        }
        $response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    public function findDriver_static()
    {
        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_type_id=$data->vehicle_type_id;
		$user_id=$data->user_id;
        if($vehicle_type_id && $user_id)
        {
            
                $sql="SELECT * FROM  tbl_feedback_list WHERE user_id = $user_id";
                $resdata=$this->db->query($sql)->row();
            
            
                $response['send_request_id']='5';
                $response['pickup_address']='Odisha';
                $response['pickup_lat']=20.856874349764800;
                $response['pickup_long']=70.612737372598010;
                $response['drop_address']='Bhubaneswar';
                $response['drop_lat']=20.858874743013917;
                $response['drop_long']=18.858874743013917;
                
                $response['driver_name']='raman';
                $response['driver_id']=3;
                $response['mobile_no']=8851385847;
                $response['driver_profile_pic'] = base_url() . "uploads/images/DriverProfile/img_1712835068.png";

                $response['email']='itrs@gmail.com';
                $response['driver_away']=20;
                $response['user_journey_distance']=50;
                $response['total_fare']=500;
                
                $response['vehicle_name']='Tesla';
                $response['vehicle_image']=base_url()."uploads/images/VehicleActive/img_1712731315.jpg";
                
                 $response['rating']=isset($resdata->rating)?$resdata->rating:'';
                 $response['feedback']=isset($resdata->feedback)?$resdata->feedback:'';
                $status='success';
                $message='success';
                $statusCode=200;  
            
        }
        else
        {
            $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;  
        }
        $response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    
    public function distance($lat1, $lon1, $lat2, $lon2, $unit) {
      if (($lat1 == $lat2) && ($lon1 == $lon2)) {
        return 0;
      }
      else {
        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
    
        if ($unit == "K") {
          return ($miles * 1.609344);
        } else if ($unit == "N") {
          return ($miles * 0.8684);
        } else {
          return $miles;
        }
      }
    }
    
    
    public function paynow()
    {
    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);

    // Validate input data
    if (empty($data->send_request_id) || empty($data->added_by_web) || empty($data->user_id) || empty($data->paymenttype)) {
        $status = 'error';
        $message = 'Missing required fields';
        $statusCode = 400;
    } else {
        $send_request_id = $data->send_request_id;
        $added_by_web = $data->added_by_web;
        $user_id = $data->user_id;
        $paymenttype = $data->paymenttype;
        $conv_charge = isset($data->conv_charge) ? $data->conv_charge : 0;

        $qry = "SELECT * FROM tbl_userwise_cabrequest WHERE id = '$send_request_id' AND user_id = '$user_id' AND status = 1 
        AND is_latest_request = 1";
        $row = $this->db->query($qry)->row_array();

        if (!empty($row)) {
            $trans_id = '';
            $booking_id = 'Book-' . sprintf("%08d", mt_rand(0, 999999));
            $total_payble = round($row['per_km_fare'] * $row['user_journey_distance'], 2);

            if ($paymenttype != 'razorpay') {
                $order_id = $this->generateOrderID($user_id);
            } else {
                $keyId = RZ_KEY;
                $keySecret = RZ_SECRETKEY;
                
                $orderData = [
                    'amount' => (int)$total_payble * 100,
                    'currency' => 'INR',
                ];
                $jsonData = json_encode($orderData);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/orders');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($jsonData)
                ]);
                curl_setopt($ch, CURLOPT_USERPWD, $keyId . ':' . $keySecret);

                $pay_response = curl_exec($ch);

                if (curl_errno($ch)) {
                    $order_id = '';
                    $message = 'Failed to create Razorpay order';
                } else {
                    $responseData = json_decode($pay_response, true);
                    if (isset($responseData['id'])) {
                        $order_id = $responseData['id'];
                    } else {
                        $order_id = '';
                        $message = 'Invalid response from Razorpay';
                    }
                }

                curl_close($ch);
            }

            if ($paymenttype == 'online') {
                $trans_id = $this->generateTransID();
                $total_payble = round($total_payble + $conv_charge);

                $login_user = [
                    'booking_id' => $booking_id,
                    'user_id' => $user_id,
                    'order_id' => $order_id,
                    'trans_id' => $trans_id,
                    'payment_type' => 'online',
                    'trans_amount' => $total_payble,
                    'conv_charge' => $conv_charge,
                    'added_by_web' => $added_by_web,
                    'ip' => $_SERVER["REMOTE_ADDR"],
                    'entry_date' => date('Y-m-d H:i:s'),
                ];

                $this->db->insert('tbl_user_trans', $login_user);
            } else {
                $conv_charge = 0;
            }

            $response['order_id'] = $order_id;
            $response['MID'] = "";
            $response['WEB_CALLBACK_URL'] = "";
            $response['CONV_CHARGE'] = (int)$conv_charge;
            $response['MAIN_AMOUNT'] = $total_payble - $conv_charge;
            $response['TXN_AMOUNT'] = $total_payble;
            $response['CUST_ID'] = $trans_id;
            $response['booking_id'] = $booking_id;
            $response['payment_type'] = $paymenttype;

            $status = 'success';
            $message = 'Payment initiated successfully';
            $statusCode = 200;
        } else {
           $message = 'Invalid booking ID or request not accepted';
        }
    }

    $response['status'] = $status;
    $response['message'] = $message;
    $response['statusCode'] = $statusCode;
    echo json_encode($response);
}

    public function online_payment_notification()
    {
        
        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;
        	$status=$data->status;
        	$order_no=$data->order_no;
        	$txn_amt=$data->txn_amt;
        	$booking_id=$data->booking_id;
        	
        	
            	if($user_id && $status && $order_no && $txn_amt && $booking_id)
                {
                    $qry="SELECT u.mobile_no,u.f_name,u.f_token_app
                    FROM tbl_booking b 
                    INNER JOIN  tbl_user u ON u.id = b.user_id  WHERE b.book_id='$booking_id' AND u.id='$user_id' ";
                    
                    $row=$this->db->query($qry)->row_array();
                        
                    if(!empty($row))
                    { 
                        
                        if($status=='success')
                        {
                            if($row['f_token_app'])
                            {
                                $body = "Dear " . $row['f_name'] . ", your payment of Rs. " . $txn_amt . 
                                " for Order No: " . $order_no . " and Booking ID: " . $booking_id . " has been done successfully!";
                                
                	            $title="User Payment";
                	            sendNotificationapp($row['f_token_app'],$body,$title);
                	            $status='success';
                                $message='Message sent Successfully';
                                $statusCode=200; 
                            }
                        }
                           
                    }
                    else
                    {
                        $status='error';
                        $message='Something went wrong..!';
                        $statusCode=400; 
                    } 
                    
                }
                else
                {
                    $status='error';
                    $message='Please fill in all required fields.';
                    $statusCode=400;  
                }
        	
            $response['status']=$status;
    		$response['message']=$message;
    		$response['statusCode']=$statusCode;
    		echo json_encode($response);
        	
        	
        
    }

    
    
    // public function paynow()
    // {
    //     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);
        
    //     $send_request_id=$data->send_request_id;
    // 	$added_by_web=$data->added_by_web;
    // 	$user_id=$data->user_id;
    // 	$paymenttype=$data->paymenttype;
    // 	$conv_charge=$data->conv_charge;
    // 	if($send_request_id && $added_by_web && $user_id && $paymenttype)
    // 	{
    	       // 	    $qry="SELECT * FROM tbl_userwise_cabrequest WHERE id = '$send_request_id' and user_id = '$user_id'  AND status = 1 AND is_latest_request = 1";
    //         $row=$this->db->query($qry)->row_array();
            
    //         if(!empty($row))
    //         {
    // 	        //$order_id=$this->generateOrderID($row['user_id']);
    //             $trans_id='';
    //             $booking_id='Book-'.sprintf("%08d", mt_rand(0, 999999));
                
                 
    //             $total_payble=round($row['per_km_fare']*$row['user_journey_distance'],2);  
                
                
                
    //             if($paymenttype != 'razorpay')
    //             {
    //                 $order_id=$this->generateOrderID($user_id);
    //             }
    //             else
    //             {
    //                 $keyId = RZ_KEY;
    //                 $keySecret = RZ_SECRETKEY;
                    
    //                 $orderData = [
    //                     'amount'          => (int)$total_payble*100, // Amount in paise = 50000 paise = INR 500
    //                     'currency'        => 'INR',
    //                 ];
                    
    //                 $jsonData = json_encode($orderData);
                    
    //                 // Initialize cURL
    //                 $ch = curl_init();
                    
    //                 curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/orders');
    //                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //                 curl_setopt($ch, CURLOPT_POST, true);
    //                 curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    //                 curl_setopt($ch, CURLOPT_HTTPHEADER, [
    //                     'Content-Type: application/json',
    //                     'Content-Length: ' . strlen($jsonData)
    //                 ]);
    //                 curl_setopt($ch, CURLOPT_USERPWD, $keyId . ':' . $keySecret);
                    
    //                 $pay_response = curl_exec($ch);
                    
    //                 if (curl_errno($ch)) {
    //                   $order_id='';
    //                 } else {
    //                     $responseData = json_decode($pay_response, true);
    //                     if(isset($responseData['id']))
    //                     {
    //                         $order_id=$responseData['id'];
    //                     }
                        
    //                 }
                    
    //                 curl_close($ch);
    //             }
                
    //             if($paymenttype == 'online')
    //             {
    //                 $trans_id=$this->generateTransID();
                    
    //                 $total_payble=round($total_payble+$conv_charge);
                    
    //                 $login_user=array(
    //     	            'booking_id'=>$booking_id,
    //                     'user_id'=>$user_id,
    //                     'order_id'=>$order_id,
    //                     'trans_id'=>$trans_id,
    //                     'payment_type'=>'online',
    //                     'trans_amount'=>$total_payble,
    //                     'conv_charge'=>$conv_charge,
    //                     'added_by_web'=>$added_by_web,
    //                     'ip'=>$_SERVER["REMOTE_ADDR"],
    //                     'entry_date'=>date('Y-m-d H:i:s'),
    //                 );
                    
    //                 $this->db->insert('tbl_user_trans',$login_user);
    //             }
    //             else
    //             {
    //                 $conv_charge=0; 
    //             }
    //             $response['order_id']=$order_id;
    //             $response['MID']="";
    //             $response['WEB_CALLBACK_URL']="";
                
    //             $response['CONV_CHARGE']=(int)$conv_charge;
    //             $response['MAIN_AMOUNT']=$total_payble-$conv_charge;
    //             $response['TXN_AMOUNT']=$total_payble;
    //             $response['CUST_ID']=$trans_id;
    //             $response['booking_id']=$booking_id;
    //             $response['payment_type']=$paymenttype;
    
    //             $status='success';
    //             $message='success';
    //             $statusCode=200;
    // 	    }
    // 	    else
    // 	    {
    	        
    // 	         $qry_check ="SELECT * FROM tbl_userwise_cabrequest WHERE id = '$send_request_id' and user_id = '$user_id'  AND status = 0 AND is_latest_request = 1";
    //         $result = $this->db->query($qry_check)->row_array();
    	    
    	    
    	    
    // 	    if(!empty($result)){
    	        
    	        
    	       
    //             $message='Driver is not Acccept the request  ';
               
    	    
    	        
    // 	    }else{
    // 	         $message='This booking is  not valid for payment,  Due to Invalid Request Id  ';
    // 	    }
    	    
    	        
    	        
    	        
    	        
    	        
    	        
    	        
    	        
    // 	        $status='error';
               
    //             $statusCode=400;  
    // 	    }
    // 	}
    // 	else
    // 	{
    // 	    $status='error';
    //         $message='Booking id required';
    //         $statusCode=400;    
    // 	}
    	
    //     $response['status']=$status;
    // 	$response['message']=$message;
    // 	$response['statusCode']=$statusCode;
    // 	echo json_encode($response);
    // }
    
    
       // Order ID
    public function generateOrderID($user_id=NULL)
     {   
         $current_timestamp_by_mktime = mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
         $ord_id="ORDCAB-".$user_id."~".$current_timestamp_by_mktime ;  
    
         $lenth = strlen($ord_id);
         if($lenth >= 30){
             $ord_id = substr($ord_id,0,29);
         }
         
        return $ord_id;
    
     }
     
    
      
    //tarnasction ID
    public function generateTransID()
    {
        $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $tran_id = "TRANSCAB-".substr($str_result,0,1)."SEND".rand(10,99999999999) ;
        
        $lenth = strlen($tran_id);
        
        if($lenth >= 30){
            $tran_id = substr($tran_id,0,29);
        }
        
        return $tran_id;
    }
    
    public function payment_verify()
    {
        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);

        $orderno=$data->orderno;
        $tarns_id=$data->tarns_id;
        $TXN_AMOUNT=$data->TXN_AMOUNT;
        $user_id=$data->user_id;
       

        if(isset($orderno) && isset($tarns_id) && isset($TXN_AMOUNT) && isset($user_id))
        {
            $check_payment=$this->db->query("SELECT * FROM tbl_user_trans WHERE order_id='$orderno' AND trans_amount='$TXN_AMOUNT' AND trans_id='$tarns_id' AND user_id='$user_id' AND status=0")->row_array();

            if(!empty($check_payment))
            {
                $response['payment_verify']=true;
                
                // $this->db->query("UPDATE tbl_user_trans SET status=1 WHERE order_id='$orderno' AND trans_amount='$TXN_AMOUNT' AND trans_id='$tarns_id' AND user_id='$user_id' AND status=0");
                
                // $this->db->query("UPDATE tbl_booking SET payment_status=1 WHERE book_id='".$check_payment['booking_id']."'");
            }
            else
            {
                $response['payment_verify']=false;
            }

            $status='success';
            $message='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 Bookcab()
    {
        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);
        
        $send_request_id=$data->send_request_id;
		$user_id=$data->user_id;
		$added_by_web=$data->added_by_web;
		$booking_id=$data->booking_id;
		$paymenttype=$data->paymenttype;
		$booking_type=$data->booking_type;
		$order_id=$data->order_id;
        $tarns_id = $data->tarns_id;
        $TXN_AMOUNT=$data->TXN_AMOUNT;
        $conv_charge=$data->conv_charge;
        $phone=$data->user_phone;
        
         $round_amnt = round($TXN_AMOUNT)  ;
         $round_conv = round($conv_charge) ;
         
         
          $total_amnt = $round_amnt +  $round_conv ; 
         
        
        
        if($send_request_id && $user_id && $booking_id && $paymenttype && $order_id && $TXN_AMOUNT && $phone && $booking_type)
        {
            
            if($paymenttype=='online')
            {
                $check_payment=$this->db->query("SELECT * FROM tbl_user_trans 
                WHERE order_id='$order_id' AND trans_amount= $total_amnt  
                 AND user_id='$user_id' AND status=0")->row_array();
                
            }
            else
            {
                $check_payment=array('paymode'=>'other');
            }
               
              
            if(!empty($check_payment))    
            {
                $qry="SELECT * FROM tbl_userwise_cabrequest WHERE id='$send_request_id' AND status=1 AND is_latest_request=1";
                $row=$this->db->query($qry)->row_array();
                
                if(!empty($row))
                {
                    
                    if($paymenttype=='online')
                    {
                       $pay_mode='online';
                       $payment_status=1;
                    }
                    else if($paymenttype=='wallet')
                    {
                       $pay_mode='wallet';
                       $payment_status=1;
                    }
                    else if($paymenttype=='razorpay')
                    {
                       $pay_mode='razorpay';
                       $payment_status=1;
                    }
                    else if($paymenttype=='phonepay')
                    {
                       $pay_mode='phonepay';
                       $payment_status=1;
                    }
                    else
                    {
                       $pay_mode='COD';
                       $payment_status=0;
                    }
                   
                    $data=array(
                        'book_id'=>$booking_id,
                        'order_id'=>$order_id,
                        'trans_id'=>$tarns_id,
                        'user_id'=>$user_id,
                        'booking_type'=>$booking_type,
                        'driver_id'=>$row['driver_id'],
                        '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'],
                        'type_id'=>$row['type_id'],
                        'driver_away'=>$row['driver_away'],
                        'send_request_id'=>$row['id'],
                        'user_journey_distance'=>round($row['user_journey_distance'],2),
                        'per_km_fare'=>$row['per_km_fare'],
                        'total_fare'=>round($row['per_km_fare']*$row['user_journey_distance']),
                        'grand_total'=>$TXN_AMOUNT,
                        'conv_charge'=>$conv_charge,
                        'ride_status'=>0,
                        'payment_status'=>$payment_status,
                        'paymenttype'=>$pay_mode,
                        'entry_date'=>date('Y-m-d H:i:s'),
                        'added_by_web'=>$added_by_web,
                    );
                    
                    $this->db->insert('tbl_booking',$data);
                    
                    
                   if($paymenttype=='online')
                   {
                        $this->db->query("UPDATE tbl_user_trans SET status=1 WHERE order_id='$order_id' AND trans_amount='$TXN_AMOUNT' AND user_id='$user_id' AND status=0");
                   }
                   else if($paymenttype=='wallet')
                   {
                       
                       $service_url = WALLETAPIURL; //production
                       
                       $payload=array(
                           'user_phone'=>$phone,
                           'order_id'=>$order_id,
                           'trans_id'=>$tarns_id,
                           'credit'=>0,
                           'debit'=>$TXN_AMOUNT,
                           'added_by_web'=>$added_by_web,
                           'service_type'=>'Cab',
                           'description'=>"Debit Rs.".$TXN_AMOUNT." of book Cab. BOOKING ID-".$booking_id,
                           );
                       
                       
                        $ch = curl_init();
                        $headers  = [
                                    'Content-Type: application/json'
                                ];
                        
                        curl_setopt($ch, CURLOPT_URL,$service_url);
                        curl_setopt($ch, CURLOPT_POST, 1);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));       
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                        $wallet_summary = curl_exec ($ch);
                       
                   }
                   
                    //send notification to driver
                    $driver_data=$this->db->query("SELECT f_token_app FROM tbl_driver WHERE id='".$row['driver_id']."'")->row_array();
                    
                    if($driver_data['f_token_app'])
    	            {
        	            //send notification
        	            $body="Ride has been booked successfully by user. Booking ID-".$booking_id;
        	            $title="Book Ride";
        	            sendNotificationFlutter($driver_data['f_token_app'],$body,$title);
    	            }
                   
                    $response['booking_id']=$booking_id;
                    $status='success';
                    $message='Your cab has been booked successfully';
                    $statusCode=200;
                }
                else
                {
                    $status='error';
                    $message='Something went wrong. Your request not found';
                    $statusCode=400;
                }
            }
            else
            {
                 $status='error';
                $message='Something went wrong your payment not verified..!';
                $statusCode=400;  
            }
            
        }
        else
        {
            $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;  
        }
        $response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
    
    public function delete_droploc_history()
    {
        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);
        
        $autoid=$data->autoid;
        
        if($autoid)
        {
            $this->db->where('id',$autoid);
            $st=$this->db->delete('tbl_drop_location_history');
            
            if($st) {  
                $status = 'success';
                $message = 'Record deleted successfully';
                $statusCode = 200;
            } else {
                $status = 'error';
                $message = 'Failed to delete the record';
                $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 conv_charge()
    {
        
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
    $method = $_SERVER['REQUEST_METHOD'];
    
    
    if($method == 'POST'){
        
     $qry = "SELECT * FROM tbl_conv_charge where status = 0 ";
      $result = $this->db->query($qry)->row_array();
      
       $qr = "SELECT * FROM tbl_cod_sts  ";
      $rt = $this->db->query($qr)->row_array();
        if(!empty($result) || !empty($rt)){
           $response['status'] =200;
           $response['conv_charge']=$result['amt'];
        $response['cod_sts']=$rt['status']; 
        $response['online_sts']=true; 
        $response['razorpay_sts']=true; 
        $response['message']=  'Success'; 
        
          
    }else{
        
    $response = array('status' => 400,'message' => ' DATA not available  .');  
    
    
    }
    
    	echo json_encode($response);
            
        }
}
    
    
    
    public function CancleBookedCab()
    {
        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;
    	$reason=$data->reason;
    	$phone=$data->user_phone;
    	if($booking_id && $reason && $phone)
    	{
    	    $qry="SELECT * FROM tbl_booking WHERE book_id='$booking_id'";
            $row=$this->db->query($qry)->row_array();
            
            if(!empty($row))
            {
	            
	            if($row['ride_status']==0)
	            {
            	    $data=array('ride_status'=>3,'is_cancle'=>1,'cancle_reason'=>$reason,'cancle_date'=>date('Y-m-d H:i:s'));
            	    $this->db->where('book_id',$booking_id);
            	    $this->db->update('tbl_booking',$data);
    	            
    	            if($row['payment_status']==1)
    	            {
    	                $service_url = WALLETAPIURL; //production
                           
                           $payload=array(
                               'user_phone'=>$phone,
                               'order_id'=>$row['order_id'],
                               'trans_id'=>$row['trans_id'],
                               'credit'=>$row['grand_total'],
                               'debit'=>0,
                               'added_by_web'=>$row['added_by_web'],
                               'service_type'=>'Cab',
                               'description'=>"Credit Rs.".$row['grand_total']." of cancelled booking by user. BOOKING ID-".$booking_id,
                               );
                           
                           
                            $ch = curl_init();
                            $headers  = [
                                        'Content-Type: application/json'
                                    ];
                            
                            curl_setopt($ch, CURLOPT_URL,$service_url);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));       
                            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                            $wallet_summary = curl_exec ($ch);
    	            }
    	            
    	            
    	            $qry="SELECT f_token_app FROM tbl_driver WHERE id='".$row['driver_id']."'";
                    $driver_row=$this->db->query($qry)->row_array();
    	            
    	            if(!empty($driver_row))
    	            {
    	                $body="Your accepted request has been booking successfully BOOKING ID-".$booking_id." Please start ride";
        	            $title="Accepted request has been book by user ";
        	            sendNotificationFlutter($driver_row['f_token_app'],$body,$title);
    	            }
    	            
    	            
    	            $status='success';
                    $message='Cab has been cancelled successfully';
                    $statusCode=200;  
	            }
	            else
	            {
	                if($row['ride_status']==1)
	                {
	                     $status='error';
                        $message='You can not cancel ride becuase it already started';
                        $statusCode=400;  
	                }
	                else
	                {
	                    $status='error';
                        $message='You can not cancel ride.';
                        $statusCode=400;  
	                }
	            }
            }
    	    else
    	    {
    	        $status='success';
                $message='Booking Details not found';
                $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 trip_history()
    {
        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;
        $pageno= $data->pageno;
        
        if($user_id)
        {
             $limit = 10;  
                if($data->pageno)
                { 
                    $pn  = $data->pageno; 
                } 
                else { 
                    $pn=1; 
                };  
                
            $start_from = ($pn-1) * $limit;
            
             $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(b.entry_date,'%Y-%m-%d') BETWEEN '$startdate' AND '$enddate'";
            }
            
            $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
            FROM tbl_booking b
            INNER JOIN tbl_vehicletype vt ON vt.id=b.type_id WHERE b.user_id='$user_id' $datefilter_qry";
            
            $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]['pickup_address']=$row['pickup_address'];
                    $response['list'][$i]['drop_address']=$row['drop_address'];
                    $response['list'][$i]['vehicle']=$row['vehicle_name'];
                    $response['list'][$i]['vehicle_image']=base_url().$row['vehicle_image'];
                    $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'];
                    
                    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'];
                    $response['list'][$i]['is_arrived_destination']= $row['is_arrived_destination'];
                    $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;
            }
            else
            {
                $response['list']=[];
                $message='Data Not found';
                 $status='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 trip_history_details()
    {
        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 b.*,DATE_FORMAT(b.entry_date,'%d/%m/%Y %H:%i %p') AS entrydate,
            vt.name as vehicle_name,vt.image as vehicle_image ,dr.mobile_no, dr.driver_name ,dr.driver_profile_pic,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_driver dr ON dr.id = b.driver_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['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['driver_name']=$row['driver_name'];
                $response['driver_img']= base_url().$row['driver_profile_pic'];
                
                
                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['deliveryboy_mobileno']=$row['mobile_no'];
                $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['is_arrived_destination']= $row['is_arrived_destination'];
                $response['vehical_number']= $row['number'];
                $message='Data found';
                $status='success';
                $statusCode=200;
            }
            else
            {
                
                $message='Data Not found';
                 $status='success';
                 $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 drop_location_history()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') 
        {
            $json = $this->security->xss_clean(file_get_contents('php://input'));
            $data = json_decode($json);
            
            $drop_lat=$data->drop_lat;
            $drop_long= $data->drop_long;
            $drop_address= $data->drop_address; 
            $booking_type= $data->booking_type;
            
            if($drop_lat && $drop_long  && $booking_type && $drop_address)
            {
                
                $data=array(
                     'drop_lat'=>$drop_lat,
                     'drop_long'=>$drop_long,
                     'drop_address'=>$drop_address,
                     'booking_type'=>$booking_type,
                     'created_at'=>date('Y-m-d H:i:s'),
                    );
                    
                $this->db->insert('tbl_drop_location_history',$data);
                
                $insert_id = $this->db->insert_id();
                
                // $sql="SELECT * FROM tbl_drop_location_history ORDER BY id DESC";
                // $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]['drop_lat']=$row['drop_lat'];
                //         $response['list'][$i]['drop_long']=$row['drop_long'];
                //         $response['list'][$i]['drop_address']=$row['drop_address'];
                //         $response['list'][$i]['booking_type']=$row['booking_type'];
                //         $i++;
                //     }
                    
                    
                // }
                
                 $status='success';
                $message='Data Saved';
                $statusCode=200;
                
               
            }
            else
            {
                $status='error';
                $message='Please fill all required fields';
                $statusCode=400;
            }
        
        
        }
        else if($_SERVER['REQUEST_METHOD'] === 'GET')
        {
            
                $sql="SELECT * FROM tbl_drop_location_history ORDER BY id DESC";
                $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]['drop_lat']=$row['drop_lat'];
                        $response['list'][$i]['drop_long']=$row['drop_long'];
                        $response['list'][$i]['drop_address']=$row['drop_address'];
                        $response['list'][$i]['booking_type']=$row['booking_type'];
                        $response['list'][$i]['created_at']=$row['created_at'];
                        $i++;
                    }
                    
                    
                }
                
                $status='success';
                $message='Data found';
                $statusCode=200;
            
        }
        else
        {
                $status='error';
                $message='Not a valid request';
                $statusCode=400;
            
        }
        
        
        
        
        $response['status']=$status;
        $response['statusCode']=$statusCode;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    
    public function pre_booking_available()
    {
        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);
        
		$pickup_lat=$data->pickup_lat;
		$pickup_long=$data->pickup_long;
	    $drop_lat=$data->drop_lat;
		$drop_long=$data->drop_long;
// 		$vehicle_type_id=$data->vehicle_type_id;
		$user_id=$data->user_id;
		$added_by_web=$data->added_by_web;
		$pickup_address=$data->pickup_address;
		$drop_address=$data->drop_address;
		$selectdate=$data->selectdate;
		$selectedtime=$data->selectedtime;
		$booking_type=$data->booking_type;
		
		
		if($pickup_lat && $pickup_long && $drop_lat && $drop_long && $selectdate && $selectedtime 
		&& $pickup_address && $drop_address)
		{
		    $this->db->where('user_id',$user_id);
		    $this->db->update('tbl_userwise_cabrequest',array('is_latest_request'=>0));
		    
		    
		    $qry="SELECT tmp.*,dmt.type_id,f.per_km,d.f_token_app,TIMESTAMPDIFF(MINUTE,d.accepted_request_time,NOW()) as driverreq_accepted_time FROM(SELECT driver_id,
    	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
            cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
     	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
     	    INNER JOIN tbl_fare f ON f.vehicle_type=dmt.type_id
     	    WHERE d.is_online=1 AND d.status=1 
     	    AND tmp.distance <= ".DEFAULT_NEARBY_DRIVER_AREA." ORDER BY tmp.distance ASC";
		    
		  //  $qry="SELECT tmp.*,dmt.type_id,f.per_km,d.f_token_app,TIMESTAMPDIFF(MINUTE,d.accepted_request_time,NOW()) as driverreq_accepted_time FROM(SELECT driver_id,
    // 	    round(( 6371 * acos( cos( radians(round($pickup_lat,2)) ) * cos( radians(curr_lat) ) *
    //         cos( radians(curr_long) - radians(round($pickup_long,2)) ) + sin( radians(round($pickup_lat,2)) ) * sin( radians(curr_lat) ) ) )) AS distance
    // 	    FROM tbl_driver_currentLocation d GROUP BY driver_id) AS tmp
    // 	    INNER JOIN tbl_driver d ON d.id=tmp.driver_id
    // 	    INNER JOIN tbl_vehicle tv ON tv.driver_id=d.id
    //  	    INNER JOIN tbl_map_vehicletype dmt ON dmt.vehicle_id=tv.id
    //  	    INNER JOIN tbl_fare f ON f.vehicle_type=dmt.type_id
    //  	    WHERE d.is_online=1 AND d.status=1 
    //  	    AND dmt.type_id=$vehicle_type_id 
    //  	    AND tmp.distance <= ".DEFAULT_NEARBY_DRIVER_AREA." ORDER BY tmp.distance ASC";
	        
		    $result=$this->db->query($qry)->result_array();
		    
		    if(!empty($result))
		    {
		        $total_distance=$this->distance($pickup_lat,$pickup_long,$drop_lat,$drop_long,'K');
    	        $request_id='REQ-'.sprintf("%08d", mt_rand(0, 999999));
    	        
    	        
		        foreach($result as $row)
    	        {
    	           // if($row['driverreq_accepted_time'] > REQUESTEXPIRE_TIME)
    	           // {
        	            $data=array(
        	                 'req_id'=>$request_id,
        	                 'pickup_address'=>$pickup_address,
        	                 'drop_address'=>$drop_address,
        	                 'pickup_lat'=>$pickup_lat,
        	                 'pickup_long'=>$pickup_long,
        	                 'drop_lat'=>$drop_lat,
        	                 'drop_long'=>$drop_long,
        	                 'user_id'=>$user_id,
        	                 'driver_id'=>$row['driver_id'],
        	                 'type_id'=>$row['type_id'],
        	                 'driver_away'=>$row['distance'],
        	                 'user_journey_distance'=>round($total_distance,2),
        	                 'per_km_fare'=>$row['per_km'],
        	                 'entry_date'=>date('Y-m-d H:i:s'),
        	                 'added_by_web'=>$added_by_web,
                            'booking_type'=>$booking_type,
                            'selectedtime'=>$selectedtime,
                            'selectedtime'=>$selectedtime,
        	                );
        	            $this->db->insert('tbl_userwise_cabrequest',$data);
        	            
        	           
        	            if($row['f_token_app'])
        	            {
            	            //send notification
            	            $body="You have received a new ride request of pickup locaion ".$pickup_address." from a user .";
            	            $title="New Ride Request";
            	            sendNotificationFlutter($row['f_token_app'],$body,$title);
        	            }
        	            
        	           
    	           // }
    	        }
    	        
    	        
    	       // $response['vehicle_type_id']=$vehicle_type_id;
    	        $status='success';
                $message='Request has been send successfully';
                $statusCode=200;
                
                
                
                
		    }
		    else
		    {
		      //  $status='error';
        //         $message='No any driver found near by you.';
        //         $statusCode=400;    
                
               $status='success';
                $message='Request has been send successfully';
                $statusCode=200;   
                
		    }
		}
		
		else
		{
		    $status='error';
            $message='Please fill in all required fields.';
            $statusCode=400;        
           
		}
		$response['status']=$status;
		$response['message']=$message;
		$response['statusCode']=$statusCode;
		echo json_encode($response);
    }
    
     
    
    
    public function afterpaynow_online()
    {
        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;
        $conv_charge=$data->conv_charge;
        
        
    	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'])+$conv_charge,2); 
    	            $total_payble=round($total_payble+$row['total_wait_charge']);
    	        }
                else
                {
                    $total_payble=round($row['total_wait_charge']);
                    $conv_charge=0; 
                }
                
              
                $trans_id=$this->generateTransID();
                
                
                $login_user=array(
    	            'booking_id'=>$row['book_id'],
                    'user_id'=>$row['user_id'],
                    'order_id'=>$row['order_id'],
                    'trans_id'=>$trans_id,
                    'payment_type'=>'online',
                    'trans_amount'=>$total_payble,
                    'conv_charge'=>$conv_charge,
                    'added_by_web'=>$row['added_by_web'],
                    'ip'=>$_SERVER["REMOTE_ADDR"],
                    'entry_date'=>date('Y-m-d H:i:s'),
                );
                
                $this->db->insert('tbl_user_trans',$login_user);
               
                $response['order_id']=$row['order_id'];
                $response['MID']="";
                $response['WEB_CALLBACK_URL']="";
                
                $response['CONV_CHARGE']=(int)$conv_charge;
                $response['MAIN_AMOUNT']=$total_payble-$conv_charge;
                $response['TXN_AMOUNT']=$total_payble;
                $response['CUST_ID']=$trans_id;
                $response['booking_id']=$row['book_id'];
                $response['payment_type']='online';
    
                $status='success';
                $message='success';
                $statusCode=200;
    	    }
    	    else
    	    {
    	        $status='error';
                $message='This booking not valid for payment';
                $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 after_onlinepayment_verify()
    {
        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);

        $orderno=$data->orderno;
        $tarns_id=$data->tarns_id;
        $TXN_AMOUNT=$data->TXN_AMOUNT;
        $user_id=$data->user_id;
       

        if(isset($orderno) && isset($tarns_id) && isset($TXN_AMOUNT) && isset($user_id))
        {
            $check_payment=$this->db->query("SELECT * FROM tbl_user_trans WHERE order_id='$orderno' AND trans_amount='$TXN_AMOUNT' AND trans_id='$tarns_id' AND user_id='$user_id' AND status=0")->row_array();

            if(!empty($check_payment))
            {
                $response['payment_verify']=true;
                
                // $this->db->query("UPDATE tbl_user_trans SET status=1 WHERE order_id='$orderno' AND trans_amount='$TXN_AMOUNT' AND trans_id='$tarns_id' AND user_id='$user_id' AND status=0");
                
                // $this->db->query("UPDATE tbl_booking SET payment_status=1 WHERE book_id='".$check_payment['booking_id']."'");
                
                $qry="SELECT * FROM tbl_booking WHERE order_id='$orderno'";
                $row=$this->db->query($qry)->row_array();
                
                if(!empty($row))
                {
        	        $total_payble=round($TXN_AMOUNT+$row['total_wait_charge']);
                    
                    $data_update=array(
                       'final_grandtotal'=>$total_payble,
                       'payment_status'=>1,
                       'post_paymenttype'=>'online',
                       'post_payment_status'=>1,
                      );
                      
                    $this->db->where('book_id',$row['book_id']);  
                    $this->db->update('tbl_booking',$data_update);
                    
                    
                    $qry="SELECT f_token_app FROM tbl_driver WHERE id='".$row['driver_id']."'";
                    $driver_row=$this->db->query($qry)->row_array();
    	            
    	            if(!empty($driver_row))
    	            {
    	                $body="Rs.".$total_payble." Pay using online payment mode by user. Booking ID-".$row['book_id'];
        	            $title="Payment Done";
        	            sendNotificationFlutter($driver_row['f_token_app'],$body,$title);
    	            }
        	            
            
                }
            }
            else
            {
                $response['payment_verify']=false;
            }

            $status='success';
            $message='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 afterpaynow_wallet()
    {
        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 b.*,u.mobile_no FROM tbl_booking b
    	    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))
            {
                
                 $total_payble=round(($row['per_km_fare']*$row['user_journey_distance']),2); 
                 
                if($row['payment_status']==0)
    	        {
    	           
    	            $total_payble=round($total_payble+$row['total_wait_charge']);
    	            
    	            $final_grandtotal=$total_payble;
    	            
    	            $description="Debit Rs.".$total_payble." of book Cab. BOOKING ID-".$booking_id;
    	        }
                else
                {
                    $final_grandtotal=round($total_payble+$row['total_wait_charge']);
                    
                    $total_payble=round($row['total_wait_charge']);
                   
                    $description="Debit Rs.".$total_payble." of book Cab waiting charge. BOOKING ID-".$booking_id;
                }
                
    	         
                $data_update=array(
                   'final_grandtotal'=>$final_grandtotal,
                   'payment_status'=>1,
                   'post_paymenttype'=>'Wallet',
                   'post_payment_status'=>1,
                  );
                  
                $this->db->where('book_id',$booking_id);  
                $this->db->update('tbl_booking',$data_update);
                
                
                if($total_payble > 0)
                {
                
                    $service_url = WALLETAPIURL; //production
                           
                    $payload=array(
                       'user_phone'=>$row['mobile_no'],
                       'order_id'=>$row['order_id'],
                       'trans_id'=>'',
                       'credit'=>0,
                       'debit'=>$total_payble,
                       'added_by_web'=>$row['added_by_web'],
                       'service_type'=>'Cab',
                       'description'=>$description,
                       );
                   
                   
                    $ch = curl_init();
                    $headers  = [
                                'Content-Type: application/json'
                            ];
                    
                    curl_setopt($ch, CURLOPT_URL,$service_url);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));       
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    $wallet_summary = curl_exec ($ch);
                    
                    
                    $qry="SELECT f_token_app FROM tbl_driver WHERE id='".$row['driver_id']."'";
                    $driver_row=$this->db->query($qry)->row_array();
    	            
    	            if(!empty($driver_row))
    	            {
    	                $body="Rs.".$total_payble." Pay using wallet by user. Booking ID-".$row['book_id'];
        	            $title="Payment Done";
        	            sendNotificationFlutter($driver_row['f_token_app'],$body,$title);
    	            }
                }
                $message='Payment has been successfully deduct from the wallet ';
                $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 afterpaynow_razorpay()
    {
        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;
        //$conv_charge=$data->conv_charge;
        
        
    	if($booking_id)
    	{
    	    $qry="SELECT * FROM tbl_booking WHERE book_id='$booking_id'";
            $row=$this->db->query($qry)->row_array();
            
            if(!empty($row))
            {
                $conv_charge=0; 
                
    	        if($row['payment_status']==0)
    	        {
    	            $total_payble=round(($row['per_km_fare']*$row['user_journey_distance']),2); 
    	            $total_payble=round($total_payble+$row['total_wait_charge']);
    	        }
                else
                {
                    $total_payble=round($row['total_wait_charge']);
                    
                }
                
                
                if($total_payble > 0)
                {
               
                    $keyId = RZ_KEY;
                    $keySecret = RZ_SECRETKEY;
                    
                    $orderData = [
                        'amount'          => (int)$total_payble*100, // Amount in paise = 50000 paise = INR 500
                        'currency'        => 'INR',
                    ];
                    
                    $jsonData = json_encode($orderData);
                    
                    // Initialize cURL
                    $ch = curl_init();
                    
                    curl_setopt($ch, CURLOPT_URL, 'https://api.razorpay.com/v1/orders');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, [
                        'Content-Type: application/json',
                        'Content-Length: ' . strlen($jsonData)
                    ]);
                    curl_setopt($ch, CURLOPT_USERPWD, $keyId . ':' . $keySecret);
                    
                    $pay_response = curl_exec($ch);
                    
                    if (curl_errno($ch)) {
                       $order_id='';
                    } else {
                        $responseData = json_decode($pay_response, true);
                       
                        if(isset($responseData['id']))
                        {
                            $order_id=$responseData['id'];
                        }
                        
                    }
                    
                    curl_close($ch);
                   
                    $response['order_id']=$row['order_id'];
                    $response['rz_order_id']=$order_id;
                    $response['MID']="";
                    $response['WEB_CALLBACK_URL']="";
                    
                    $response['CONV_CHARGE']=(int)$conv_charge;
                    $response['MAIN_AMOUNT']=$total_payble-$conv_charge;
                    $response['TXN_AMOUNT']=$total_payble;
                    $response['CUST_ID']='';
                    $response['booking_id']=$row['book_id'];
                    $response['payment_type']='online';
        
                    $status='success';
                    $message='success';
                    $statusCode=200;
                }
                else
                {
                    $status='error';
                    $message='Payment completed';
                    $statusCode=400;  
                }
    	    }
    	    else
    	    {
    	        $status='error';
                $message='This booking not valid for payment';
                $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 after_razorpay_verify()
    {
        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);

        $orderno=$data->rz_order_id;
        $book_id=$data->booking_id;
        // $tarns_id=$data->tarns_id;
        $TXN_AMOUNT=$data->TXN_AMOUNT;
        //$user_id=$data->user_id;
       

        if(isset($orderno) && isset($book_id) && isset($TXN_AMOUNT))
        {
            $qry="SELECT * FROM tbl_booking WHERE book_id='$book_id'";
            $row=$this->db->query($qry)->row_array();
            
            if(!empty($row))
            {
    	        $total_payble=round($TXN_AMOUNT+$row['total_wait_charge']);
                
                $data_update=array(
                   'final_grandtotal'=>$total_payble,
                   'rz_order_id'=>$orderno,
                   'payment_status'=>1,
                   'post_paymenttype'=>'razorpay',
                   'post_payment_status'=>1,
                  );
                  
                $this->db->where('book_id',$row['book_id']);  
                $this->db->update('tbl_booking',$data_update);
                
                
                $qry="SELECT f_token_app FROM tbl_driver WHERE id='".$row['driver_id']."'";
                $driver_row=$this->db->query($qry)->row_array();
	            
	            if(!empty($driver_row))
	            {
	                $body="Rs.".$total_payble." Pay using razorpay payment mode by user. Booking ID-".$row['book_id'];
    	            $title="Payment Done";
    	            sendNotificationFlutter($driver_row['f_token_app'],$body,$title);
	            }
    	            
        
            }

            $status='success';
            $message='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 get_theme()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status='error';
		$message='Invalid Request';
        $statusCode=400;
        
        
         $qry="SELECT th.*,ic_th.*,ap_th.*,dt_th.*,gd.*,textth.*
         
            FROM themes th
            INNER JOIN icon_theme ic_th ON ic_th.theme_id=th.id
            
            INNER JOIN app_bar_theme ap_th ON ap_th.theme_id=th.id
            
            INNER JOIN  data_table_theme dt_th ON dt_th.theme_id=th.id
            
            INNER JOIN  gradient gd ON gd.theme_id=th.id
            
            INNER JOIN  text_theme textth ON textth.theme_id=th.id
            
              ORDER BY th.id ASC";
              
            $row=$this->db->query($qry)->result_array();
            
            // echo "<pre>";
            // print_r($row);
            // die;
        
            
            if(!empty($row))
            {
                
                    $response = [];

                    foreach ($row as $data) 
                    {
                        
                        
                        $sections = explode(',', $data['section_name']);
                        $font_weights = explode(',', $data['font_weight']); // Assuming font weights are dynamic and in the same format
                        $textTheme = [];
                        
                        
                        foreach ($sections as $index => $section) 
                        {
                            $fontSizeMap = [
                                'displayLarge' => 24,
                                'displayMedium' => 20,
                                'displaySmall' => 12,
                                'titleLarge' => 24,
                                'titleMedium' => 18,
                                'titleSmall' => 12,
                                'bodyLarge' => 18,
                                'bodyMedium' => 13,
                                'bodySmall' => 16
                            ];
                            
                            $textTheme[$section] = [
                                'fontFamily' => $data['font_family'],
                                'fontWeight' => isset($font_weights[$index]) ? $font_weights[$index] : 'normal', // Use normal if not found
                                'fontSize' => isset($fontSizeMap[$section]) ? $fontSizeMap[$section] : 16, // Default to 16 if not mapped
                                'color' => $data['text_theme_color'] // Use color from your data array
                            ];
                        }
                        
                        
                        $response['light_theme'] = [
                            "primaryColor" => $data['primary_color'],
                            "primaryColorDark" => $data['primary_color_dark'],
                            "primaryColorLight" => $data['primary_color_light'],
                            "cardColor" => $data['card_color'],
        
                        // DataTableTheme
                        "dataTableTheme" => [
                            "headingTextStyle" => [
                                "fontFamily" => $data['font_family'], 
                                "color" => $data['heading_color'], 
                                "fontSize" => $data['font_size']
                            ],
                            "dividerThickness" => $data['divider_thickness'],
                            "headingRowColor" => $data['heading_row_color']
                        ],
        
                        // AppBarTheme
                        "appBarTheme" => [
                            "backgroundColor" => $data['background_color'],
                            "elevation" => $data['elevation'],
                            "shape" => [
                                "borderRadius" => [
                                    "bottomLeft" => $data['border_radius_bottom_left'],
                                    "bottomRight" => $data['border_radius_bottom_right']
                                ]
                            ],
                            "shadowColor" => $data['shadow_color']
                        ],
                        
                        // TextTheme
                        "textTheme" => $textTheme,
        
                         // IconTheme
                        "iconTheme" => [
                            "color" => $data['icon_theme_color']
                        ],
                        
                        // Gradient
                        // "gradient" => [
                        //     "start_color" => $data['start_color'],
                        //     "center_color" => $data['center_color'],
                        //     "end_color" => $data['end_color']
                        // ]
                        
                    ];
                    
                     $response['dark_theme'] = new stdClass();  // Empty object
                    $response['book_now'] = new stdClass();    // Empty object
                    $response['pre_booking'] = new stdClass(); // Empty object
                    $response['rental'] = new stdClass();      // Empty object
                     
                    
                }
        
            }
            else
            {
                $response['status']=$status;
                $response['statusCode']=$statusCode;
        		$response['message']='No Data is Found';
            }

            
        
        
        
		echo json_encode($response,JSON_PRETTY_PRINT);
    }
    
    
    
    public function notification_history()
    {
        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);
        
        if($_SERVER['REQUEST_METHOD'] === 'POST')
        {
        
            $user_id=$data->user_id;
            $paymenttype=$data->paymenttype;
            $type=$data->type;
            $pageno= $data->pageno;
            
            if($user_id)
            {
                    $limit = 10;  
                    if($data->pageno)
                    { 
                        $pn  = $data->pageno; 
                    } 
                    else { 
                        $pn=1; 
                    };  
                    
                    $start_from = ($pn-1) * $limit;
                    
                if($type=='search_payment')
                {
                    $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.user_id=b.user_id 
                    INNER JOIN tbl_user tu ON tu.id=b.user_id 
                    WHERE b.user_id='$user_id' AND b.paymenttype='$paymenttype' AND b.payment_status='1' GROUP BY b.book_id";
                    
                }
                if($type=='cabrequest')
                {
                  $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.user_id=b.user_id 
                    INNER JOIN tbl_user tu ON tu.id=b.user_id 
                    WHERE tbc.user_id='$user_id'  AND tbc.status='3' GROUP BY b.book_id";   
                }
                
                if($type=='ridecomplete')
                {
                  $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.user_id=b.user_id 
                    INNER JOIN tbl_user tu ON tu.id=b.user_id 
                    WHERE b.user_id='$user_id'  AND b.ride_status='2' 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;
                }
                else
                {
                     $response['list']=[];
                    $message='Data Not found';
                     $status='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);
    }
    
    
    
    
}

?>