<?php

header('Access-Control-Allow-Origin: *'); //for allow any domain, insecure   
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); //method allowed  
header('Access-Control-Allow-Headers: *'); //for allow any headers, insecure

//header("Access-Control-Allow-Origin: *");
//header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
//header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

use Restserver\Libraries\REST_Controller;
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

class Api extends REST_Controller { 


	function __construct()
	{
		parent::__construct();
		$this->load->database();
		$this->load->model('api_model');
		$this->load->model('geofence_model');
		$this->load->model('customer_model');
		$this->load->model('trips_model');
		$this->load->model('drivers_model');
		$this->load->model('comman_model');  
		$this->load->model('vehicle_model');      
        // $this->load->library('bcrypt');
		date_default_timezone_set('Asia/Kolkata'); 


	}

	public function index_get() { 
		$write_content = var_export($_GET, true);
		file_put_contents("myloggets.php", $write_content);
	}
	public function check_token($token){
		$error='';
		$data = array("token"=>$token);
		$cust=$this->comman_model->get_data_where('customers',$data);
		if($cust){
			$response='';
		}else{
			$driver_info=$this->comman_model->get_data_where('drivers',$data);
			if($driver_info){
				$response='';
			}else{
				$error='Invalid token';
				goto end;
			}
		}
		end:
		if($error !="")
		{
			$response = ["status"=>0,"message"=>$error];
			echo json_encode($response);
			exit();
		}
	}

    public function index_post()   //Get GPS feed in device
    { 
    	if(isset($_GET)) {
    		$id = isset($_GET['id']) ? $_GET['id'] : ''; 
    		$checklogin = $this->api_model->checkgps_auth($id);   
    		if($checklogin) 
    		{ 
    			$v_id = $checklogin[0]['v_id'];
    			$v_id = $checklogin[0]['v_id'];
    			$lat = isset($_GET["lat"]) ? $_GET["lat"] : NULL;
    			$lon = isset($_GET["lon"]) ? $_GET["lon"] : NULL;
    			$timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : NULL;
    			$altitude = isset($_GET["altitude"]) ? $_GET["altitude"] : NULL;
    			$speed = isset($_GET["speed"]) ? $_GET["speed"] : NULL;
    			$bearing = isset($_GET["bearing"]) ? $_GET["bearing"] : NULL;
    			$accuracy = isset($_GET["accuracy"]) ? $_GET["accuracy"] : NULL;
    			$comment = isset($_GET["comment"]) ? $_GET["comment"] : NULL;
    			$postarray = array('v_id'=>$v_id,'latitude'=>$lat,'longitude'=>$lon,'time'=>date('Y-m-d h:i:s'),'altitude'=>$altitude,'speed'=>$speed,'bearing'=>$bearing,'accuracy'=>$accuracy,'comment'=>$comment);
    			$this->api_model->add_postion($postarray);
    			$this->checkgeofence($v_id,$lat,$lon);
    			$response = array('error'=>false,'message'=>['v_id' => $v_id]);
    			$this->set_response($response);
    		} 
    	} else{ 
    		$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : ''; 
    		$checklogin = $this->api_model->checkgps_auth($id);   
    		if($checklogin) 
    		{ 
    			echo $v_id = $checklogin[0]['v_id'];
    			$lat = isset($_REQUEST["lat"]) ? $_REQUEST["lat"] : NULL;
    			$lon = isset($_REQUEST["lon"]) ? $_REQUEST["lon"] : NULL;
    			$timestamp = isset($_REQUEST["timestamp"]) ? $_REQUEST["timestamp"] : NULL;
    			$altitude = isset($_REQUEST["altitude"]) ? $_REQUEST["altitude"] : NULL;
    			$speed = isset($_REQUEST["speed"]) ? $_REQUEST["speed"] : NULL;
    			$bearing = isset($_REQUEST["bearing"]) ? $_REQUEST["bearing"] : NULL;
    			$accuracy = isset($_REQUEST["accuracy"]) ? $_REQUEST["accuracy"] : NULL;
    			$comment = isset($_REQUEST["comment"]) ? $_REQUEST["comment"] : NULL;
    			$postarray = array('v_id'=>$v_id,'latitude'=>$lat,'longitude'=>$lon,'time'=>date('Y-m-d h:i:s'),'altitude'=>$altitude,'speed'=>$speed,'bearing'=>$bearing,'accuracy'=>$accuracy,'comment'=>$comment);
    			$this->api_model->add_postion($postarray);
    			$this->checkgeofence($v_id,$lat,$lon);
    			$response = array('error'=>false,'message'=>['v_id' => $v_id]);
    			$this->set_response($response);
    		} 
    	}
    }
    public function positions_post()     //Postion feed to front end   
    {
    	$this->db->select("*");
    	$this->db->from('positions');
    	$this->db->where('v_id',$this->post('t_vechicle'));
    	$this->db->where('date(time) >=', $this->post('fromdate'));
    	$this->db->where('date(time) <=', $this->post('todate'));
    	$query = $this->db->get();
    	$data = $query->result_array();
    	$distancefrom = reset($data);
    	$distanceto = end($data);
    	$totaldist = $this->totaldistance($distancefrom,$distanceto);
    	$returndata = array('status'=>1,'data'=>$data,'totaldist'=>$totaldist,'message'=>'data');
    	$this->set_response($returndata);
    }



    public function totaldistance($distancefrom,$distanceto,$earthRadius = 6371000)
    {
    	$latFrom = deg2rad($distancefrom['latitude']);
    	$lonFrom = deg2rad($distancefrom['longitude']);
    	$latTo = deg2rad($distanceto['latitude']);
    	$lonTo = deg2rad($distanceto['longitude']);
    	$latDelta = $latTo - $latFrom;
    	$lonDelta = $lonTo - $lonFrom;
    	$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
    	return $angle * $earthRadius;
    }
    public function currentpositions_get()     
    { 
    	$data = array();
    	$postions = array();
    	$this->db->select("p.*,v.v_name,v.v_type,v.v_color");
    	$this->db->from('positions p');
    	$this->db->join('vehicles v', 'v.v_id = p.v_id');
    	$this->db->where('v.v_is_active', 1);

    	if(isset($_GET['uname'])) { $this->db->where('v.v_api_username',$_GET['uname']);  }

    	if(isset($_GET['gr'])) { $this->db->where('v.v_group',$_GET['gr']);  }

    	if(isset($_GET['v_id'])) { $this->db->where('v.v_id',$_GET['v_id']);  }

    	$this->db->where('`id` IN (SELECT MAX(id) FROM positions GROUP BY `v_id`)', NULL, FALSE);
    	$query = $this->db->get();
    	$data = $query->result_array();
    	if(count($data)>=1) {
    		$resp = array('status'=>1,'data'=>$data);
    	} else {
    		$resp = array('status'=>0,'message'=>'No live GPS feed found');
    	}
    	$this->set_response($resp);
    }
    public function checkgeofence($vid,$lat,$log)     
    { 
    	$vgeofence = $this->geofence_model->getvechicle_geofence($vid);
    	if(!empty($vgeofence)) {
    		$points = array("$lat $log");
    		foreach($vgeofence as $geofencedata) {
    			$lastgeo = explode(" ,",$geofencedata['geo_area']);
    			$polygon = $geofencedata['geo_area'].$lastgeo[0];
    			$polygondata = explode(' , ',$polygon);
    			foreach($polygondata as $polygoncln) {
    				$geopolygondata[] = str_replace("," , ' ',$polygoncln); 
    			}
    			foreach($points as $key => $point) {
    				$geocheck = pointInPolygon($point, $geopolygondata,false);
    				if($geocheck=='outside' || $geocheck=='boundary' || $geocheck=='inside') {
                      //  $wharray = array('ge_v_id' => $vid, 'ge_geo_id' => $geofencedata['geo_id'], 'ge_event' => $geocheck,
                           // 'DATE(ge_timestamp)'=>date('Y-m-d'));
                        //$geofence_events = $this->db->select('*')->from('geofence_events')->where($wharray)->get()->result_array();
                       // echo $this->db->last_query();
                        //new query
    					$this->db->select("*");
    					$this->db->from('geofence_events');
    					$this->db->where('ge_v_id',$vid);    
    					$this->db->where('ge_geo_id',$geofencedata['geo_id']);                
    					$this->db->where('`ge_id` IN (SELECT MAX(ge_id) FROM geofence_events GROUP BY `ge_v_id`)', NULL, FALSE);
    					$query = $this->db->get(); 
    					$geofence_events = $query->row_array(); 
    					if($geofence_events['ge_event'] != $geocheck) {
    						$insertarray = array('ge_v_id'=>$vid,'ge_geo_id'=>$geofencedata['geo_id'],'ge_event'=>$geocheck,'ge_timestamp'=>
    							date('Y-m-d h:i:s'));
    						$this->db->insert('geofence_events',$insertarray);

                            //user notification
    						$data=array('v_id'=>$vid);
    						$vehicle_data=$this->comman_model->get_data_by_row('vehicles',$data);                            
    						$n_data=array(
    							"n_user_id"=>$vehicle_data['v_driver_id'],
    							"n_user_type"=>"driver",
    							"n_title"=>"Your Geo Fencing".$geocheck,
    							"n_message"=>"Your Geo Fencing".$geocheck,
    							"n_created_date"=> date('y-m-d'), 
    							"n_created_date_time"=> date('y-m-d H:i:s')
    						);
    						$this->comman_model->insert_record('all_notifications', $n_data); 

    					} 
    				}
    			}
    		}
    	}
    }

    public function customer_singup_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
         $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (($input_data->c_mobile) != "") {
        	$data['c_mobile']= $input_data->c_mobile;
        }else {
        	$error = "Mobile  No is required";
        	goto end;
        }if (($input_data->c_name) != "") {
        	$data['c_name']= $input_data->c_name;
        }else {
        	$error = "Customer Name is required";
        	goto end;
        }
        if (($input_data->c_email) != "") {
        	$data['c_email']= $input_data->c_email;
        } else {
        	$error = "Email Id is required";
        	goto end;
        }
        if (($input_data->device_token) != "") {
        	$device_token= $input_data->device_token;
        } else {
        	$error = "Device Token is required";
        	goto end;
        }
        end :
        if($error !="")
        {
        	$result = ["status"=>0,"message"=>$error];
        }
        else
        {


        	$where_array=array( "c_mobile"=>$data['c_mobile']);
        	$update_data=array("device_token"=>$device_token ,"c_email"=>$data['c_email'] ,"c_name"=>$data['c_name'] );
        	$update=$this->comman_model->update('customers', $where_array, $update_data); 
        	if($update){
        		$customer_info = $this->db->select('*')->from('customers')->where('c_mobile',$data['c_mobile'])->get()->result_array();
        		$result = ["status"=>1,"message"=>"Successfully Registered","customer_info"=>$customer_info];
        	}else{
        		$result = ["status"=>0,"message"=>"Unable to Register"];
        	}


        }
        echo json_encode($result);
        exit(); 
    }
    public function login_post(){ 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (($input_data->c_email) != "") {
    		$data['c_email']= $input_data->c_email;
    	} else {
    		$error = "Email Id is required";
    		goto end;
    	}
    	if (($input_data->c_pwd) != "") {
    		$data['c_pwd']= md5($input_data->c_pwd);
    	} else {
    		$error = "password is required";
    		goto end;
    	}
    	if (($input_data->device_token) != "") {
    		$device_token= $input_data->device_token;
    	} else {
    		$error = "Device Token is required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else
    	{
    		$this->db->where('c_email', $data['c_email']);
    		$this->db->where('c_pwd',$data['c_pwd']);
    		$query = $this->db->get("customers");
    		if ($query->num_rows() >= 1) {
    			$result = $query->row_array();

    			if($result['c_isactive']==0) {

    				$response = ["status"=>0,"message"=>"User not active.Please contact admin"];
    			} else {

				   /* $password = $data['c_pwd'];
				   $user_id=$data['c_email'];
				   $hash=$password.$user_id.rand();
				   $token = $this->bcrypt->hash_password($hash);
				   $data_where=array("c_email"=>$data['c_email']);
				   $update_data=array("token"=>$token);
				   $update_info = $this->comman_model->update('customers', $data_where, $update_data);	
				   
				   if($update_info){
						$data_where=array("c_email"=>$data['c_email']);
						$result_data= $this->comman_model->get_data_where('customers',$data_where);
						if($result_data){
							$response = ["status"=>1,"message"=>"You got logged in successfully..","customer_info"=>$result_data];
						}else{
							$response = ["status"=>1,"message"=>"unable to get Customer Info.."];
						}
				   }else{
					   $response = ["status"=>1,"message"=>"Unable to Generate Token Please try again"];
					} */

					$where_array=array( "c_email"=>$data['c_email']);
					$update_data=array("device_token"=>$device_token );
					$this->comman_model->update('customers', $where_array, $update_data);

					$response = ["status"=>1,"message"=>"You got logged in successfully..","customer_info"=>$result];

				}
			} else {
				$response = ["status"=>0,"message"=>"Invalid Email Id or Password"];
			}
		}

		echo json_encode($response);
		exit(); 
	}

	public function  user_update_post(){
		$json = file_get_contents('php://input');
		$input_data = json_decode($json);
		$error = "";
		if (($input_data->c_id) != "") {
			$c_id= $input_data->c_id;
		}else{
			$error = "Customer Id is required";
			goto end;
		} 
		if (($input_data->c_name) != "") {
			$data['c_name']= $input_data->c_name;
		} else{
			$error = "Customer Name is required";
			goto end;
		}
		if (($input_data->c_email) != "") {
			$data['c_email']= $input_data->c_email;
		} else{
			$error = "Customer Email is required";
			goto end;
		}  
		end :
		if($error !="")
		{
			$response = ["status"=>0,"message"=>$error];
		}
		else
		{
			$cust_where=array("c_id"=>$c_id);           
			$cust_data = array('c_name' =>$data['c_name'],'c_email' =>$data['c_email']);
			$update_customer = $this->comman_model->update('customers', $cust_where, $cust_data); 
			if($update_customer){
				$c_name = $this->db->select('*')->from('customers')->where('c_id',$c_id)->get()->row()->c_name;
				$response = ["status"=>1,"message"=>"profile successfully updated","Customer_Name"=>$c_name];
			}else{
				$response = ["status"=>0,"message"=>"Unable to Update Profile"];
			}
		}
		$this->set_response($response);
	}

         //get vechile veriant
	public function vehicle_veriant_post(){
		$json = file_get_contents('php://input');
		$input_data = json_decode($json);
		$error="";     
		if (($input_data->distance) != "") {
			$distance= $input_data->distance;
		}else{
			$error = "Distance is required";
			goto end;
		}   
		if(isset($input_data->latitude) != ""){
			$latitude= $input_data->latitude;
		}else{
			$error = "latitude is required";
			goto end;  
		}if(isset($input_data->longitude) != ""){
			$longitude= $input_data->longitude;
		}else{
			$error = "longitude is required";
			goto end;
		}

		end :
		if($error !="")
		{
			$response = ["status"=>0,"message"=>$error];
		}
		else
		{
			$sql="SELECT *, ( 6371 * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance FROM positions JOIN vehicles ON positions.v_id = vehicles.v_id JOIN drivers ON drivers.d_id = vehicles.v_driver_id JOIN vehicle_group ON vehicle_group.gr_id = vehicles.v_group JOIN vehicle_type ON vehicle_type.vt_group = vehicles.v_group AND vehicle_type.v_type = vehicles.v_type    WHERE positions.id IN (SELECT MAX(id) FROM positions GROUP BY positions.v_id) and drivers.d_available_status='yes' and drivers.d_riding_status='no' GROUP BY drivers.d_id HAVING distance <2 ORDER BY distance LIMIT 0 , 20";

			$query = $this->db->query($sql);  
			$query_result= $query->result();
			foreach($query_result as $row){
				$hour = date("H");

                // $hour='4';


				if ($hour == $row->gr_mid_night_time_start || $hour <= $row->gr_mid_night_time_to)
				{
					$test=$distance-$row->gr_fixed_km;
					$diff=$test > 0 ? $test : 0;
					if($diff=='0'){
						$row->actual_price=round($row->gr_mid_night_charge);
					}else{

						$extra=($row->gr_price*$row->gr_mid_night_extra)/100;
						$charge=$row->gr_price+$extra;
						$v=$charge*$test;

						$row->actual_price=round($v+$row->gr_mid_night_charge);
					}
                // $row->actual_price=$row->gr_price*$distance; 
					$row->img_path= $local_path=$this->config->base_url().'assets/uploads/'.$row->image;
					$row->side_path=$local_path=$this->config->base_url().'assets/uploads/'.$row->sideimage;



				}else{
					$test=$distance-$row->gr_fixed_km;
					$diff=$test > 0 ? $test : 0;
					if($diff=='0'){
						$row->actual_price=round($row->gr_fixed_amount);
					}else{
						$v=$row->gr_price*$test;

						$row->actual_price=round($v+$row->gr_fixed_amount);
					}
                // $row->actual_price=$row->gr_price*$distance; 
					$row->img_path= $local_path=$this->config->base_url().'assets/uploads/'.$row->image;
					$row->side_path=$local_path=$this->config->base_url().'assets/uploads/'.$row->sideimage;

				}
			}
			if($query_result){
				$response = ["status"=>1,"vehicle_veriant_info"=>$query_result];
			}else{
				$response = ["status"=>0,"message"=>"Unable to get vehicle veriant info"];
			}
		}
		$this->set_response($response);

	}
    //get vechile veriant price
	public function vehicle_veriant_price_post(){
		$json = file_get_contents('php://input');
		$input_data = json_decode($json);
          $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */       
        if (($input_data->distance) != "") {
        	$distance= $input_data->distance;
        }else{
        	$error = "Distance is required";
        	goto end;
        }   
        end :
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$this->db->select('vehicle_group.gr_name as gr_name,vehicle_group.gr_price as gr_price');
        	$this->db->from('vehicles');
        	$this->db->join('vehicle_group', 'vehicle_group.gr_id=vehicles.v_group');
        	$this->db->group_by('vehicle_group.gr_id');
        	$query = $this->db->get(); 
        	$query_result= $query->result();
        	foreach($query_result as $row){
        		$row->actual_price=$row->gr_price*$distance;
        	}
        	if($query_result){
        		$response = ["status"=>1,"vehicle_veriant_info"=>$query_result];
        	}else{
        		$response = ["status"=>0,"message"=>"Unable to get vehicle veriant info"];
        	}
        	$this->set_response($response);



        }  
    }
        //driver singup page
    public function driver_singup_post(){ 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error='';
    	if(($input_data->d_name) != "")
    	{
    		$data['d_name'] = $input_data->d_name;
    		$data['d_email'] = $input_data->d_email;
    		$data['d_doj'] = date("Y-m-d H:i:s");               
    	}else{            
    		$error = "Name is required";
    		goto end;
    	}
    	if(($input_data->d_mobile) != "")
    	{
    		$data['d_mobile'] = $input_data->d_mobile;  
    		$data['d_created_date'] = date("Y-m-d H:i:s");              
    	}else{            
    		$error = "Mobile is required";
    		goto end;
    	}
    	if($input_data->organization_id != "")
    	{
    		$data['organization_id'] = $input_data->organization_id;               
    	}else{            
    		$error = "Organization Id is Required";
    		goto end;
    	} 
    	if($input_data->v_registration_no != "")
    	{
    		$v_data['v_registration_no'] = $input_data->v_registration_no;               
    	}else{            
    		$error = "Vehicle registration number is Required";
    		goto end;
    	}
    	if($input_data->v_type != "")
    	{
    		$v_data['v_type'] = $input_data->v_type;  
    		$v_data['v_created_date'] = date("Y-m-d H:i:s");                    
    	}else{            
    		$error = "Vehicle Type is Required";
    		goto end;
    	}if($input_data->v_group != "")
    	{
    		$v_data['v_group'] = $input_data->v_group;               
    	}else{            
    		$error = "Vehicle Group Id is Required";
    		goto end;
    	}


    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else 
    	{ 

    		$where_array=array( "d_mobile"=>$data['d_mobile']);
    		$update_data=array("organization_id"=>$data['organization_id'] ,"d_name"=>$data['d_name'],"d_created_date"=>$data['d_created_date'],"d_doj"=>$data['d_doj'],"d_email"=>$data['d_email'],"d_is_active"=>"1");
    		$update=$this->comman_model->update('drivers', $where_array, $update_data);

    		$db_otp = $this->db->select('d_id')->from('drivers')->where('d_mobile',$data['d_mobile'])->get()->row_array();
    		$v_data['v_driver_id']=$db_otp['d_id'];
    		$response = $this->vehicle_model->add_vehicle($v_data);
    		if($response){
    			$response = ["status"=>1,"message"=>"Your Registered Successfully"];
    		}else{
    			$response = ["status"=>0,"message"=>"Unable To Register"];
    		}

    	}
    	echo json_encode($response);
    	exit(); 
    }
    // rc front file 
    public function rc_front_file_post(){ 
    	$error='';
    	if(isset($_FILES['image']) != "")
    	{  
    		$file_data = $_FILES['image']; 
    	}else{            
    		$error = "RC Front Image is Required";
    		goto end;
    	}if($this->input->post('driver_id') !="")
    	{
    		$driver_id = $this->input->post('driver_id');               
    	}else{            
    		$error = "Driver Id is Required";
    		goto end;
    	}if($this->input->post('driver_name') !="")
    	{
    		$driver_name = $this->input->post('driver_name');               
    	}else{            
    		$error = "Driver Name is Required";
    		goto end;
    	}if($this->input->post('org_code') !="")
    	{
    		$org_code = $this->input->post('org_code');               
    	}else{            
    		$error = "Organization code is Required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else 
    	{                 
    		$document_name="rc_front_file";
    		$file_info=$this->api_model->file_upload($file_data,$driver_id,$driver_name,$document_name,$org_code);
    		if($file_info){
    			
    			$this->db->where('driver_id',$driver_id);
    			$query = $this->db->get('drivers_documents');
    			$restult_count=$query->num_rows(); 
    			if($restult_count == 4){ 
    				$where=array("d_id"=>$driver_id);
    				$data=array("d_is_active"=>"0");
    				$this->comman_model->update("drivers", $where, $data);
    			}else{
    				
    			}         
    			
    			$result = ["status"=>1,"message"=>"file uploaded successfully"];
    		}else{ 
                  //  $result = ["status"=>0,"message"=>$file_info];
    		} 
    	}
    	
    	echo json_encode($result);
    	exit(); 
    }
        //rc_back_file
    public function rc_back_file_post(){
    	$error='';
    	if(isset($_FILES['image']) != "")
    	{
    		$file_data = $_FILES['image']; 
    	}else{            
    		$error = "RC Back Image is Required";
    		goto end;
    	}if($this->input->post('driver_id') !="")
    	{
    		$driver_id = $this->input->post('driver_id');               
    	}else{            
    		$error = "Driver Id is Required";
    		goto end;
    	}if($this->input->post('driver_name') !="")
    	{
    		$driver_name = $this->input->post('driver_name');               
    	}else{            
    		$error = "Driver Name is Required";
    		goto end;
    	}if($this->input->post('org_code') !="")
    	{
    		$org_code = $this->input->post('org_code');               
    	}else{            
    		$error = "Organization code is Required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else 
    	{                 
    		$document_name="rc_back_file";
    		$file_info=$this->api_model->file_upload($file_data,$driver_id,$driver_name,$document_name,$org_code);
    		if($file_info){
    			$this->db->where('driver_id',$driver_id);
    			$query = $this->db->get('drivers_documents');
    			$restult_count=$query->num_rows(); 
    			if($restult_count == 4){ 
    				$where=array("d_id"=>$driver_id);
    				$data=array("d_is_active"=>"0");
    				$this->comman_model->update("drivers", $where, $data);
    			}else{
    				
    			} 
    			$result = ["status"=>1,"message"=>"file uploaded successfully"];
    		}else{
    			$result = ["status"=>0,"message"=>"unable to upload file"];
    		} 
    	}
    	
    	echo json_encode($result);
    	exit();  
    }

         //dl_front_file
    public function dl_front_file_post(){
    	$error='';
    	if(isset($_FILES['image']) != "")
    	{ 
    		$file_data = $_FILES['image']; 
    	}else{            
    		$error = "DL Front Image is Required";
    		goto end;
    	}if($this->input->post('driver_id') !="")
    	{
    		$driver_id = $this->input->post('driver_id');               
    	}else{            
    		$error = "Driver Id is Required";
    		goto end;
    	}if($this->input->post('driver_name') !="")
    	{
    		$driver_name = $this->input->post('driver_name');               
    	}else{            
    		$error = "Driver Name is Required";
    		goto end;
    	}if($this->input->post('org_code') !="")
    	{
    		$org_code = $this->input->post('org_code');               
    	}else{            
    		$error = "Organization code is Required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else 
    	{       
    		$document_name="dl_front_file";            
    		$file_info=$this->api_model->file_upload($file_data,$driver_id,$driver_name,$document_name,$org_code);
    		if($file_info){
    			$this->db->where('driver_id',$driver_id);
    			$query = $this->db->get('drivers_documents');
    			$restult_count=$query->num_rows(); 
    			if($restult_count == 4){ 
    				$where=array("d_id"=>$driver_id);
    				$data=array("d_is_active"=>"0");
    				$this->comman_model->update("drivers", $where, $data);
    			}else{
    				
    			} 
    			$result = ["status"=>1,"message"=>"file uploaded successfully"];
    		}else{
    			$result = ["status"=>0,"message"=>"unable to upload file"];
    		} 
    		
    	}            
    	echo json_encode($result);
    	exit(); 
    }
        //dl_back_file
    public function dl_back_file_post(){ 
    	$error='';
    	if(isset($_FILES['image']) != "")
    	{
    		$file_data = $_FILES['image']; 
    	}else{            
    		$error = "DL Back Image is Required";
    		goto end;
    	}if($this->input->post('driver_id') !="")
    	{
    		$driver_id = $this->input->post('driver_id');               
    	}else{            
    		$error = "Driver Id is Required";
    		goto end;
    	}if($this->input->post('driver_name') !="")
    	{
    		$driver_name = $this->input->post('driver_name');               
    	}else{            
    		$error = "Driver Name is Required";
    		goto end;
    	}if($this->input->post('org_code') !="")
    	{
    		$org_code = $this->input->post('org_code');               
    	}else{            
    		$error = "Organization code is Required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else 
    	{                 
    		$document_name="dl_back_file";
    		$file_info=$this->api_model->file_upload($file_data,$driver_id,$driver_name,$document_name,$org_code);
    		if($file_info){
    			$this->db->where('driver_id',$driver_id);
    			$query = $this->db->get('drivers_documents');
    			$restult_count=$query->num_rows();  
    			if($restult_count == "4"){ 
    				$where=array("d_id"=>$driver_id);
    				$data=array("d_is_active"=>"0");
    				$this->comman_model->update("drivers", $where, $data);
    			}else{
    				
    			} 
    			$result = ["status"=>1,"message"=>"file uploaded successfully"];
    		}else{
    			$result = ["status"=>0,"message"=>"unable to upload file"];
    		} 
    	}
    	
    	echo json_encode($result);
    	exit();
    }

    public function driver_login_post() { 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error="";
    	if (($input_data->d_mobile) != ""){
    		$data['d_mobile']= $input_data->d_mobile;
    	}else {
    		$error = "Mobile Number is required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else
    	{

    		$this->db->where('d_mobile', $data['d_mobile']);
    		$query = $this->db->get("drivers");
    		if ($query->num_rows() >= 1) {
    			$result = $query->row_array();


    			if($result['d_is_active']==0) {

    				$result = ["status"=>0,"message"=>"Driver is not active.Please contact admin"];
    			}else{
    				$trip_where=array("d_mobile"=>$data['d_mobile']);
    				$data['d_otp'] = rand(1000, 9999);

    				$trp_data = array('d_otp' =>$data['d_otp']);
    				$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);

    				if($update_trip){

    					$apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
                // Message details
    					$OTP = $data['d_otp'];
    					$numbers = $data['d_mobile'];
    					$sender = urlencode("Volta");
    					$message = rawurlencode('Dear User, your OTP for Volta App Login is '.$OTP.'.Do not share your OTP with anyone .'); 

                // Prepare data for POST request
    					$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
                // Send the POST request with cURL
    					$ch = curl_init('https://api.textlocal.in/send/');
    					curl_setopt($ch, CURLOPT_POST, true);
    					curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    					$response = curl_exec($ch);
    					curl_close($ch);
                // Process your response here
                // echo $response;

    					$result = ["status"=>1,"message"=>"OTP sent to registered Mobile Number"];


    				}else{
    					$result = ["status"=>0,"message"=>"Unable to get otp"];
    				}
    			}
    		}else{

    			$data['d_otp'] = rand(1000, 9999);           
    			$update_trip = $this->comman_model->insert_record('drivers',$data);
    			if($update_trip){
    				$apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
                // Message details
    				$OTP = $data['d_otp'];
    				$numbers = $data['d_mobile'];
    				$sender = urlencode("Volta");
    				$message = rawurlencode('Dear User, your OTP for Volta App Login is '.$OTP.'.Do not share your OTP with anyone .'); 

                // Prepare data for POST request
    				$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
                // Send the POST request with cURL
    				$ch = curl_init('https://api.textlocal.in/send/');
    				curl_setopt($ch, CURLOPT_POST, true);
    				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    				$response = curl_exec($ch);
    				curl_close($ch);
    				$result = ["status"=>0,"message"=>"OTP sent to your Mobile Number"];
    			}
    		}

    	}   

    	$this->set_response($result);

    }
//user booking
    public function user_booking_post(){
            // die('hi');
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
             $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->t_customer_id) != "") {
        	$data['t_customer_id']= $input_data->t_customer_id;
        	$data['t_trackingcode'] = uniqid();
        }else {
        	$error = "Customer Id is required";
        	goto end;
        }if(isset($input_data->t_payment_type) != ""){ 
        	$data['t_payment_type']= $input_data->t_payment_type; 
        }else {
        	$error = "Payment Type is required";
        	goto end;
        }if (isset($input_data->t_trip_fromlocation) != "") {
        	$data['t_trip_fromlocation']= $input_data->t_trip_fromlocation;
        	$data['t_created_date']= date("Y-m-d H:i:s");
        	$data['t_start_date']= date("Y-m-d h:i:s:A");
        }else {
        	$error = "From Location is required";
        	goto end;
        }
        if(isset($input_data->t_trip_tolocation) != "") {
        	$data['t_trip_tolocation']= $input_data->t_trip_tolocation;
        	$data['t_otp'] = rand(1000,9999);
        }else {
        	$error = "To Location is required";
        	goto end;
        }
        if(isset($input_data->t_trip_fromlat) != "") {
        	$data['t_trip_fromlat']= $input_data->t_trip_fromlat;
        }else {
        	$error = "From lattitude is required";
        	goto end;
        }
        if(isset($input_data->t_trip_fromlog) != "") {
        	$data['t_trip_fromlog']= $input_data->t_trip_fromlog;
        }else {
        	$error = "From longitude is required";
        	goto end;
        }
        if(isset($input_data->t_trip_tolat) != "") {
        	$data['t_trip_tolat']= $input_data->t_trip_tolat;
        }else {
        	$error = "To lattitude is required";
        	goto end;
        }
        if(isset($input_data->t_trip_tolog) != "") {
        	$data['t_trip_tolog']= $input_data->t_trip_tolog;
        }else {
        	$error = "To longitude is required";
        	goto end;
        }
        if(isset($input_data->t_vehicle_group_id) != "") {
                // $data['t_vehicle_group_id']= $input_data->t_vehicle_group_id;
        	$t_vehicle_group_id= $input_data->t_vehicle_group_id;
        }else {
        	$error = "vehicle group id is required";
        	goto end;
        }
        if(isset($input_data->t_totaldistance) != "") {
        	$data['t_totaldistance']= $input_data->t_totaldistance;
        }else {
        	$error = "Total Distance is required";
        	goto end;
        }
        if(isset($input_data->t_trip_amount) != "") { 
        	$data['t_trip_amount']= $input_data->t_trip_amount; 
        }else {
        	$error = "Trip Amount is required";
        	goto end;
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
            // $data['t_start_date']=date("Y-m-d");
        	$trip_id= $this->trips_model->add_from_mobile_trips($data); 
                // $trip_id=$this->comman_model->insert_record('tr',$data);
                // print_r($trip_id);
                // exit;
        	if($trip_id){
        		$from_lat= $data['t_trip_fromlat'];
        		$from_long=$data['t_trip_fromlog'];

        		$sql="SELECT *, ( 6371 * acos( cos( radians($from_lat) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($from_long) ) + sin( radians($from_lat) ) * sin( radians( latitude ) ) ) ) AS distance FROM positions JOIN vehicles ON positions.v_id = vehicles.v_id JOIN drivers ON drivers.d_id = vehicles.v_driver_id JOIN vehicle_group ON vehicles.v_group= vehicle_group.gr_id  WHERE positions.id IN (SELECT MAX(id) FROM positions GROUP BY positions.v_id) and drivers.d_available_status='yes' and vehicles.v_type='$t_vehicle_group_id' and drivers.d_riding_status='no'  GROUP BY drivers.d_id  HAVING distance <2  ORDER BY distance LIMIT 0 , 20";          
        		$query = $this->db->query($sql);  
        		$driver_details= $query->result(); 
        		foreach($driver_details as $row){


        			$driver_id=$row->d_id;
        			$insertdata=array(
        				'n_driver_id'=>$driver_id, 
        				'n_trip_id'=>$trip_id,
        				'n_trip_status'=>'pending' 
        			);
        			$this->db->insert('notification',$insertdata);

        			$device_id=$row->device_token;
        			$title='Booking';
        			$name=$row->d_name;
        			$d_id=$row->d_id;
        			$message='Name :'.$row->d_name.'From Location : '.$data['t_trip_fromlocation'].' '.'To Location :'.$data['t_trip_tolocation'];
                      // $message="User Booking for text";
        			$this->comman_model->fcm_notification($device_id,$title,$message);

                        //nofication table insert notification
        			$n_data=array(
        				"n_user_id"=>$d_id,
        				"n_user_type"=>"driver",
        				"n_title"=>"User Request",
        				"n_message"=>"User Trying To Book A Ride",
        				"n_created_date"=> date('y-m-d'),
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data);

        		}
        		$response = ["status"=>1,"message"=>"Please wait Checking Available Vehicle checking ...","trip_id"=>$trip_id,"t_otp"=>$data['t_otp']]; 
        	}else{
        		$response = ["status"=>0,"message"=>"Unable To book Vehicle Please Try again"];
        	}
        }
        echo json_encode($response);
        exit(); 

    }
        //Get Notification
    public function notification_post(){             
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
             $error="";/*$token = $input_data->token;
            $error = "";
            if (isset($token) != "") {
                $this->check_token($token);
            }else {
                $error = "Token is required";
                goto end;
            }        */
            if (isset($input_data->n_driver_id) != "") {
            	$n_driver_id= $input_data->n_driver_id;
            }else {
            	$error = "Driver Id is required";
            	goto end;
            } 
            
            end:
            if($error !="")
            {
            	$response = ["status"=>0,"message"=>$error];
            }
            else
            {
            	$this->db->select('trips.*,trips.*,customers.c_name as c_name,customers.c_mobile,customers.c_email as c_email'); 
            	$this->db->from('notification');
            	$this->db->join('trips', 'trips.t_id=notification.n_trip_id');
            	$this->db->join('customers', 'customers.c_id=trips.t_customer_id');
            	$this->db->join('drivers', 'drivers.d_id=notification.n_driver_id');
            	$this->db->where('notification.n_trip_status','pending');
            	$this->db->where('notification.n_driver_id',$n_driver_id);
            	$this->db->group_by('notification.n_id'); 
            	$this->db->group_by('trips.t_id');
            	$query = $this->db->get(); 
            	$query_result= $query->result_array();
            	if($query_result){
            		$response = ["status"=>1,"booking_info"=>$query_result];
            	}else{ 
            		$response = ["status"=>0,"message"=>"Unable to get Booking info"];
            	}
            } 
            echo json_encode($response);
            exit(); 
        }



        	//Driver  online or offline update code 
        public function driver_online_status_update_post(){
        	$json = file_get_contents('php://input');
        	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->d_available_status) != "") {
        	$data['d_available_status']= $input_data->d_available_status;
        }else {
        	$error = "Driver Available is required";
        	goto end;
        }
        if (isset($input_data->d_id) != "") {
        	$data['d_id']= $input_data->d_id;
        }else {
        	$error = "Driver Id is required";
        	goto end;
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$update_driver_status = [
        		'd_available_status' => $data['d_available_status'],
        	];
        	$this->db->where('d_id',$data['d_id']); 
        	$this->db->update('drivers', $update_driver_status);
        	if ($this->db->affected_rows() > 0)
        	{
        		$response = ["status"=>1,"message"=>"Successfully Updated"];
        	}
        	else
        	{
        		$response = ["status"=>0,"message"=>"Unable to Update"];
        	}
        }
        echo json_encode($response);
        exit(); 

    } 

//Driver postion insert into database
    public function insert_vehicle_position_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       // $token = $input_data->token;
         $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */ 
        if(isset($input_data->v_id) != ""){  
        	$data['v_id']= $input_data->v_id;
        	$vid= $input_data->v_id;
            // $tid= '2';
        }else{
        	$error = "Vehicle Id is required";
        	goto end;
        }
        if(isset($input_data->t_id) != ""){  
        	$t_id= $input_data->t_id;



        }else{
        	$t_id= '0';
        }
        if(isset($input_data->latitude) != ""){
        	$data['latitude']= $input_data->latitude;
        	$lat= $input_data->latitude;

        }else{
        	$error = "latitude is required";
        	goto end; 
        }
        if(isset($input_data->longitude) != ""){
        	$data['longitude']= $input_data->longitude;
        	$lon= $input_data->longitude;

        }else{
        	$error = "longitude is required";
        	goto end;
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {     

        	$result_data = $this->comman_model->insert_record('positions',$data);      
        	$data1= $this->db->select('*')->from('wait_time')->where('w_v_id',$vid)->where('w_t_id',$t_id)->order_by('w_id','desc')->limit(1)->get()->row_array();
            // $result_data = $this->comman_model->insert_record('positions',$data);

//             if($data1==""){

//                 // die('ji');
//                 if($t_id>0){
//                 $insert1['w_lat']=$data['latitude'];
//                 $insert1['w_long']=$data['longitude'];
//                 $insert1['w_t_id']=$t_id;
//                 // $data['w_time']=date('Y-m-d h:i:s');
//                 $insert1['w_v_id']=$vid;
//                 $insert1['w_date']=date('Y-m-d h:i:s');

//                 $result_data = $this->comman_model->insert_record('wait_time',$insert1);
//             }

//             }else{

//                 if($t_id>0){
//                     $lat= $this->db->select('*')->from('wait_time')->where('w_v_id',$vid)->where('w_t_id',$t_id)->order_by('w_id','desc')->limit(1)->get()->row_array(); 


// $latitudeFrom =$lat['w_lat'];
// $longitudeFrom =$lat['w_long'];
// $latitudeTo = $data['latitude'];
// $longitudeTo = $data['longitude'];

// ///Calculate distance from latitude and longitude
// $theta = $longitudeFrom - $longitudeTo;
// $dist = sin(deg2rad($latitudeFrom))*sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
// $dist = acos($dist);
// $dist = rad2deg($dist);
// $miles = $dist  *60  *1.1515;

// $distance = ($miles * 1.609344);

// // $distance = ($miles * 1.609344);
// $meters=$distance*1000;

// if($meters>10){
//               $insert['w_lat']=$data['latitude'];
//                 $insert['w_long']=$data['longitude'];
//                 $datetime=$lat['w_date'];
//                 $insert['w_t_id']=$t_id;
//                 $insert['w_v_id']=$vid;
//                 $insert['w_date']=date('Y-m-d h:i:s');
//                 $currentdate=date('Y-m-d h:i:s');
//              $datetime1 = new DateTime($datetime);
//             $datetime2 = new DateTime($currentdate);
//             $interval = $datetime1->diff($datetime2);
//             // $a=strtotime($interval);
//             $time=$interval->format('%h:%i:%s');
//             $timesplit=explode(':',$time);
//             $min=($timesplit[0]*60)+($timesplit[1])+($timesplit[2]>30?1:0);
//             $seconds=$min*60;



//                if($seconds>5){
//                 $insert['w_time']=gmdate("H:i:s",$seconds);

//                $insert['w_status']='1';
//                 $result_data = $this->comman_model->insert_record('wait_time',$insert);
//                }else{
//                 $result_data = $this->comman_model->insert_record('wait_time',$insert);
//             }

// }else{

//                // $data['w_lat']=$lat;
//                //  $data['w_long']=$lon;
//                //  // $data['w_time']=date('Y-m-d h:i:s');
//                //  $data['w_v_id']=$vid;
//                //  $data['w_date']=date('Y-m-d h:i:s');

//                //  $result_data = $this->comman_model->insert_record('wait_time',$data);


// }


//                 }






// }

            // $result_data = $this->comman_model->insert_record('positions',$data); 
        	if($result_data){

        		$vechile_details=$this->db->select('*')->from('vehicles')->join('vehicle_type', 'vehicle_type.vt_group = vehicles.v_group')->group_by('vehicles.v_group')->where('v_id',$vid)->order_by('id','desc')->get()->result();
        		foreach($vechile_details as $row){
        			$row->img_path= $local_path=$this->config->base_url().'assets/uploads/'.$row->image;
        		} 
                //check geo fencing 
        		$this->check_geo_fencing($vid,$lat,$lon);
        		$response = ["status"=>0,"message"=>'Successfully Updated position',"details"=>$vechile_details];
        	}else{
        		$response = ["status"=>0,"message"=>'Unable to Update position'];
        	}
        }
        $this->set_response($response);

    }
    public function check_geo_fencing($v_id,$lat,$lon){ 
    	$timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : NULL;
    	$altitude = isset($_GET["altitude"]) ? $_GET["altitude"] : NULL;
    	$speed = isset($_GET["speed"]) ? $_GET["speed"] : NULL;
    	$bearing = isset($_GET["bearing"]) ? $_GET["bearing"] : NULL;
    	$accuracy = isset($_GET["accuracy"]) ? $_GET["accuracy"] : NULL;
    	$comment = isset($_GET["comment"]) ? $_GET["comment"] : NULL;
    	$postarray = array('v_id'=>$v_id,'latitude'=>$lat,'longitude'=>$lon,'time'=>date('Y-m-d h:i:s'),'altitude'=>$altitude,'speed'=>$speed,'bearing'=>$bearing,'accuracy'=>$accuracy,'comment'=>$comment);
    	$this->checkgeofence($v_id,$lat,$lon);
    }
    
      // get the accept details 
    public function accept_post() {
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */

        if (isset($input_data->d_id) != "") {
        	$d_id= $input_data->d_id;
        }else {
        	$error = "Driver id  is required";
             // echo $error;
        }
        if (isset($input_data->c_id) != "") {
        	$c_id= $input_data->c_id;
        }else {
        	$error = "customer id  is required";
             // echo $error;
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
            // $data=$this->db->select('d_name,d_mobile,d_available_status,d_riding_status,d_address,d_age,d_licenseno,d_license_expdate,d_total_exp,d_doj,d_ref,d_is_active,c_id,c_name,c_mobile,c_email,c_address,c_isactive,v_id ,v_name,v_registration_no,v_model,v_chassis_no,v_engine_no,v_manufactured_by,v_type,v_driver_id,v_group,v_mileageperlitre,t_customer_id,t_driver,t_start_date,t_end_date,t_trip_fromlocation,t_trip_tolocation,t_trip_fromlat,t_trip_fromlog,t_trip_tolat,t_trip_tolog,t_totaldistance,t_trip_amount,t_trip_status,t_trackingcode,t_driver_fromlog,t_driver_status,t_driver_fromlat')->from('drivers')->join('trips', 'trips.t_driver = drivers.d_id')->join('vehicles', 'vehicles.v_driver_id = drivers.d_id')->join('customers', 'customers.c_id = trips.t_customer_id')->where('d_id',$d_id)->where('trips.t_trip_status',"accepted")->where('c_id',$c_id)->order_by('d_id','asc')->get()->result_array();
        	$this->db->select('d_name,d_mobile,d_available_status,d_riding_status,d_address,d_age,d_licenseno,d_license_expdate,d_total_exp,d_doj,d_ref,d_is_active,c_id,c_name,c_mobile,c_email,c_address,c_isactive,v_id ,v_name,v_registration_no,v_model,v_chassis_no,v_engine_no,v_manufactured_by,v_type,v_driver_id,v_group,v_mileageperlitre,t_customer_id,t_driver,t_start_date,t_end_date,t_trip_fromlocation,t_trip_tolocation,t_trip_fromlat,t_trip_fromlog,t_trip_tolat,t_trip_tolog,t_totaldistance,t_trip_amount,t_trip_status,t_trackingcode,t_driver_fromlog,t_driver_status,t_driver_fromlat');
        	$this->db->from('drivers');
        	$this->db->join('trips', 'trips.t_driver = drivers.d_id');
        	$this->db->join('vehicles', 'vehicles.v_driver_id = drivers.d_id');
        	$this->db->join('customers', 'customers.c_id = trips.t_customer_id');
        	$this->db->where('drivers.d_id',$d_id); 
            // $this->db->where('trips.t_trip_status',"gotopickup"); 
        	$this->db->where('customers.c_id',$c_id);
        	$where = '(trips.t_trip_status="accepted" or trips.t_trip_status = "gotopickup")';
        	$this->db->where($where);
        	$this->db->order_by("d_id", "desc");
        	$query = $this->db->get(); 
        	$query_result= $query->result();
        	if($query_result){
        		$response = array('status'=>1,'customer_details'=>$query_result);
        	}else{
        		$response = array('status'=>0,'message'=>"Unable to get Data Please Try again");
        	}
        }
        $this->set_response($response);
    }
     // booking accepet from mobile
    public function accepted_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->t_id) != "") {
        	$t_id= $input_data->t_id;
        }else {
        	$error = "Trip id  is required";
        	goto end;
        }
        if (isset($input_data->t_vehicle) != "") { 
        	$data1['t_vechicle']= $input_data->t_vehicle;
        }else {
        	$error = "Vehicle id  is required";
        	goto end;
        }
        if (isset($input_data->t_driver) != "") {
        	$data1['t_driver']= $input_data->t_driver;
        }else {
        	$error = "Driver id  is required";
        	goto end;
        }
        if (isset($input_data->t_trip_status) != "") {
        	$data1['t_trip_status']= $input_data->t_trip_status;
        }else {
        	$error = "status  is required";
        	goto end;
        }
        if (isset($input_data->t_driver_status) != "") {
        	$data1['t_driver_status']= $input_data->t_driver_status;
        }else {
        	$error = "Driver status  is required";
        	goto end;
        } 
        if(isset($input_data->t_driver_fromlat) != "") {
        	$data1['t_driver_fromlat']= $input_data->t_driver_fromlat;
        }else {
        	$error = "From lattitude is required";
        	goto end;
        }
        if(isset($input_data->t_driver_fromlog) != "") { 
        	$data1['t_driver_fromlog']= $input_data->t_driver_fromlog;
        }else {
        	$error = "From longitude is required";
        	goto end; 
        }
        if(isset($input_data->t_v_group) != "") { 
        	$data1['t_vehicle_group_id']= $input_data->t_v_group;
        }else {
        	$error = "From longitude is required";
        	goto end; 
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$trip_id = $this->trips_model->upadte($data1,$t_id); 
        	$trip_id2 = $this->trips_model->upadtenotifiy($data1,$t_id);
        	$trip_id3 = $this->trips_model->upadtedriver($data1);
        	$response = ["status"=>1,"message"=>"Driver accepted the order"]; 

				 //FCM Integration
        	$user_data = $this->trips_model->get_User_data($t_id);
              //echo $this->db->last_query();

             //fcm customer 
        	$device_id=$user_data['c_device_token'];
        	$title='Your Booking Accepted By Driver';
        	$message='Driver Name :'.$user_data['d_name'].'  Vehicle No : '.$user_data['v_registration_no'];
        	$this->comman_model->fcm_notification($device_id,$title,$message);

             //fcm driver 
        	$device_id=$user_data['d_device_token'];
        	$title='You Confirmed The User Request';
        	$message='User Name :'.$user_data['c_name'].'Mobile No : '.$user_data['c_mobile'];
        	$this->comman_model->fcm_notification($device_id,$title,$message); 

              //nofication table insert notification
        	$n_data=array(
        		"n_user_id"=>$data1['t_driver'],
        		"n_user_type"=>"driver",
        		"n_title"=>"Ride Confirmed",
        		"n_message"=>"You confirmed the User Booking Request",
        		"n_created_date"=> date('y-m-d'),
        		"n_created_date_time"=> date('y-m-d H:i:s')
        	);
        	$this->comman_model->insert_record('all_notifications', $n_data);
        	$user_data_info=array(
        		"n_user_id"=>$user_data['t_customer_id'],
        		"n_user_type"=>"user",
        		"n_title"=>"Ride Confirmation",
        		"n_message"=>"Your Ride Confirmed by Driver",
        		"n_created_date"=> date('y-m-d'),
        		"n_created_date_time"=> date('y-m-d H:i:s')
        	);
        	$this->comman_model->insert_record('all_notifications', $user_data_info);
			// $apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
   //              // Message details
   //              $OTP = $user_data['t_otp'];
   //              $numbers = $user_data['c_mobile'];
   //              $sender = urlencode("Volta");
   //              $message = rawurlencode('Dear User, Driver has accepted your Ride.Your Volta App Trip OTP is '.$OTP.'.Do not share your OTP with anyone .'); 

   //              // Prepare data for POST request
   //              $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
   //              // Send the POST request with cURL
   //              $ch = curl_init('https://api.textlocal.in/send/');
   //              curl_setopt($ch, CURLOPT_POST, true);
   //              curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   //              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   //              $response = curl_exec($ch);
   //              curl_close($ch);

        	$trip=$this->db->select('*')->from('trips')->where('t_id',$t_id)->order_by('t_id','asc')->get()->row_array();
        	if($trip['t_trip_status'] == "accepted"){
        		$response = ["status"=>1,"message"=>"Driver already accepted the order"];
        	}elseif($trip['t_trip_status'] == "session_out"){
        		$response = ["status"=>0,"message"=>"session out"];

        	}else{
                //Trip Table Update
        		$trip_where=array("t_id"=>$t_id);           
        		$trp_data = array('t_trip_status' => $data1['t_trip_status'],'t_driver_fromlog' =>$data1['t_driver_fromlog'],'t_driver_fromlat' =>$data1['t_driver_fromlat'],'t_driver' =>$data1['t_driver'],'t_vechicle' =>$data1['t_vechicle'],'t_driver_status' =>$data1['t_driver_status']);
        		$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
        		if($update_trip){ 
               //notification update
        			$notification_where=array("n_trip_id"=>$t_id, "n_driver_id"=>$data1['t_driver']);           
        			$notification_data = array('n_trip_status' => $data1['t_trip_status']);
        			$update_trip1 = $this->comman_model->update('notification', $notification_where, $notification_data);

        			$drv=$data1['t_driver'];
        			$ntrip=$data1['t_trip_status'];
        			$array = array('n_trip_status' => 'already_accepted');
        			$this->db->where('n_driver_id !=', $drv);
        			$this->db->where('n_trip_id ', $t_id);
        			$this->db->update('notification',$array);  
        		}
        		if($update_trip1){ 
            //driver update
        			$driver_where=array( "d_id"=>$data1['t_driver']);
        			$driver_data = array('d_riding_status' => 'yes'); 
        			$update_trip2 = $this->comman_model->update('drivers', $driver_where, $driver_data);

        			if($update_trip2){                

                //echo $this->db->last_query();  
                //insert user data into notification table

                //echo $this->db->last_query();  


        				$response = ["status"=>1,"message"=>"Driver accepted the Ride"]; 
        			}else{
        				$response = ["status"=>0,"message"=>"Unable to Driver  accepted the order"]; 
        			}
        		}else{
        			$response = ["status"=>0,"message"=>"Unable to Driver  accepted the order"];
        		}
        	}
        }  
        echo json_encode($response);
        exit(); 
    }


     // get the user history
    public function user_history_post() {
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->c_id) != "") {
        	$c_id= $input_data->c_id;
        }else {
        	$error = "Customer id  is required";        
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }

        else
        {
        	$this->db->select('*,sum(trips.t_dyanamic_price) + sum(trips.t_d_waiting_amount) AS total_amount' );
        	$this->db->from('customers');
        	$this->db->join('trips', 'trips.t_customer_id=customers.c_id');
        	$this->db->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id');
        	$this->db->where_not_in('trips.t_trip_status','yettoconfirm'); 
        	$this->db->where_not_in('trips.t_trip_status','session_out'); 
        	$this->db->where('customers.c_id',$c_id);
        	$this->db->group_by(array("trips.t_id","customers.c_id" ));
        	$this->db->order_by("trips.t_id", "desc");
        	$query = $this->db->get(); 
        	$query_result= $query->result();
        	foreach($query_result as $row){

        		if(isset($row->t_vechicle)){
        			$vehicle_where=array("v_id"=>$row->t_vechicle);
        			$row->vehicle_info= $this->comman_model->get_data_where('vehicles',$vehicle_where);
        			$driver_where=array("d_id"=>$row->t_driver);
        			$row->driver_info=  $this->comman_model->get_data_where('drivers',$driver_where);
        			$trip_payament_where=array("tp_trip_id"=>$row->t_id);
        			$row->trip_payament_info=  $this->comman_model->get_data_where('trip_payments',$trip_payament_where); 
                  //get payment status
        			$row->payment_status = $this->db->select('tp_payment_status')->from('trip_payments')->where('tp_trip_id',$row->t_id)->get()->row();
        			if($row->payment_status){
        				$row->payment_status=1;
        			}elseif($row->t_trip_status=="cancelled" || $row->t_trip_status=="admin_cancel"){
        				$row->payment_status=2;
        			}else{
        				$row->payment_status=0;
        			}


        		}


        	}
        	if($query_result){
        		$response = array('status'=>1,'user_history_details'=>$query_result);
        	}else{
        		$response = array('status'=>0,'message'=>'Unable to Get User Info'); 
        	}
        }
        $this->set_response($response);
    }

     // get the driver  history
    public function driver_history_post() {
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->d_id) != "") {
        	$d_id= $input_data->d_id;
        }else {
        	$error = "Driver id  is required";            
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else 
        {
        	$this->db->select('*,sum(trips.t_dyanamic_price) + sum(trips.t_d_waiting_amount) AS total_amount');
        	$this->db->from('drivers');
        	$this->db->join('trips', 'trips.t_driver=drivers.d_id');
        	$this->db->join('customers', 'customers.c_id=trips.t_customer_id');
        	$this->db->where('drivers.d_id',$d_id);
        	$this->db->group_by("trips.t_id");
        	$this->db->order_by("trips.t_id", "desc"); 
        	$query = $this->db->get(); 
        	$query_result= $query->result();
        	foreach($query_result as $row){
        		if(isset($row->t_td)){
        			$trip_payament_where=array("tp_trip_id"=>$row->t_id);
        			$row->trip_payament_info=  $this->comman_model->get_data_where('trip_payments',$trip_payament_where); 
        		}
        	}
        	if($query_result){
        		$response = array('status'=>1,'driver_history_details'=>$query_result);
        	}else{
        		$response = array('status'=>1,'message'=>'Unable to Get Driver Info');
        	}
        }
        $this->set_response($response);        
    }

    // get the driver details to user 
    public function driver_details_post() {
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->c_id) != "") {
        	$c_id= $input_data->c_id;
        }else {
        	$error = "customer id  is required";
        }
        end:
        if($error !="") 
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$data=$this->db->select('d_name,d_mobile,d_available_status,d_riding_status,d_address,d_age,d_licenseno,d_license_expdate,d_total_exp,d_doj,d_ref,d_is_active,c_id,c_name,c_mobile,c_email,c_address,c_isactive,t_id,t_vechicle,t_type,t_customer_id,t_driver,t_start_date,t_end_date,t_trip_fromlocation,t_trip_tolocation,t_trip_fromlat,t_trip_fromlog,t_trip_tolat,t_trip_tolog,t_totaldistance,t_trip_amount,t_trip_status,t_trackingcode,t_driver_fromlog,t_driver_status,t_driver_fromlat,v_id ,v_name,v_registration_no,v_model,v_chassis_no,v_engine_no,v_manufactured_by,v_type,v_driver_id,v_group,v_mileageperlitre,t_id,t_vechicle,t_type')->from('customers')->join('trips', 'trips.t_customer_id = customers.c_id')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->where('c_id',$c_id)->where('trips.t_driver_status','accepted')->order_by('c_id','asc')->get()->result_array();
        	$response = array('status'=>1,'driver_details'=>$data);
        }
        $this->set_response($response);    
    } 
     // get the driver details to user 
    public function driver_confirmation_post() {
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->c_id) != "") {
        	$c_id= $input_data->c_id;
        }else {
        	$error = "customer id  is required";           
        }
        if (isset($input_data->t_id) != "") {
        	$t_id= $input_data->t_id;
        }else {
        	$error = "Trip id  is required";           
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {

        	$data=$this->db->select('*')->from('customers')->join('trips', 'trips.t_customer_id = customers.c_id')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->join('vehicle_group', 'vehicle_group.gr_id = vehicles.v_group')->join('vehicle_type', 'vehicle_type.v_type = vehicles.v_type')->where('t_id',$t_id)->where('c_id',$c_id)->where('trips.t_driver_status','accepted')->where_not_in('trips.t_trip_status','completed')->order_by('t_id','desc')->limit(1)->get()->result();  
        	foreach($data as $row){

        		$row->img_path=$local_path=$this->config->base_url().'assets/uploads/'.$row->image;
        		$row->side_path=$local_path=$this->config->base_url().'assets/uploads/'.$row->sideimage;

        	} 

        	if($data){                
        		$response = array('status'=>1,'driver_details'=>$data); 
        	}else{                
        		$response = array('status'=>1,'message'=>'Unable to get driver details'); 
        	}    
        }
        $this->set_response($response);    
    }
    // vehicle current position 
    public function vehicle_current_position_post() {
    	$json = file_get_contents('php://input'); 
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if(isset($input_data->latitude) != ""){
        	$latitude= $input_data->latitude;
        }else{
        	$error = "latitude is required";
        	goto end;  
        }if(isset($input_data->longitude) != ""){
        	$longitude= $input_data->longitude;
        }else{
        	$error = "longitude is required";
        	goto end;
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$sql="SELECT *, ( 6371 * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance FROM positions JOIN vehicles ON positions.v_id = vehicles.v_id JOIN drivers ON drivers.d_id = vehicles.v_driver_id JOIN vehicle_type ON vehicle_type.vt_group = vehicles.v_group AND vehicle_type.v_type = vehicles.v_type    WHERE positions.id IN (SELECT MAX(id) FROM positions GROUP BY positions.v_id) and drivers.d_available_status='yes' and drivers.d_riding_status='no' GROUP BY drivers.d_id HAVING distance <2 ORDER BY distance LIMIT 0 , 20";           $query = $this->db->query($sql);  
        	$vechile_details= $query->result();    
        	foreach($vechile_details as $row){
        		$row->img_path= $local_path=$this->config->base_url().'assets/uploads/'.$row->image;
        	} 
        	if($vechile_details){
        		$response = ["status"=>1,"vechile_info"=>$vechile_details];
        	}else{
        		$response = ["status"=>0,"message"=>"No vehicle Your Location"];
        	}
        }
        echo json_encode($response);
        exit();  
    }
    
    // User Cancel Method
    public function user_cancel_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->t_id) != "") {
        	$t_id= $input_data->t_id;
        }else {
        	$error = "Trip id  is required";
        	goto end;
        }
        if (isset($input_data->c_id) != "") {
        	$data1['c_id']= $input_data->c_id;
        }else {
        	$error = "Customer id  is required";
        	goto end;
        }
        if (isset($input_data->t_trip_status) != "") {
        	$data1['t_trip_status']= $input_data->t_trip_status;
        }else {
        	$error = " Trip status  is required";
        	goto end;
        } 
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$trip_id = $this->trips_model->usercancel($data1,$t_id);
        	if($trip_id){
        		$user_data = $this->trips_model->get_User_data($t_id);
        		if($user_data){
        			$device_id=$user_data['d_device_token'];
        			$title='Customer has Cancelled Trip';
        			$message='Customer Name :'.$user_data['c_name'];
        			$this->comman_model->fcm_notification($device_id,$title,$message);

        			$n_data=array(
        				"n_user_id"=>$user_data['t_driver'],
        				"n_user_type"=>"driver",
        				"n_title"=>"User Trip Cancelled",
        				"n_message"=>"Trip Cancelled by User",
        				"n_created_date"=> date('y-m-d'), 
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data);
        		}else{

        		}


        		$response = ["status"=>1,"message"=>"Cancel the Trip"];  
        	}else{
        		$response = ["status"=>0,"message"=>"Unable to Cancel Trip"];  
        	}

        }
        echo json_encode($response);
        exit(); 

    }
    // Driver Cancel Method
    public function driver_cancel_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->t_id) != "") {
        	$t_id= $input_data->t_id;
        }else {
        	$error = "Trip id  is required";
        	goto end;
        }
        if (isset($input_data->t_driver) != "") {
        	$data1['t_driver']= $input_data->t_driver;
        }else {
        	$error = "Driver id  is required";
        	goto end;
        }
        if (isset($input_data->t_driver_status) != "") {
        	$data1['t_driver_status']= $input_data->t_driver_status;
        	$data1['t_trip_status']= $input_data->t_driver_status; 
        }else {
        	$error = " Driver status  is required";
        	goto end;
        } 
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
        	$trip_id= $this->trips_model->drivercancel($data1,$t_id);
        	if($trip_id){
        		$user_data = $this->trips_model->get_User_data($t_id);
        		if($user_data){
        			$device_id=$user_data['c_device_token'];
        			$title='Driver has Cancelled Trip';
        			$message='Driver Name :'.$user_data['d_name'].'  Vechicle No:'.$user_data['v_registration_no'];
        			$this->comman_model->fcm_notification($device_id,$title,$message);
                    //insert into all notification
        			$n_data=array(
        				"n_user_id"=>$user_data['t_customer_id'],
        				"n_user_type"=>"user",
        				"n_title"=>"Your Trip Cancelled",
        				"n_message"=>"Your Trip Cancelled by Driver",
        				"n_created_date"=> date('y-m-d'),
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data);
        		}
        		$response = ["status"=>1,"message"=>"Driver Cancel the Trip"]; 

        	}else{
        		$response = ["status"=>1,"message"=>"Unable to Driver Cancel the Trip"]; 

        	}           

        }
        echo json_encode($response);
        exit(); 
    }
     // Go to Pickup  Method
    public function gotopickup_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if (isset($input_data->t_id) != "") {
        	$t_id= $input_data->t_id;
        }else {
        	$error = "Trip id  is required";
        	goto end;
        }
        if (isset($input_data->t_driver) != "") {
        	$data1['t_driver']= $input_data->t_driver;
        }else {
        	$error = "Driver id  is required";
        	goto end;
        }
        if (isset($input_data->trip_status) != "") {
        	$data1['t_trip_status']= $input_data->trip_status;
        }else {
        	$error = " Trip status  is required";
        	goto end;
        } 
        if (isset($input_data->v_latitude) != "") {
        	$data1['v_latitude']= $input_data->v_latitude;
        }else {
        	$error = " Driver latitude  is required";
        	goto end;
        } 
        if (isset($input_data->v_longitude) != "") {
        	$data1['v_longitude']= $input_data->v_longitude;
        }else {
        	$error = " Driver longitude is required";
        	goto end;
        } 
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
            //Trip Table Update
        	$t_trip_status = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_trip_status;
        	if($t_trip_status=="cancelled"){
        		$response = ["status"=>1,"message"=>"User Cancelled The Trip"]; 
        	}elseif($t_trip_status=="admin_cancel"){
        		$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_driver;
        		$trip_where=array("d_id"=>$db_otp);           
        		$trp_data = array('d_riding_status' =>'no');
        		$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);
        		$response = ["status"=>1,"message"=>"Admin Cancelled The Trip"]; 
        		$user_data = $this->trips_model->get_User_data($t_id);                        
        		if($user_data){
                        //driver notification
        			$n_data=array(
        				"n_user_id"=>$user_data['t_driver'],
        				"n_user_type"=>"driver",
        				"n_title"=>"Admin Cancelled The Trip",
        				"n_message"=>"Admin Cancelled The Trip",
        				"n_created_date"=> date('y-m-d'), 
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data);
        			$n_data1=array(
        				"n_user_id"=>$user_data['t_customer_id'],
        				"n_user_type"=>"user",
        				"n_title"=>"Driver Started To Your Pickup Location",
        				"n_message"=>"Driver Started To Your Pickup Location",
        				"n_created_date"=> date('y-m-d'), 
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications',$n_data1);

                        //user notification
        			$n_data_user=array(
        				"n_user_id"=>$user_data['t_customer_id'],
        				"n_user_type"=>"user",
        				"n_title"=>"Admin Cancelled The Trip",
        				"n_message"=>"Admin Cancelled The Trip",
        				"n_created_date"=> date('y-m-d'), 
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data_user);

        		}

        	}
        	else{

        		$trip_where=array("t_id"=>$t_id, "t_driver"=>$data1['t_driver']);           
        		$trp_data = array('t_trip_status' => $data1['t_trip_status'],'t_driver_fromlog' =>$data1['v_longitude'],'t_driver_fromlat' =>$data1['v_latitude']);
        		$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
        		$user_data = $this->trips_model->get_User_data($t_id);
        		$device_id=$user_data['c_device_token'];
        		$title='Dear User Your Driver Started For your Pickup Location';
        		$message='Driver Name :'.$user_data['d_name'].' Driver Mobile : '.$user_data['d_mobile'];
                      // $message="User Booking for text";
        		$this->comman_model->fcm_notification($device_id,$title,$message);
        		if($update_trip){   
               //notification update
        			$notification_where=array("n_trip_id"=>$t_id, "n_driver_id"=>$data1['t_driver']);           
        			$notification_data = array('n_trip_status' => $data1['t_trip_status']);
        			$update_trip = $this->comman_model->update('notification', $notification_where, $notification_data);
        			if($update_trip){
        				$response = ["status"=>1,"message"=>"Pickup start the Driver"]; 
        			}else{
        				$response = ["status"=>0,"message"=>"Unable to Driver pickup the Trip"]; 
        			}
        		}else{
        			$response = ["status"=>0,"message"=>"Unable to Driver pickup the Trip"]; 
        		} 
        	}         

        }
        echo json_encode($response);
        exit(); 

    }

    public function trip_start_post(){ 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->td_trip_id) != "") { 
    		$t_id= $input_data->td_trip_id;
    		$data1['t_start_time']= date('y-m-d H:i:s');
    	}else {
    		$error = "Trip id  is required";
    		goto end;
    	}
    	if (isset($input_data->t_driver) != "") {
    		$data1['t_driver']= $input_data->t_driver;
    	}else {
    		$error = "Driver id  is required";
    		goto end;
    	}
    	if (isset($input_data->trip_status) != "") {
    		$data1['t_trip_status']= $input_data->trip_status;
    	}else {
    		$error = " Trip status  is required";
    		goto end;
    	} 
    	if (isset($input_data->td_latitude) != "") {
    		$data1['td_latitude']= $input_data->td_latitude;
    	}else {
    		$error = " Driver latitude  is required";
    		goto end;
    	} 
    	if (isset($input_data->td_longitude) != "") {
    		$data1['td_longitude']= $input_data->td_longitude;

    	}else {
    		$error = " Driver longitude is required";
    		goto end;
    	} 
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{
    		$t_trip_status = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_trip_status;
    		if($t_trip_status=="cancelled"){
    			$response = ["status"=>1,"message"=>"User Cancelled The Trip"]; 
    		}elseif($t_trip_status=="admin_cancel"){
    			$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_driver;
    			$trip_where=array("d_id"=>$db_otp);           
    			$trp_data = array('d_riding_status' =>'no');
    			$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);
    			$response = ["status"=>1,"message"=>"Admin Cancelled The Trip"]; 
    			$user_data = $this->trips_model->get_User_data($t_id);                        
    			if($user_data){
                        //driver notification
    				$n_data=array(
    					"n_user_id"=>$user_data['t_driver'],
    					"n_user_type"=>"driver",
    					"n_title"=>"Admin Cancelled The Trip",
    					"n_message"=>"Admin Cancelled The Trip",
    					"n_created_date"=> date('y-m-d'), 
    					"n_created_date_time"=> date('y-m-d H:i:s')
    				);
    				$this->comman_model->insert_record('all_notifications', $n_data);

                        //user notification
    				$n_data_user=array(
    					"n_user_id"=>$user_data['t_customer_id'],
    					"n_user_type"=>"user",
    					"n_title"=>"Admin Cancelled The Trip",
    					"n_message"=>"Admin Cancelled The Trip",
    					"n_created_date"=> date('y-m-d'), 
    					"n_created_date_time"=> date('y-m-d H:i:s')
    				);
    				$this->comman_model->insert_record('all_notifications', $n_data_user);

    			}

    		}
    		else{
           //Trip Table Update
    			$trip_where=array("t_id"=>$t_id, "t_driver"=>$data1['t_driver']);           
    			$trp_data = array('t_start_time' => $data1['t_start_time'],'t_trip_status' => $data1['t_trip_status'],'t_driver_fromlog' =>$data1['td_longitude'],'t_driver_fromlat' =>$data1['td_latitude']);
    			$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
    			if($update_trip){ 
               //notification update
    				$notification_where=array("n_trip_id"=>$t_id, "n_driver_id"=>$data1['t_driver']);           
    				$notification_data = array('n_trip_status' => $data1['t_trip_status']);
    				$update_trip = $this->comman_model->update('notification', $notification_where, $notification_data);
    				if($update_trip){
    					$t_payment_type=$this->db->select('*')->from('trips')->where('t_id',$t_id)->order_by('t_id','asc')->get()->row()->t_payment_type; 
    					$response = ["status"=>1,"message"=>"Trip start the Driver","payment_mode"=>$t_payment_type]; 
    				}else{
    					$response = ["status"=>0,"message"=>"Unable to Driver Start the Trip"]; 
    				}
    			}else{
    				$response = ["status"=>0,"message"=>"Unable to Driver Start the Trip"]; 
    			} 
    		}
    	}
    	echo json_encode($response);
    	exit(); 
    }
    
    public function pickup_loation_reahched_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
       $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */
        if(isset($input_data->t_id) != "") {
        	$t_id= $input_data->t_id;
        	$data1['t_reached_time']= date('y-m-d H:i:s');

        }else {
        	$error = "Trip id  is required";      
        	goto end;     
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        { 
        	$t_trip_status = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_trip_status;
        	if($t_trip_status=="cancelled"){
        		$response = ["status"=>1,"message"=>"User Cancelled The Trip"]; 
        	}elseif($t_trip_status=="admin_cancel"){
        		$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_driver;
        		$trip_where=array("d_id"=>$db_otp);           
        		$trp_data = array('d_riding_status' =>'no');
        		$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);
        		$response = ["status"=>1,"message"=>"Admin Cancelled The Trip"]; 
        		$user_data = $this->trips_model->get_User_data($t_id);                        
        		if($user_data){
                        //driver notification
        			$n_data=array(
        				"n_user_id"=>$user_data['t_driver'],
        				"n_user_type"=>"driver",
        				"n_title"=>"Admin Cancelled The Trip",
        				"n_message"=>"Admin Cancelled The Trip",
        				"n_created_date"=> date('y-m-d'), 
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data);

                        //user notification
        			$n_data_user=array(
        				"n_user_id"=>$user_data['t_customer_id'],
        				"n_user_type"=>"user",
        				"n_title"=>"Admin Cancelled The Trip",
        				"n_message"=>"Admin Cancelled The Trip",
        				"n_created_date"=> date('y-m-d'), 
        				"n_created_date_time"=> date('y-m-d H:i:s')
        			);
        			$this->comman_model->insert_record('all_notifications', $n_data_user);

        		}

        	}
        	else{
        		$reday_to_pickup="ready_to_pickup"; 
        		$trip_where=array("t_id"=>$t_id);           
        		$trip_data = array('t_trip_status' => $reday_to_pickup,'t_reached_time' => $data1['t_reached_time']);
        		$update_trip = $this->comman_model->update('trips', $trip_where, $trip_data);
        		if($update_trip){
        			$user_data = $this->trips_model->get_User_data($t_id);
        			if($user_data){  
        				$device_id=$user_data['c_device_token']; 
        				$title='Driver Reached Your Location Please Contact';
        				$message='Driver Name :'.$user_data['d_name'].'  Mobile No:'.$user_data['d_mobile'].'  Vechicle No:'.$user_data['v_registration_no'];
        				$this->comman_model->fcm_notification($device_id,$title,$message);

        				$user_data_info=array( 
        					"n_user_id"=>$user_data['t_customer_id'],
        					"n_user_type"=>"user", 
        					"n_title"=>"Cab Reached Your Location Please Contact",
        					"n_message"=>"Cab Reached Your Location Please Contact Driver",
        					"n_created_date"=> date('y-m-d'),
        					"n_created_date_time"=> date('y-m-d H:i:s')
        				);
        				$this->comman_model->insert_record('all_notifications', $user_data_info);
        			}

        			$response = ["status"=>1,"message"=>"Successfully Update"]; 
        		}else{
        			$response = ["status"=>0,"message"=>"Unable to Update"]; 
        		}
        	}
        }
        $this->set_response($response); 
    }
    // Trip end  Method
    public function trip_end__old_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
        /*
        $input_data = json_decode($json);
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        } */
        if (isset($input_data->trip_id) != "") {
        	$t_id= $input_data->trip_id;
        }else {
        	$error = "Trip id  is required";
        	goto end;
        }
        if (isset($input_data->driver_id) != "") {
        	$data1['t_driver']= $input_data->driver_id;
        }else {
        	$error = "Driver id  is required";
        	goto end;
        }
        if (isset($input_data->trip_status) != "") {
        	$data1['t_trip_status']= $input_data->trip_status;
        }else {
        	$error = " Trip status  is required";
        	goto end;
        } 
        if (isset($input_data->v_latitude) != "") {
        	$data1['td_latitude']= $input_data->v_latitude;
        }else {
        	$error = " Driver latitude  is required";
        	goto end;
        } 
        if (isset($input_data->v_longitude) != "") {
        	$data1['td_longitude']= $input_data->v_longitude;

        }else {
        	$error = " Driver longitude is required";
        	goto end;
        } 
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {
           //Trip Table Update
        	$trip_where=array("t_id"=>$t_id, "t_driver"=>$data1['t_driver']);           
        	$trp_data = array('t_trip_status' => $data1['t_trip_status'],'t_driver_fromlog' =>$data1['td_longitude'],'t_driver_fromlat' =>$data1['td_latitude']);
        	$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
        	if($update_trip){ 
               //notification update
        		$notification_where=array("n_trip_id"=>$t_id, "n_driver_id"=>$data1['t_driver']);           
        		$notification_data = array('n_trip_status' => $data1['t_trip_status']);
        		$update_trip = $this->comman_model->update('notification', $notification_where, $notification_data);
        		if($update_trip){
        			$response = ["status"=>1,"message"=>"Trip completed the Driver"]; 
        		}else{
        			$response = ["status"=>0,"message"=>"Unable to Driver completed the Trip"]; 
        		}
        	}else{
        		$response = ["status"=>0,"message"=>"Unable to Driver completed the Trip"]; 
        	}          
        }
        echo json_encode($response);
        exit();
    }
  // Trip end  Method
    public function trip_end_post(){  
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->trip_id) != "") {
    		$t_id= $input_data->trip_id;
    	}else {
    		$error = "Trip id  is required";
    		goto end;
    	}
    	if (isset($input_data->driver_id) != "") {
    		$data1['t_driver']= $input_data->driver_id;
    		$data1['t_end_date']= date("Y-m-d h:i:s:A");

    	}else {
    		$error = "Driver id  is required";
    		goto end;
    	}
    	if (isset($input_data->trip_status) != "") {
    		$data1['t_trip_status']= $input_data->trip_status;
    	}else {
    		$error = " Trip status  is required";
    		goto end;
    	} 
    	if (isset($input_data->v_latitude) != "") {
    		$data1['td_latitude']= $input_data->v_latitude;
    	}else {
    		$error = " Driver latitude  is required";
    		goto end;
    	} 
    	if (isset($input_data->v_longitude) != "") {
    		$data1['td_longitude']= $input_data->v_longitude;

    	}else {
    		$error = " Driver longitude is required";
    		goto end;
    	}
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{


           //Trip Table Update
    		$trip_where=array("t_id"=>$t_id, "t_driver"=>$data1['t_driver']);           
    		$trp_data = array('t_end_date'=>$data1['t_end_date'],'t_cash_payment'=>'completed','t_trip_status' => $data1['t_trip_status'],'t_driver_fromlog' =>$data1['td_longitude'],'t_driver_fromlat' =>$data1['td_latitude']);
    		$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
    		if($update_trip){ 
               //notification update
    			$notification_where=array("n_trip_id"=>$t_id, "n_driver_id"=>$data1['t_driver']);           
    			$notification_data = array('n_trip_status' => $data1['t_trip_status']);
    			$update_trip = $this->comman_model->update('notification', $notification_where, $notification_data);
    			$driver_where=array("d_id"=>$data1['t_driver']);           
    			$driver_data = array('d_riding_status' => 'no');
    			$update_trip = $this->comman_model->update('drivers', $driver_where, $driver_data);
    			if($update_trip){
    				$data=$this->db->select('*')->from('trips')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->where('t_id',$t_id)->order_by('t_id','asc')->get()->row_array();

    				if($data['t_trip_status']=='completed'){
    					$user_data = $this->trips_model->get_User_data($t_id);
                       //fcm customer 
    					$device_id=$user_data['d_device_token'];
    					$title='Dear Driver Your Trip Completed';
    					$message='Customer Name :'.$user_data['c_name'].'Mobile No : '.$user_data['c_mobile'];
    					$this->comman_model->fcm_notification($device_id,$title,$message);
    					$device_id=$user_data['c_device_token'];
    					$title='Dear User Your Trip Completed';
    					$message='Driver Name :'.$user_data['d_name'].'  From Location : '.$user_data['t_trip_fromlocation'].' '.'  To Location :'.$user_data['t_trip_fromlocation'];
                      // $message="User Booking for text";
    					$this->comman_model->fcm_notification($device_id,$title,$message);                        
    					if($user_data){
                        //driver notification
    						$n_data=array(
    							"n_user_id"=>$user_data['t_driver'],
    							"n_user_type"=>"driver",
    							"n_title"=>"Trip Completed",
    							"n_message"=>"Successfully completed Ride",
    							"n_created_date"=> date('y-m-d'), 
    							"n_created_date_time"=> date('y-m-d H:i:s')
    						);
    						$this->comman_model->insert_record('all_notifications', $n_data);

                        //user notification
    						$n_data_user=array(
    							"n_user_id"=>$user_data['t_customer_id'],
    							"n_user_type"=>"user",
    							"n_title"=>"Trip Completed",
    							"n_message"=>"Successfully completed your Ride",
    							"n_created_date"=> date('y-m-d'), 
    							"n_created_date_time"=> date('y-m-d H:i:s')
    						);
    						$this->comman_model->insert_record('all_notifications', $n_data_user);

    					}

    					$this->load->model('email_model');  
    					$gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Trip Completed')->get()->result_array();
    					if(!empty($gettemplate)) {
                            $emailcontent = $gettemplate[0]['et_body'];
                            $value = '<b>Trip Completed :</b><br><br> '.'<b>From</b><br>'.$data['t_trip_fromlocation']. ' <br><b>To</b><br> ' . $data['t_trip_tolocation']. ' <br><b>on</b><br> ' .$data['t_start_date'].'<br>'.'<b>Trip Amount:</b>'.$data['t_dyanamic_price'].'<br>'.'<b>Vehicle Type:</b>'.$data['v_type'].'<br>'.'<b>Driver Name:</b>'.$data['d_name'].'<br>'.'<br>'.'<b>Total Distance:</b>'.$data['t_dyanamic_distance'];
                            $body = str_replace('{{details}}', $value, $emailcontent);
                            $custemail=$this->db->select('*')->from('trips')->join('customers', 'customers.c_id = trips.t_customer_id')->where('t_id',$t_id)->order_by('t_id','asc')->get()->row()->c_email;
                            $email = $this->email_model->sendemail_end($custemail,$gettemplate[0]['et_subject'],$body);



                        }
                    }
                    $response = ["status"=>1,"message"=>"Trip completed the Driver"]; 

                }else{
                    $response = ["status"=>0,"message"=>"Unable to Driver completed the Trip"]; 
                }
            }else{
             $response = ["status"=>0,"message"=>"Unable to Driver completed the Trip"]; 
         }          

     }
     echo json_encode($response);
     exit(); 

 }  

    //  organization details get method   
 public function organization_get() {
   $data_where=array('org_isactive'=>1);
   $data= $this->comman_model->get_data_where('organization',$data_where);
   if($data){                
      $response = array('status'=>1,'organization_details'=>$data); 
  }else{                
      $response = array('status'=>0,'message'=>'Unable to get organization details details'); 
  }    

  $this->set_response($response);    
}

    //  app version details get method   
public function app_version_get() {
   $data=$this->db->select('*')->from('app_version')
   ->get()->row_array();
   if($data){                
      $response = array('status'=>1,'version_details'=>$data); 
  }else{                
      $response = array('status'=>0,'message'=>'Unable to get version details details'); 
  }    

  $this->set_response($response);    
}

    //  total trip count get method   
public function total_trips_post() {
   $json = file_get_contents('php://input');
   $input_data = json_decode($json);
   $error = "";
   if (isset($input_data->t_driver) != "") {
      $t_driver= $input_data->t_driver;
  }else {
      $error = "Driver id  is required";
      goto end;
  }
  end:
  if($error !="")
  {
      $response = ["status"=>0,"message"=>$error];
  }
  else
  {
      $data=$this->db
      ->where('t_trip_status','completed')
      ->where('t_driver', $t_driver) 
      ->count_all_results('trips');
      if($data){                
         $response = array('status'=>1,'total_jobs'=>$data); 
     }else{                
         $response = array('status'=>0,'message'=>'Unable to get total jobs'); 
     }    

     $this->set_response($response);    
 }
}
    //  total distance  get method   
public function total_distance_post() { 
   $json = file_get_contents('php://input');
   $input_data = json_decode($json);
   $error = "";
   if (isset($input_data->t_driver) != "") {
      $t_driver= $input_data->t_driver;
  }else {
      $error = "Driver id  is required";
      goto end;
  }
  end:
  if($error !="")
  {
      $response = ["status"=>0,"message"=>$error];
  }
  else
  {
      $data=$this->db->select('sum(t_dyanamic_distance)')->from('trips')
      ->where('t_trip_status','completed')
      ->where('t_driver', $t_driver)
      ->group_by('t_driver')
      ->get()->row_array();
      if($data){                
         $response = array('status'=>1,'total_distance'=>round($data['sum(t_dyanamic_distance)'])); 
     }else{                
         $response = array('status'=>0,'message'=>'Unable to get total distance'); 
     }    

     $this->set_response($response);    
 }
}
    //  Vechile group
public function vechile_group_get(){       
   $query = $this->db->get('vehicle_group');  
   $vehicle_group_data= $query->result();
   if($vehicle_group_data){
      $response = array('status'=>1,'vechile_group_info'=>$vehicle_group_data); 
  }else{
      $response = array('status'=>0,'message'=>'Unable to get Vechicle grou['); 
  }
  $this->set_response($response);
}

     // Add Trip Payment  Method
public function add_trip_payments_post(){
   $json = file_get_contents('php://input');
   $input_data = json_decode($json);

   $error="";
   if (isset($input_data->t_id) != "") {
      $data['tp_trip_id']= $input_data->t_id;
      $t_id= $input_data->t_id;
  }else {
      $error = " Trip  id  is required";
      goto end;
  }
  if (isset($input_data->tp_payment_amount) != "") {
      $data['tp_payment_amount']= $input_data->tp_payment_amount;
      $data['tp_payment_date_time']= date('y/m/d h:i:s:A');
      $data['tp_created_date']= date('y-m-d H:i:s');
      $data['tp_payment_transaction_id'] = uniqid(time());
      $data['tp_orderkey_id'] = uniqid(time());
      $data['tp_unique_request_id'] = uniqid(time());
      $data['tp_payment_transaction_refno'] = uniqid(time());
  }else {
      $error = "Amount is required";
      goto end;
  }
  if (isset($input_data->tp_payment_method_type) != "") {
      $data['tp_payment_method_type']= $input_data->tp_payment_method_type;
  }else {
      $error = "Payment Type required";
      goto end;
  }
  if (isset($input_data->tp_payment_status) != "") {
      $data['tp_payment_status']= $input_data->tp_payment_status;
  }else {
      $error = "Payment Staus required";
      goto end;
  }
  if (isset($input_data->tp_payment_transaction_id) != "") {
      $data['tp_payment_transaction_id']= $input_data->tp_payment_transaction_id;
  }else {
      $error = "Payment Transaction Id   is required";
      goto end;
  } 

  end:
  if($error !="")
  {
      $response = ["status"=>0,"message"=>$error];
  }
  else
  {

      $ql = $this->db->select('tp_trip_id')->from('trip_payments')->where('tp_trip_id',$t_id)->get();

            // print_r($ql->num_rows());
            // exit();
      if($ql->num_rows()!=0){
         $trip_where=array("tp_trip_id"=>$t_id);           
         $trp_data = array('tp_payment_amount' =>$data['tp_payment_amount'],'tp_created_date' =>$data['tp_created_date'],'tp_payment_date_time' =>$data['tp_payment_date_time'],'tp_payment_transaction_id' =>$data['tp_payment_transaction_id'],'tp_payment_method_type' =>$data['tp_payment_method_type']);
         $update_trip = $this->comman_model->update('trip_payments', $trip_where, $trp_data);  
         if($update_trip){
            $payment_status = $this->db->select('*')->from('trip_payments')->where('tp_trip_id',$t_id)->get()->row()->tp_payment_status;
            $data=$this->db->select('*')->from('trips')->join('customers', 'customers.c_id = trips.t_customer_id')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->join('trip_payments', 'trip_payments.tp_trip_id = trips.t_id')->where('t_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row_array();
            $this->load->model('email_model');  
            $gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Payment')->get()->result_array();
            if(!empty($gettemplate)) {
               $emailcontent = $gettemplate[0]['et_body']; 
               $value = '<b>Dear '.$data['c_name'].' Your Payment Successfully Completed :</b><br><br> ' .'<b>From</b><br>'.$data['t_trip_fromlocation']. ' <br><b>To</b><br> ' . $data['t_trip_tolocation']. ' <br><b>on</b><br> ' .$data['t_start_date'].'<br>'.'<b>Trip Amount:</b>'.$data['tp_payment_amount'].'<br>'.'<br>'.'<b>Vehicle Type:</b>'.$data['v_type'].'<br>'.'<b>Driver Name:</b>'.$data['d_name'].'<br>'.'<br>'.'<b>Total Distance:</b>'.$data['t_dyanamic_distance'].'<br>'.'<b>Transaction Order ID:</b>'.$data['tp_orderkey_id'].'<br>'.'<b>Transaction Type:</b>'.$data['tp_payment_method_type'].'<br>'.'<b>Transaction Date:</b>'.$data['tp_payment_date_time'];
              
               $body = str_replace('{{details}}', $value, $emailcontent);
               $custemail=$this->db->select('*')->from('trip_payments')->join('trips', 'trips.t_id = trip_payments.tp_trip_id')->join('customers', 'customers.c_id = trips.t_customer_id')->where('tp_trip_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row()->c_email;
               $email = $this->email_model->sendemail_password($custemail,$gettemplate[0]['et_subject'],$body);

           }
           $response = ["status"=>1,"message"=>"Trip Payment Update successfully","payment_status"=>$payment_status]; 

       }
   }
            //insert trip Payment details

   else{
     $insert_id = $this->comman_model->insert_record('trip_payments',$data);
     if($insert_id){
        $payment_status = $this->db->select('*')->from('trip_payments')->where('tp_trip_id',$t_id)->get()->row()->tp_payment_status;
        $data=$this->db->select('*')->from('trips')->join('customers', 'customers.c_id = trips.t_customer_id')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->join('trip_payments', 'trip_payments.tp_trip_id = trips.t_id')->where('t_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row_array();
        $this->load->model('email_model');  
        $gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Payment')->get()->result_array();
        if(!empty($gettemplate)) {
           $emailcontent = $gettemplate[0]['et_body']; 
           $value = '<b>Dear '.$data['c_name'].' Your Payment Successfully Completed :</b><br><br> ' .'<b>From</b><br>'.$data['t_trip_fromlocation']. ' <br><b>To</b><br> ' . $data['t_trip_tolocation']. ' <br><b>on</b><br> ' .$data['t_start_date'].'<br>'.'<b>Trip Amount:</b>'.$data['tp_payment_amount'].'<br>'.'<b>Vehicle Type:</b>'.$data['v_type'].'<br>'.'<b>Driver Name:</b>'.$data['d_name'].'<br>'.'<b>Total Distance:</b>'.$data['t_dyanamic_distance'].'<br>'.'<b>Transaction Date:</b>'.$data['tp_payment_date_time'];
           $body = str_replace('{{details}}', $value, $emailcontent);
           $custemail=$this->db->select('*')->from('trip_payments')->join('trips', 'trips.t_id = trip_payments.tp_trip_id')->join('customers', 'customers.c_id = trips.t_customer_id')->where('tp_trip_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row()->c_email;
           $email = $this->email_model->sendemail_password($custemail,$gettemplate[0]['et_subject'],$body);
                         //FCM Integration
           $user_data = $this->trips_model->get_User_data($t_id);
           $device_id=$user_data['c_device_token'];
           $title='Payment Successfully Completed';
           $message='User Name :'.$user_data['c_name'];
           $this->comman_model->fcm_notification($device_id,$title,$message);

                            //nofication table insert notification
           $n_data=array(
              "n_user_id"=>$user_data['d_id'],
              "n_user_type"=>"driver",
              "n_title"=>"Payment Successfully Completed",
              "n_message"=>"Payment Successfully Completed by ". $user_data['c_name'],
              "n_created_date"=> date('y-m-d'),
              "n_created_date_time"=> date('y-m-d H:i:s')
          );
           $this->comman_model->insert_record('all_notifications', $n_data);

       }
       $response = ["status"=>1,"message"=>"Trip Payment added successfully"]; 

   }
   else{
    $response = ["status"=>0,"message"=>"Unable to add Trip Payment"]; 
}
}          

}
$this->set_response($response); 

}
    //  Time Out   method   
public function time_out_post() {  
   $json = file_get_contents('php://input');
   $input_data = json_decode($json);
   $error = "";
   if (isset($input_data->t_id) != "") {
      $t_id= $input_data->t_id;
  }else {
      $error = "Trip id  is required";
      goto end;
  }
  end:
  if($error !="")
  {
      $response = ["status"=>0,"message"=>$error];
  }
  else
  {
      $trip_where=array("t_id"=>$t_id);           
      $trp_data = array('t_trip_status' =>'session_out');
      $update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);         
      if($update_trip){
         $trip_where1=array("n_trip_id"=>$t_id);
         $update_trip2 = $this->comman_model->delete_row('notification', $trip_where1);
         if($update_trip2){
            $response = array('status'=>1,'message'=>'session out');
        }else{
            $response = array('status'=>0,'message'=>'Unable Upadte session out'); 
        }
    }else{                
     $response = array('status'=>0,'message'=>'Unable Upadte session out'); 
 }    


}
$this->set_response($response);
}

    //get nofication user wise 
public function notification_data_post(){ 
   $json = file_get_contents('php://input');
   $input_data = json_decode($json);
   $error = "";
   $response="";
   if (isset($input_data->n_user_type) != "") { 
      $n_user_type= $input_data->n_user_type;
  }else {
      $error = "User Type  is required";
      goto end;
  }if (isset($input_data->n_user_id) != "") {
      $n_user_id= $input_data->n_user_id;
  }else {
      $error = "User id  is required";
      goto end;
  }
  end:
  if($error !="")
  {
      $response = ["status"=>0,"message"=>$error];         

  }
  else
  {

      $data=array("n_user_id"=>$n_user_id,"n_user_type"=>$n_user_type,"n_created_date"=>date('y-m-d '));
      $table="all_notifications";
      $this->db->select('*');
      $this->db->from($table);
      $this->db->where($data); 
      $this->db->order_by("all_notifications.n_id", "desc");
      $query = $this->db->get();
            if($query->num_rows() > 0) //counting result from query
            {
            	$nofication_data = $query->result_array();  
            	if($nofication_data){
            		$response = array('status'=>1,'message'=>'Successfully get Notification data',"notification_data"=>$nofication_data,"total_notifications"=>count($nofication_data)); 
            	}else{
            		$response = array('status'=>0,'message'=>'there no notification'); 
            	}
            }else{
            	$response = array('status'=>0,'message'=>'there no notification'); 
            }
        }

        $this->set_response($response);  
    }



    //get nofication user wise 
    public function coupons_get(){

            // $data=array("cu_end_date"=>date('y-m-d'));
        $table="coupons";
        $this->db->select('*');
        $this->db->select("CONCAT_WS(' ', coupons.cu_name, coupons.discount) AS coupon_name",FALSE);
        $this->db->from($table);
            // $this->db->where($data); 
        $this->db->where('coupons.cu_end_date >=',date('y-m-d'));
        $this->db->order_by("coupons.cu_id", "desc");
        $query = $this->db->get();
            if($query->num_rows() > 0) //counting result from query
            {
                $coupons_data = $query->result_array();  
                if($coupons_data){
                    $response = array('status'=>1,'message'=>'Successfully get Coupons data',"coupons_data"=>$coupons_data,"total_coupons"=>count($coupons_data)); 
                }else{
                    $response = array('status'=>0,'message'=>'there is no Coupons'); 
                }
            }else{
                $response = array('status'=>0,'message'=>'there is no Coupons'); 
            }


            $this->set_response($response);  
        }


       //  Payment Type Update  method   
        public function discount_post() { 
            $json = file_get_contents('php://input');
            $input_data = json_decode($json);
            $error = "";
            if (isset($input_data->total_amount) != "") {
                $total_amount= $input_data->total_amount;
            }else {
                $error = "total amount is required";
                goto end;
            }
            if (isset($input_data->discount) != "") {
                $discount= $input_data->discount;
            }else {
                $error = "Trip discount is required";
                goto end;
            }
             if (isset($input_data->cu_type) != "") {
                $cu_type= $input_data->cu_type;
            }else {
                $error = "Trip discount is required";
                goto end;
            }
            end:
            if($error !="")
            {
                $response = ["status"=>0,"message"=>$error];
            }
            else
            {
                if($total_amount>="100" ){
                if($cu_type=="Percentage"){
                $selling_price = $total_amount- ($total_amount * ($discount / 100)); 
            }else{
                 $selling_price = $total_amount- $discount; 
            }
        }else{
             $selling_price = $total_amount;
        }

                if($selling_price){
                    $response = array('status'=>1,'selling_price'=>round($selling_price));
                }else{
                    $response = array('status'=>0,'message'=>'Unable calculated discount'); 
                }

            }    

            $this->set_response($response);    

        }
        //  Cash Payment   method   
        public function cash_payment_post() {
           $json = file_get_contents('php://input');
           $input_data = json_decode($json);
           $error = "";
           if (isset($input_data->t_id) != "") {
              $data['tp_trip_id']= $input_data->t_id;
          }else {
              $error = "Trip id  is required";
              goto end;
          }
          if (isset($input_data->tp_payment_amount) != "") {
              $data['tp_payment_amount']= $input_data->tp_payment_amount;
              $data['tp_payment_status']= '1';
              $data['tp_payment_method_type']= 'Cash';
              $data['tp_payment_date_time']= date('y/m/d h:i:s:A');
              $data['tp_payment_transaction_id'] = uniqid(time());
              $data['tp_orderkey_id'] = uniqid(time());
              $data['tp_unique_request_id'] = uniqid(time());
              $data['tp_payment_transaction_refno'] = uniqid(time());
          }else {
              $error = "Amount is required";
              goto end;
          }
          end:
          if($error !="")
          {
              $response = ["status"=>0,"message"=>$error];
          }
          else
              {            $ql = $this->db->select('tp_trip_id')->from('trip_payments')->where('tp_trip_id',$data['tp_trip_id'])->get();

            // print_r($ql->num_rows());
            // exit();
          if($ql->num_rows()!=0){
              $trip_where=array("tp_trip_id"=>$data['tp_trip_id']);           
              $trp_data = array('tp_payment_amount' =>$data['tp_payment_amount'],'tp_payment_date_time' =>$data['tp_payment_date_time'],'tp_payment_transaction_refno' =>$data['tp_payment_transaction_refno'],'tp_payment_status' =>$data['tp_payment_status'],'tp_unique_request_id' =>$data['tp_unique_request_id'],'tp_orderkey_id' =>$data['tp_orderkey_id'],'tp_payment_method_type' =>$data['tp_payment_method_type']);
              $update_trip = $this->comman_model->update('trip_payments', $trip_where, $trp_data);  
              if($update_trip){
                 $data=$this->db->select('*')->from('trips')->join('customers', 'customers.c_id = trips.t_customer_id')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->join('trip_payments', 'trip_payments.tp_trip_id = trips.t_id')->where('t_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row_array();
                 $this->load->model('email_model');  
                 $gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Payment')->get()->result_array();
                 if(!empty($gettemplate)) {
                    $emailcontent = $gettemplate[0]['et_body']; 
                    $value = '<b>Dear '.$data['c_name'].' Your Payment Successfully Completed :</b><br><br> ' .'<b>From</b><br>'.$data['t_trip_fromlocation']. ' <br><b>To</b><br> ' . $data['t_trip_tolocation']. ' <br><b>on</b><br> ' .$data['t_start_date'].'<br>'.'<b>Trip Amount:</b>'.$data['tp_payment_amount'].'<br>'.'<br>'.'<b>Vehicle Type:</b>'.$data['v_type'].'<br>'.'<b>Driver Name:</b>'.$data['d_name'].'<br>'.'<br>'.'<b>Total Distance:</b>'.$data['t_dyanamic_distance'].'<br>'.'<b>Transaction Order ID:</b>'.$data['tp_orderkey_id'].'<br>'.'<b>Transaction Type:</b>'.$data['tp_payment_method_type'].'<br>'.'<b>Transaction Date:</b>'.$data['tp_payment_date_time'];
                    $body = str_replace('{{details}}', $value, $emailcontent);
                    $custemail=$this->db->select('*')->from('trip_payments')->join('trips', 'trips.t_id = trip_payments.tp_trip_id')->join('customers', 'customers.c_id = trips.t_customer_id')->where('tp_trip_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row()->c_email;
                    $email = $this->email_model->sendemail_password($custemail,$gettemplate[0]['et_subject'],$body);

                }
                $response = ["status"=>1,"message"=>"Trip Payment Update successfully"]; 

            }
        }else{


          $update_trip = $this->comman_model->insert_record('trip_payments',$data); 


          if($update_trip){
             $data=$this->db->select('*')->from('trips')->join('customers', 'customers.c_id = trips.t_customer_id')->join('drivers', 'drivers.d_id = trips.t_driver')->join('vehicles', 'vehicles.v_id = trips.t_vechicle')->join('trip_payments', 'trip_payments.tp_trip_id = trips.t_id')->where('t_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row_array();


             $this->load->model('email_model');  
             $gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Payment')->get()->result_array();
             if(!empty($gettemplate)) {
                $emailcontent = $gettemplate[0]['et_body']; 
                $value = '<b>Your Payment Successfully Completed </b><br> ';
               $value = '<b>Dear '.$data['c_name'].' Your Payment Successfully Completed :</b><br><br> ' .'<b>From</b><br>'.$data['t_trip_fromlocation']. ' <br><b>To</b><br> ' . $data['t_trip_tolocation']. ' <br><b>on</b><br> ' .$data['t_start_date'].'<br>'.'<b>Trip Amount:</b>'.$data['tp_payment_amount'].'<br>'.'<br>'.'<b>Vehicle Type:</b>'.$data['v_type'].'<br>'.'<b>Driver Name:</b>'.$data['d_name'].'<br>'.'<br>'.'<b>Total Distance:</b>'.$data['t_dyanamic_distance'].'<br>'.'<b>Transaction Order ID:</b>'.$data['tp_orderkey_id'].'<br>'.'<b>Transaction Type:</b>'.$data['tp_payment_method_type'].'<br>'.'<b>Transaction Date:</b>'.$data['tp_payment_date_time'];
                $body = str_replace('{{details}}', $value, $emailcontent);
                $custemail=$this->db->select('*')->from('trip_payments')->join('trips', 'trips.t_id = trip_payments.tp_trip_id')->join('customers', 'customers.c_id = trips.t_customer_id')->where('tp_trip_id',$data['tp_trip_id'])->order_by('t_id','asc')->get()->row()->c_email;
                $email = $this->email_model->sendemail_password($custemail,$gettemplate[0]['et_subject'],$body,$data['c_name']);
            } 
            $response = ["status"=>1,"message"=>"Trip Payment added successfully"];


        }else{
         $response = ["status"=>0,"message"=>"Unable to add Trip Payment"]; 
     } 
 }
 $this->set_response($response);  
}


}

    //  Payment Type Update  method   
public function payment_type_update_post() { 
	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
	$error = "";
	if (isset($input_data->t_id) != "") {
		$t_id= $input_data->t_id;
	}else {
		$error = "Trip id  is required";
		goto end;
	}
	if (isset($input_data->t_payment_type) != "") {
		$t_payment_type= $input_data->t_payment_type;
	}else {
		$error = "Trip Payment Type  is required";
		goto end;
	}
	end:
	if($error !="")
	{
		$response = ["status"=>0,"message"=>$error];
	}
	else
	{
		$trip_where=array("t_id"=>$t_id);           
		$trp_data = array('t_payment_type' =>$t_payment_type,'t_cash_payment' =>'processing');
		$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);        
		if($update_trip){
			$response = array('status'=>1,'message'=>'Payment Type Upadte successfully');
		}else{
			$response = array('status'=>0,'message'=>'Unable Upadte Payment Type'); 
		}

	}    

	$this->set_response($response);    

}




    //  Trip Status check  method   
public function trip_status_check_post() { 
	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
	$error = "";
	if (isset($input_data->t_id) != "") {
		$t_id= $input_data->t_id;
	}else {
		$error = "Trip id  is required";
		goto end;
	}
	end:
	if($error !="")
	{
		$response = ["status"=>0,"message"=>$error];
	}
	else
	{
		$t_trip_status = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_trip_status;
		if($t_trip_status=="cancelled"){
			$response = ["status"=>1,"message"=>"Driver Cancelled The Trip"]; 
		}elseif($t_trip_status=="admin_cancel"){
			$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_driver;
			$trip_where=array("d_id"=>$db_otp);           
			$trp_data = array('d_riding_status' =>'no');
			$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);
			$response = ["status"=>1,"message"=>"Admin Cancelled The Trip"]; 

		}
		else{
			$response = ["status"=>1,"message"=>"Trip is Alive"];
		}

	}    

	$this->set_response($response);    

}
    // get the user invoice
public function user_invoice_post() { 
	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
	$error="";
	if (isset($input_data->c_id) != "") {
		$c_id= $input_data->c_id;
	}else {
		$error = "Customer id  is required";        
	}
	if (isset($input_data->t_id) != "") {
		$t_id= $input_data->t_id;
	}else {
		$error = "Trip id  is required";        
	}
	end:
	if($error !="")
	{
		$response = ["status"=>0,"message"=>$error];
	}

	else
	{
		$this->db->select('*,sum(trips.t_dyanamic_price) + sum(trips.t_d_waiting_amount) AS total_amount' );
		$this->db->from('customers');
		$this->db->join('trips', 'trips.t_customer_id=customers.c_id');
		$this->db->join('drivers', 'drivers.d_id=trips.t_driver');
		$this->db->join('trip_payments', 'trip_payments.tp_trip_id=trips.t_id');
		$this->db->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id');
		$this->db->where('trips.t_trip_status','completed'); 
		$this->db->where('trips.t_customer_id',$c_id);
		$this->db->where('trips.t_id',$t_id);
		$this->db->order_by("trips.t_id", "desc");
		$query = $this->db->get(); 
		$query_result= $query->result();
		if($query_result){
			$response = array('status'=>1,'user_invoice_details'=>$query_result);
		}else{
			$response = array('status'=>0,'message'=>'Unable to Get User invoice'); 
		}
	}
	$this->set_response($response);
} 
    //  Privacy Policy get  method   
public function privacy_policy_get() { 
	$this->load->view('privacy_policy_view');
}

//  Privacy Policy get  method   
public function share_get($d) { 
  

    $json = file_get_contents('php://input');
    $input_data = json_decode($json);
    $error = "";
     $t_id= $d;
    // if (isset($input_data->t_id) != "") {
    //    // $t_id= $input_data->t_id;
    //     $t_id= $d;
    // }else {
    //     $error = "Trip id  is required";
    //     goto end;
    // }
    // end:
    if($error !="")
    {
        $response = ["status"=>0,"message"=>$error];
    }
    else
    {
        $data['d'] = $this->db->select('s_googel_api_key')->from('settings')->get()->result_array();
        $data['data'] = $this->db->select('*')->from('trips')->join('drivers', 'drivers.d_id=trips.t_driver','left')->join('vehicles', 'vehicles.v_driver_id=drivers.d_id','left')->where('t_id',$t_id)->get()->row_array();
       
      $this->load->view('share_view',$data);

    } 
   
}


    //  Trip Otp check  method   
public function trip_otp_check_post() { 
	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
	$error = "";
	if (isset($input_data->t_id) != "") {
		$t_id= $input_data->t_id;
	}else {
		$error = "Trip id  is required";
		goto end;
	}
	if (isset($input_data->t_otp) != "") {
		$t_otp= $input_data->t_otp;
	}else {
		$error = "Trip Otp  is required";
		goto end;
	}
	end:
	if($error !="")
	{
		$response = ["status"=>0,"message"=>$error];
	}
	else
	{
		$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_otp;
		if($db_otp==$t_otp){
			$response = ["status"=>1,"message"=>"Otp matched successfully"]; 
		}else{
			$response = ["status"=>0,"message"=>"otp wrong"];

		}

	}    

	$this->set_response($response);    

}

    //  Trip Otp resend  method   
public function trip_otp_resend_post() { 
	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
	$error = "";
	if (isset($input_data->t_id) != "") {
		$t_id= $input_data->t_id;
		$data['t_otp'] = rand(1000, 1000000);
	}else {
		$error = "Trip id  is required";
		goto end;
	}
	end:
	if($error !="")
	{
		$response = ["status"=>0,"message"=>$error];
	}
	else
	{
		$trip_where=array("t_id"=>$t_id);           
		$trp_data = array('t_otp' =>$data['t_otp']);
		$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);        
		if($update_trip){
			$response = array('status'=>1,'message'=>'Otp Upadte successfully');
		}else{
			$response = array('status'=>0,'message'=>'Unable Upadte Otp '); 
		}

	}    

	$this->set_response($response);    

}




 // to calucalte the distance and amount for digital meter 
public function distance_post () {

	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
	$error = "";
	if (isset($input_data->t_id) != "") {
		$t_id= $input_data->t_id;
	}else {
		$error = "Trip id  is required";
		goto end;
	}
	if (isset($input_data->to_lat) != "") {
		$to_lat= $input_data->to_lat;
	}else {
		$error = "To latitude is required";
		goto end;
	}
	if (isset($input_data->to_long) != "") {
		$to_long= $input_data->to_long;
	}else {
		$error = "To longitude  is required";
		goto end;
	}
	end:
	if($error !="")
	{
		$response = ["status"=>0,"message"=>$error];
	}
	else
	{

		$lat = $this->db->select('t_trip_fromlat,t_trip_fromlog,gr_price,t_driver,t_vechicle,t_show_meter_distance')->from('trips')->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id','left')->where('t_id',$t_id)->get()->row_array();

		if($lat['t_show_meter_distance']==0.00){

			$latitudeFrom =$lat['t_trip_fromlat'];
			$longitudeFrom =$lat['t_trip_fromlog'];
			$latitudeTo = $to_lat;
			$longitudeTo = $to_long;
		}else{
			$last_row=$this->db->select('*')->order_by('id',"desc")->limit(1)->where('v_id',$lat['t_vechicle'])->get('positions')->row();

			$latitudeFrom =$last_row->latitude;
			$longitudeFrom =$last_row->longitude;
			$latitudeTo = $to_lat;
			$longitudeTo = $to_long;

		}


// ///Calculate distance from latitude and longitude
// $theta = $longitudeFrom - $longitudeTo;
// $dist = sin(deg2rad($latitudeFrom))*sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
// $dist = acos($dist);
// $dist = rad2deg($dist);
// $miles = $dist  *60  *1.1515;

// $distance = ($miles * 1.609344);
		$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$latitudeFrom.",".$longitudeFrom."&destinations=".$latitudeTo.",".$longitudeTo."&key=AIzaSyByZMqOPxhY92T-AxAhSuwiTyfSBKnKAO8";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		$response = curl_exec($ch);
		curl_close($ch);
		$response_a = json_decode($response, true);


		$status = "ERROR"; 
		$dist   = 0;
		$time   = 0;
		if($response_a['rows'][0]['elements'][0]['status'] === 'OK') {
			$dist   = $response_a['rows'][0]['elements'][0]['distance']['value'];
			$time   = $response_a['rows'][0]['elements'][0]['duration']['text'];
			$status = "OK";
		}
// $d=trim($dist,"km");

		$distance=$dist/1000;
		$this->show_meter_post($lat['t_vechicle'],$latitudeTo,$longitudeTo,$t_id);
		$this->meter_price_post($distance,$lat['t_driver'],$t_id);
// $distance = ($miles * 1.609344);
// $meters=$distance*1000;

	}    



}


//Driver postion insert into database
public function show_meter_post($v_id,$latitude,$longitude,$t_id){
        // $json = file_get_contents('php://input');
        // $input_data = json_decode($json);
       // $token = $input_data->token;
         $error="";/*$token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        }        */ 
        if(isset($v_id) != ""){  
        	$data['v_id']= $v_id;
        	$vid= $v_id;
        }else{
        	$error = "Vehicle Id is required";
        	goto end;
        }
        if(isset($t_id) != ""){  
        	$t_id= $t_id;

        }else{
        	$t_id= '0';
        }
        if(isset($latitude) != ""){
        	$data['latitude']= $latitude;
        	$lat= $latitude;

        }else{
        	$error = "latitude is required";
        	goto end; 
        }
        if(isset($longitude) != ""){
        	$data['longitude']= $longitude;
        	$lon= $longitude;

        }else{
        	$error = "longitude is required";
        	goto end;
        }
        end:
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {     

        	$result_data = $this->comman_model->insert_record('positions',$data);      
        	$data1= $this->db->select('*')->from('wait_time')->where('w_t_id',$t_id)->where('w_v_id',$vid)->order_by('w_id','desc')->limit(1)->get()->row_array();
            // $result_data = $this->comman_model->insert_record('positions',$data);

        	if($data1==""){

                // die('ji');
        		if($t_id>0){
        			$insert1['w_lat']=$data['latitude'];
        			$insert1['w_long']=$data['longitude'];
        			$insert1['w_t_id']=$t_id;
                // $data['w_time']=date('Y-m-d h:i:s');
        			$insert1['w_v_id']=$vid;
        			$insert1['w_date']=date('Y-m-d h:i:s');

        			$result_data = $this->comman_model->insert_record('wait_time',$insert1);
        		}

        	}else{

        		if($t_id>0){
        			$lat= $this->db->select('*')->from('wait_time')->where('w_v_id',$vid)->where('w_t_id',$t_id)->order_by('w_id','desc')->limit(1)->get()->row_array(); 


        			$latitudeFrom =$lat['w_lat'];
        			$longitudeFrom =$lat['w_long'];
        			$latitudeTo = $data['latitude'];
        			$longitudeTo = $data['longitude'];

        			$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$latitudeFrom.",".$longitudeFrom."&destinations=".$latitudeTo.",".$longitudeTo."&key=AIzaSyByZMqOPxhY92T-AxAhSuwiTyfSBKnKAO8";
        			$ch = curl_init();
        			curl_setopt($ch, CURLOPT_URL, $url);
        			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        			curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        			$response = curl_exec($ch);
        			curl_close($ch);
        			$response_a = json_decode($response, true);


        			$status = "ERROR"; 
        			$dist   = 0;
        			$time   = 0;
        			if($response_a['rows'][0]['elements'][0]['status'] === 'OK') {
        				$dist   = $response_a['rows'][0]['elements'][0]['distance']['value'];
        				$time   = $response_a['rows'][0]['elements'][0]['duration']['text'];
        				$status = "OK";
        			}
// $d=trim($dist,"km");

        			$meters=$dist/1000;
// $meters=$distance*1000;

        			if($meters>0.008){
        				$insert['w_lat']=$data['latitude'];
        				$insert['w_long']=$data['longitude'];
        				$datetime=$lat['w_date'];
        				$insert['w_t_id']=$t_id;
        				$insert['w_v_id']=$vid;
        				$insert['w_date']=date('Y-m-d h:i:s');
        				$currentdate=date('Y-m-d h:i:s');
        				$datetime1 = new DateTime($datetime);
        				$datetime2 = new DateTime($currentdate);
        				$interval = $datetime1->diff($datetime2);
            // $a=strtotime($interval);
        				$time=$interval->format('%h:%i:%s');
        				$timesplit=explode(':',$time);
        				$min=($timesplit[0]*60)+($timesplit[1])+($timesplit[2]>30?1:0);
        				$seconds=$min*60;



        				if($seconds>8){
        					$insert['w_time']=gmdate("H:i:s",$seconds);
                // $insert['w_time']=$min;


        					$insert['w_status']='1';
        					$result_data = $this->comman_model->insert_record('wait_time',$insert);
        				}else{
        					$result_data = $this->comman_model->insert_record('wait_time',$insert);
        				}

        			}else{

               // $data['w_lat']=$lat;
               //  $data['w_long']=$lon;
               //  // $data['w_time']=date('Y-m-d h:i:s');
               //  $data['w_v_id']=$vid;
               //  $data['w_date']=date('Y-m-d h:i:s');

               //  $result_data = $this->comman_model->insert_record('wait_time',$data);


        			}


        		}






        	}

            // $result_data = $this->comman_model->insert_record('positions',$data); 
        	if($result_data){

        		$vechile_details=$this->db->select('*')->from('vehicles')->join('vehicle_type', 'vehicle_type.vt_group = vehicles.v_group')->group_by('vehicles.v_group')->where('v_id',$vid)->order_by('id','desc')->get()->result();
        		foreach($vechile_details as $row){
        			$row->img_path= $local_path=$this->config->base_url().'assets/uploads/'.$row->image;
        		} 
                //check geo fencing 
        		$this->check_geo_fencing($vid,$latitude,$longitude);
        		$response = ["status"=>0,"message"=>'Successfully Updated position',"details"=>$vechile_details];
        	}else{
        		$response = ["status"=>0,"message"=>'Unable to Update position'];
        	}
        }
        $this->set_response($response);

    }


//  User Forgot Password  method
    public function customer_forgot_password_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error="";
    	if (($input_data->c_email) != "") {
    		$data['c_email']= $input_data->c_email;
    	} else {
    		$error = "Email Id is required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else
    	{
            //NEW CODE
    		$email = $this->db->select('*')->from('customers')->where('c_email',$data['c_email'])->get()->row_array();
    		if($email['c_email']==$data['c_email']){
    			$trip_where=array("c_email"=>$data['c_email']);
    			$data['c_otp'] = rand(1000, 1000000);           
    			$trp_data = array('c_otp' =>$data['c_otp']);
    			$update_trip = $this->comman_model->update('customers', $trip_where, $trp_data);
    			if($update_trip){
    				$this->load->model('email_model');  
    				$gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Forgotpassword')->get()->result_array();
    				if(!empty($gettemplate)) {
    					$emailcontent = $gettemplate[0]['et_body'];
    					$value = '<b>Your OTP :</b> '.$data['c_otp'];
    					$body = str_replace('{{details}}', $value, $emailcontent);
    					$custemail = $data['c_email'];
    					$email = $this->email_model->sendemail_password($custemail,$gettemplate[0]['et_subject'],$body);
    				} 

    				$result = ["status"=>1,"message"=>"OTP sent to registered email id"];
    			}else{
    				$result = ["status"=>1,"message"=>"Unable to  send otp to registered email id"];
    			}

    		}else{
    			$result = ["status"=>0,"message"=>"Please Enter valid Email"];
    		}   
    	}
    	$this->set_response($result); 

    }

     //  Forgot Password  Otp check  method   
    public function forgot_otp_check_post() { 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->c_email) != "") {
    		$c_email= $input_data->c_email;
    	}else {
    		$error = "Email  is required";
    		goto end;
    	}
    	if (isset($input_data->c_otp) != "") {
    		$c_otp= $input_data->c_otp;
    	}else {
    		$error = "Customer Otp  is required";
    		goto end;
    	}
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{
    		$db_otp = $this->db->select('*')->from('customers')->where('c_email',$c_email)->get()->row()->c_otp;
    		if($db_otp==$c_otp){
    			$response = ["status"=>1,"message"=>"Otp matched successfully"]; 
    		}else{
    			$response = ["status"=>0,"message"=>"otp wrong"];

    		}

    	}    

    	$this->set_response($response);    

    }


    //  User Forgot Password  method   
    public function customer_update_password_post(){ 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->c_email) != "") {
    		$c_email= $input_data->c_email;
    	}else {
    		$error = "Customer Mail id  is required";
    		goto end;
    	}
    	if (isset($input_data->confirm_password) != "") {
    		$password= $input_data->confirm_password;
    	}else {
    		$error = "Password is required";
    		goto end;
    	}
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{
    		$c_pwd = $this->db->select('*')->from('customers')->where('c_email',$c_email)->get()->row()->c_pwd;
    		$pwd =md5($password);
    		if($c_pwd==$pwd){
    			$response = array('status'=>0,'message'=>'old password and new password should not be same');

    		}else{
    			$cust_where=array("c_email"=>$c_email);           
    			$cust_data = array('c_pwd' =>md5($password));
    			$update_customer = $this->comman_model->update('customers', $cust_where, $cust_data);        
    			if($update_customer){
    				$response = array('status'=>1,'message'=>'Password Update successfully');
    			}else{
    				$response = array('status'=>0,'message'=>'Unable Update Password '); 
    			}


    		}  
    	}  

    	$this->set_response($response);    

    }
    

     //Change Password  Otp check  method   
    public function change_otp_check_post() { 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->c_email) != "") {
    		$c_email= $input_data->c_email;
    	}else {
    		$error = "Email  is required";
    		goto end;
    	}
    	if (isset($input_data->c_otp) != "") {
    		$c_otp= $input_data->c_otp;
    	}else {
    		$error = "Customer Otp  is required";
    		goto end;
    	}
    	if (isset($input_data->old_password) != "") {
    		$old_password= md5($input_data->old_password);
    	}else {
    		$error = " Old Password  is required";
    		goto end;
    	}
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{
    		$db_otp = $this->db->select('c_otp,c_pwd')->from('customers')->where('c_email',$c_email)->get()->row_array();
    		if($db_otp['c_otp']!=$c_otp && $db_otp['c_pwd']!=$old_password){
    			$response = ["status"=>0,"message"=>"Invalid details"]; 
    		}elseif($db_otp['c_pwd']!=$old_password){
    			$response = ["status"=>0,"message"=>"Password you entered was wrong"];

    		}elseif($db_otp['c_otp']!=$c_otp){
    			$response = ["status"=>0,"message"=>"otp wrong"];
    		}elseif($db_otp['c_otp']==$c_otp && $db_otp['c_pwd']==$old_password){
    			$response = ["status"=>1,"message"=>"Otp && password matched successfully"]; 

    		}
    	}    

    	$this->set_response($response);    

    }
        //  Vechile Group  post  method   
    public function grace_period_post() { 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->v_id) != "") {
    		$v_id= $input_data->v_id;
    	}else {
    		$error = "Vehicle Id   is required";
    		goto end;
    	}

    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    		{   $data = $this->db->select('*')->from('vehicles')->join('vehicle_group', 'vehicle_group.gr_id=vehicles.v_group','left')->where('v_id',$v_id)->get()->row_array();
    	if($data){
    		$response = ["status"=>1,"grace_period"=>$data['gr_grace_time'],"gr_waiting_price"=>$data['gr_waiting_price']]; 
    	}else{
    		$response = ["status"=>0,"message"=>"unable to get vechicle group details"];

    	}

    }    

    $this->set_response($response);    

}
    // get the Trip amount
public function trip_amount_post() {
	$json = file_get_contents('php://input');
	$input_data = json_decode($json);
      $error="";/*$token = $input_data->token;
       $error = "";
       if (isset($token) != "") {
           $this->check_token($token);
       }else {
           $error = "Token is required";
           goto end;
       }        */
       if (isset($input_data->t_id) != "") {
       	$t_id= $input_data->t_id;
       }else {
       	$error = "Trip id  is required";            
       }
       end:
       if($error !="")
       {
       	$response = ["status"=>0,"message"=>$error];
       }
       else 
       {
       	$data=$this->db->select("*,sum(trips.t_dyanamic_price) + sum(trips.t_d_waiting_amount) AS Amount")->from('trips')
       	->where('t_id', $t_id)
       	->group_by('t_id')
       	->get()->row_array();
       	if($data){
       		$response = ['status'=>1,'total_amount'=>$data];
       	}else{
       		$response = ['status'=>0,'message'=>'Unable to Get total amount'];
       	}
       }
       $this->set_response($response);        
   }


  // ongoing status  check  method   
   public function ongoing_status_check_post() { 
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->t_id) != "") {
   		$t_id= $input_data->t_id;
   	}else {
   		$error = "Trip id required";
   		goto end;
   	}

   	end:
   	if($error !="")
   	{ 
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{
   		$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_trip_status;
   		if($db_otp=="ongoing"){
   			$response = ["status"=>1,"message"=>"Trip is ongoing"]; 
   		}elseif($db_otp=="admin_cancel"){
   			$db_otp = $this->db->select('*')->from('trips')->where('t_id',$t_id)->get()->row()->t_driver;
   			$trip_where=array("d_id"=>$db_otp);           
   			$trp_data = array('d_riding_status' =>'no');
   			$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);
   			$response = ["status"=>1,"message"=>"Admin Cancelled The Trip"]; 

   		}elseif($db_otp=="cancelled"){
   			$response = ["status"=>1,"message"=>"Driver Cancelled The Trip"]; 

   		}elseif($db_otp=="completed"){
   			$response = ["status"=>1,"message"=>"Trip is Ended"]; 

   		}elseif($db_otp=="yettoconfirm"){
   			$response = ["status"=>1,"message"=>"Trip is yettoconfirm"]; 

   		}
   		elseif($db_otp=="ready_to_pickup"){
   			$response = ["status"=>1,"message"=>"Driver Reached Your pickup Location"]; 

   		}
   		elseif($db_otp=="reached_destination"){
   			$response = ["status"=>1,"message"=>"Reached Your Destination"]; 

   		}
   		else{
   			$response = ["status"=>0,"message"=>"Trip is not ongoing"];

   		}

   	}    

   	$this->set_response($response);    

   }


    //  Vechile type get method
   public function vechile_type_get(){       
   	$data=$this->db->select('*')->from('vehicle_type')->where('v_type',"AUTORICKSHAW")->group_by('v_type')
   	->get()->result_array(); 
   	
   	$vehicle_type_data= $data;
   	if($vehicle_type_data){
   		$response = array('status'=>1,'vehicle_type_data'=>$vehicle_type_data); 
   	}else{
   		$response = array('status'=>0,'message'=>'Unable to get Vechicle type'); 
   	}
   	$this->set_response($response);
   }

	//  Wait time add   post  method   
   public function wait_time_add_post() { 
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->t_id) != "") {
   		$t_id= $input_data->t_id;
   	}else {
   		$error = "Trip  Id   is required";
   		goto end;
   	}
   	if (isset($input_data->wait_time) != "") {
   		$wait_time= $input_data->wait_time;
   	}else {
   		$error = "Wait time  is required";
   		goto end;
   	}

   	end:
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{ 

   		$data = $this->db->select('*')->from('trips')->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id','left')->where('t_id',$t_id)->get()->row_array();
   		$time=$wait_time;
   		$timesplit=explode(':',$time);
   		$min=($timesplit[0]*60)+($timesplit[1])+($timesplit[2]>30?1:0);

   		$wait_time= $data['t_waiting_time']+$min;
   		$amount2=$wait_time*$data['gr_waiting_price'];

   		$trip_where=array("t_id"=>$t_id);           
   		$trip_data = array('t_trip_status'=>'payment_pending','t_waiting_time' =>$wait_time,'t_waiting_amount' =>$amount2);
   		$trip_customer = $this->comman_model->update('trips', $trip_where, $trip_data); 
   		if($trip_customer ){
   			$response = ["status"=>1,"message"=>"waiting time calculated successfully","waiting_time"=>$wait_time,"waiting_amount"=>$amount2]; 
   		}else{
   			$response = ["status"=>0,"message"=>"unable to calculate wait time"];

   		}

   	}    

   	$this->set_response($response);    

   }

	// Wait time caluclate  method   
   public function waiting_time_post(){ 
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->t_id) != "") {
   		$t_id= $input_data->t_id;
   	}else {
   		$error = "Trip Id  is required";
   		goto end;
   	}
   	end:
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{
   		$db_otp = $this->db->select('*')->from('trips')->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id','left')->where('t_id',$t_id)->get()->row_array();
   		$datetime1 = new DateTime($db_otp['t_start_time']);
   		$datetime2 = new DateTime($db_otp['t_reached_time']);
   		$interval = $datetime1->diff($datetime2);
            // $a=strtotime($interval);
   		$time=$interval->format('%H:%i:%s');



   		$grace= $db_otp['gr_grace_time']*60;
   		$grace_time=gmdate("H:i:s",$grace);
   		$w=strtotime($grace_time);
   		$q=strtotime($time);
   		$hours = ($q - $w);
   		$diff=$hours > 0 ? $hours : 0;



            // $totalSecondsDiff =abs($time-$grace_time);
   		$time_taken=gmdate("H:i:s",$diff);


            // $totalsec=strtotime($time_taken);

   		$str_time = $time_taken;

   		$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);

   		sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

   		$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;


   		$paisa=$db_otp['gr_waiting_price']*100;
   		$money=$paisa/60;
   		$total_amount= ($money*$time_seconds/100);





   		$trip_where=array("t_id"=>$t_id);           
   		$trip_data = array('t_waiting_time' =>$time_taken,'t_waiting_amount' =>$total_amount);
   		$trip_customer = $this->comman_model->update('trips', $trip_where, $trip_data); 

   		if($trip_customer){
   			$response = ["status"=>1,"message"=>"calculated  successfully","waiting_time"=>$time_taken,"waiting_amount"=>round($total_amount)]; 
   		}else{
   			$response = ["status"=>0,"message"=>"unable to calculate  time"];

   		}

   	}    

   	$this->set_response($response);     

   }


 // Wait time caluclate  method   
   public function wait_update_post(){ 
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->t_id) != "") {
   		$t_id= $input_data->t_id;
   	}else {
   		$error = "Trip Id  is required";
   		goto end;
   	}
   	end:
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{
   		$group = $this->db->select('*')->from('trips')->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id','left')->where('t_id',$t_id)->get()->row_array();



   		$data=$this->db->select('w_id,SEC_TO_TIME( SUM( TIME_TO_SEC( `w_time` ) ) ) AS timeSum ')->from('wait_time')
   		->where('w_t_id', $t_id)
   		->where('w_status', '1')
   		->group_by('w_t_id')
   		->get()->row_array();



   		if($data){

           //      // $prasent_time = substr($data['timeSum'], 0, strpos($data['timeSum'], "."));

           //    // echo $variable;

   			$old_time=$group['t_waiting_time'];

   			$time =$data['timeSum'];
   			$time2 =$old_time;

   			$secs = strtotime($time2)-strtotime("00:00:00");
   			$result = date("H:i:s",strtotime($time)+$secs);


   			$str_time = $result;

   			$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);

   			sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

   			$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;


   			$paisa=$group['gr_waiting_price']*100;
   			$money=$paisa/60;
   			$total_amount= ($money*$time_seconds/100);

   			$trip_where=array("t_id"=>$t_id);           
   			$trip_data = array('t_d_waiting_time' =>$result,'t_d_waiting_amount' =>$total_amount);
   			$trip_customer = $this->comman_model->update('trips', $trip_where, $trip_data); 

   			if($trip_customer){
   				$response = ["status"=>1,"message"=>"calculated  successfully","waiting_time"=>$result,"waiting_amount"=>round($total_amount)]; 
   			}else{
   				$response = ["status"=>0,"message"=>"unable to calculate  time"];

   			}

   		}else{

   			$old_time=$group['t_waiting_time'];
   			$old_amount=$group['t_waiting_amount'];
   			$trip_where=array("t_id"=>$t_id);           
   			$trip_data = array('t_d_waiting_time' =>$old_time,'t_d_waiting_amount' =>$old_amount);
   			$trip_customer = $this->comman_model->update('trips', $trip_where, $trip_data); 


   			$response = ["status"=>1,"message"=>"calculated  successfully","waiting_time"=>$old_time,"waiting_amount"=>round($old_amount)];
   		}

   	}    

   	$this->set_response($response);     

   }
   //  Vechile type get method
   public function vechile_image_post(){       
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->d_id) != "") {
   		$d_id= $input_data->d_id;
   	}else {
   		$error = "Driver Id  is required";
   		goto end;
   	}
   	end:
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{


   		$this->db
   		->select('image')
   		->from('drivers')
   		->join('vehicles', 'vehicles.v_driver_id=drivers.d_id')
   		->join('vehicle_type', 'vehicle_type.vt_group = vehicles.v_group AND vehicle_type.v_type=vehicles.v_type')
   		->where('drivers.d_id',$d_id);

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

   		$test=$query->result();  

   		foreach($test as $row){

   			$row->img_path=$local_path=$this->config->base_url().'assets/uploads/'.$row->image;

   		} 

   		if($test){
   			$response = array('status'=>1,'vehicle_image_data'=>$test); 
   		}else{
   			$response = array('status'=>0,'message'=>'Unable to get Vechicle type'); 
   		}
   		$this->set_response($response);
   	}
   }


   //get vechile veriant
   public function meter_price_post($distance,$d_id,$t_id){

        // $json = file_get_contents('php://input');
        // $input_data = json_decode($json);
   	$error="";
      /*  $token = $input_data->token;
        $error = "";
        if (isset($token) != "") {
            $this->check_token($token);
        }else {
            $error = "Token is required";
            goto end;
        } */       
        if (($distance) != "") {
        	$distance= $distance;

        }else{
        	$error = "Distance is required";
        	goto end;
        }   
        if(isset($d_id) != ""){
        	$d_id= $d_id;
        }else{
        	$error = "Driver id required";
        	goto end;  
        }

        end :
        if($error !="")
        {
        	$response = ["status"=>0,"message"=>$error];
        }
        else
        {

        	$this->db
        	->select('gr_mid_night_time_start,gr_mid_night_time_to,gr_mid_night_extra,gr_mid_night_charge,gr_fixed_km,gr_price,gr_fixed_amount')
        	->from('drivers')
        	->join('vehicles', 'vehicles.v_driver_id=drivers.d_id')
        	->join('vehicle_group', 'vehicle_group.gr_id = vehicles.v_group')
        	->where('drivers.d_id',$d_id);

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

        	$query_result=$query->result(); 

        	$lat = $this->db->select('t_trip_fromlat,t_trip_fromlog,gr_price,t_driver,t_vechicle,t_show_meter_distance')->from('trips')->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id','left')->where('t_id',$t_id)->get()->row_array();


        	foreach($query_result as $row){
        		$hour = date("H");



        		if ($hour == $row->gr_mid_night_time_start || $hour <= $row->gr_mid_night_time_to)
        		{
        			$test=$distance-$row->gr_fixed_km;
        			$diff=$test > 0 ? $test : 0;
        			if($diff=='0'){
        				$row->actual_price=round($row->gr_mid_night_charge);
        				$u=round($distance);
        				$km=round($lat['t_show_meter_distance'], 1); 
        				if($km<$row->gr_fixed_km){
        					if($lat['t_show_meter_distance']==0.00){
        						$query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."',t_show_meter_price=t_show_meter_price+'".$row->actual_price."' WHERE t_id='".$t_id."'");

        					}else{

        						$query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."' WHERE t_id='".$t_id."'");



        					}
        				}else{
        					$extra=($row->gr_price*$row->gr_mid_night_extra)/100;
        					$charge=$row->gr_price+$extra;
        					$v=$charge*$distance;

        					$row->actual_price=round($v);
        					$query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."',t_show_meter_price=t_show_meter_price+'".$row->actual_price."' WHERE t_id='".$t_id."'");


        				}


        			}else{

//                 $extra=($row->gr_price*$row->gr_mid_night_extra)/100;
//                 $charge=$row->gr_price+$extra;
//                 $v=$charge*$test;

//                 $row->actual_price=round($v+$row->gr_mid_night_charge);
//                 $driver_where=array("t_id"=>$t_id);           
// $driver_data = array('t_show_meter_distance' =>round($distance),'t_show_meter_price' =>$row->actual_price);
// $u=round($distance); 
// $query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."',t_show_meter_price=t_show_meter_price+'".$row->actual_price."' WHERE t_id='".$t_id."'");
        			}



        		}else{


        			$test=$distance-$row->gr_fixed_km;

        			$diff=$test > 0 ? $test : 0;
        			if($diff=='0'){
        				$row->actual_price=round($row->gr_fixed_amount);
        				$driver_where=array("t_id"=>$t_id);           
        				$driver_data = array('t_show_meter_distance' =>round($distance),'t_show_meter_price' =>$row->actual_price);
        				$u=round($distance);
        				$km=round($lat['t_show_meter_distance'], 1); 
        				if($km<$row->gr_fixed_km){
        					if($lat['t_show_meter_distance']==0.00){
        						$query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."',t_show_meter_price=t_show_meter_price+'".$row->actual_price."' WHERE t_id='".$t_id."'");

        					}else{

        						$query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."' WHERE t_id='".$t_id."'");



        					}
        				}else{
        					$v=$row->gr_price*$distance;

        					$row->actual_price=round($v);
        					$query=$this->db->query("UPDATE trips SET t_show_meter_distance=t_show_meter_distance+'".$distance."',t_show_meter_price=t_show_meter_price+'".$row->actual_price."' WHERE t_id='".$t_id."'");


        				}

        			}else{
        				$v=$row->gr_price*$test;

        				$row->actual_price=round($v+$row->gr_fixed_amount);
        				$driver_where=array("t_id"=>$t_id);  
        				$u=round($distance);
        			}




        		}
// 

        	}



        	if($query_result){
        		$response = ["status"=>1,"vehicle_veriant_info"=>$query_result];
        	}else{
        		$response = ["status"=>0,"message"=>"Unable to get vehicle veriant info"];
        	}
        }
        $this->set_response($response);

    }
    public function show_meter_display_post(){       
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->t_id) != "") {
    		$t_id= $input_data->t_id;
    	}else {
    		$error = "Trip Id  is required";
    		goto end;
    	}
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{


    		$lat = $this->db->select('t_show_meter_distance,t_show_meter_price')->from('trips')->where('t_id',$t_id)->get()->row_array();


    		if($lat){
    			$response = ["status"=>1,"message"=>$lat];
    		}else{
    			$response = ["status"=>0,"message"=>"Unable get details"];
    		}


    		$this->set_response($response);
    	}
    }


    public function  feedback_form_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (($input_data->c_id) != "") {
    		$data['f_c_id']= $input_data->c_id;
    	}else{
    		$error = "Customer Id is required";
    		goto end;
    	}
    	if (($input_data->d_id) != "") {
    		$data['f_d_id']= $input_data->d_id;
    	}else{
    		$error = "Customer Id is required";
    		goto end;
    	} 
    	if (($input_data->c_name) != "") {
    		$data['f_c_name']= $input_data->c_name;
    	} else{
    		$error = "Customer Name is required";
    		goto end;
    	} 
    	if (($input_data->c_email) != "") {
    		$data['f_c_email']= $input_data->c_email;
    	} else{
    		$error = "Customer email is required";
    		goto end;
    	} 
    	if (($input_data->c_age) != "") {
    		$data['f_c_age']= $input_data->c_age;
    	} else{
    		$error = "Customer age is required";
    		goto end;
    	} 
    	if (($input_data->c_gender) != "") {
    		$data['f_c_gender']= $input_data->c_gender;
    	} else{
    		$error = "Customer sex is required";
    		goto end;
    	}
    	if (($input_data->t_id) != "") {
    		$data['f_t_id']= $input_data->t_id;
    	} else{
    		$error = "Trip  id required";
    		goto end;
    	}  
    	if (($input_data->rideapp_rating) != "") {
    		$data['f_rideapp_rating']= $input_data->rideapp_rating;
    	} else{
    		$error = "Customer ride app rating is required";
    		goto end;
    	} 
    	if (($input_data->rateapp_usage) != "") {
    		$data['f_rateapp_usage']= $input_data->rateapp_usage;
    	} else{
    		$error = "Customer rate app usage is required";
    		goto end;
    	} 
    	if (($input_data->similar_ola_uber) != "") {
    		$data['f_similar_ola_uber']= $input_data->similar_ola_uber;
    	} else{
    		$error = "Customer similar ola uber  is required";
    		goto end;
    	} 
    	if (($input_data->recommend) != "") {
    		$data['f_recommend']= $input_data->recommend;
    	} else{
    		$error = "Customer recommend is required";
    		goto end;
    	} 
    	if (($input_data->improvements_comments) != "") {
    		$data['f_improvements_comments']= $input_data->improvements_comments;
    	} else{
    		$error = "Customer improvements comments is required";
    		goto end;
    	} 
    	end :
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{

    		$update_customer = $this->db->insert('feedback_customers',$data); 
    		if($update_customer){
    			$response = ["status"=>1,"message"=>"Thank you for the feedback, hope to see you again."];
    		}else{
    			$response = ["status"=>0,"message"=>"Unable to add feedback"];
    		}
    	}
    	$this->set_response($response);
    }

    public function feedback_check_post(){       
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (isset($input_data->t_id) != "") {
    		$t_id= $input_data->t_id;
    	}else {
    		$error = "Trip Id  is required";
    		goto end;
    	}
    	end:
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{


    		$ql = $this->db->select('f_t_id')->from('feedback_customers')->where('f_t_id',$t_id)->get();


    		if($ql->num_rows()!=0){
    			$response = ["status"=>0,"message"=>"Feedback already given"];
    		}else{
    			$response = ["status"=>0,"message"=>"No feedback given"];
    		}


    		$this->set_response($response);
    	}
    }

     public function address_get(){ 
     $lat=17.4929964;
      $lng=78.3685922;

       $google_api_key = $this->config->item('google_api_key'); 
     $url = 'https://maps.googleapis.com/maps/api/geocode/json?key='.$google_api_key.'&latlng='.trim($lat).','.trim($lng).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
        if (!empty($data)) {
            $status = $data->status;
            if ($status == "OK") {
                print_r($data->results[1]->formatted_address);
                exit();
                return $data->results[1]->formatted_address;
            } else {
                return false;
            }
        } else {
            return '';
        }
    }

    public function  support_form_post(){
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (($input_data->c_id) != "") {
    		$data['s_c_id']= $input_data->c_id;
    	}else{
    		$error = "Customer Id is required";
    		goto end;
    	}
    	if (($input_data->s_related) != "") {
    		$data['s_related']= $input_data->s_related;
    		$data['s_ticket'] = rand(1000,9999);
    	}else{
    		$error = "Realted type is required";
    		goto end;
    	} 
    	if (($input_data->s_comment) != "") {
    		$data['s_comment']= $input_data->s_comment;
    	} else{
    		$error = "Comment is  required";
    		goto end;
    	} 

    	end :
    	if($error !="")
    	{
    		$response = ["status"=>0,"message"=>$error];
    	}
    	else
    	{

    		$update_customer = $this->db->insert('support_customers',$data); 
    		if($update_customer){
    			$this->load->model('email_model');
    			$this->load->library('email');
    			$gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Support')->get()->result_array();
    			$email = $this->db->select('*')->from('customers')->where('c_id',$data['s_c_id'])->get()->row_array();


    			if(!empty($gettemplate)) {
    				$emailcontent = $gettemplate[0]['et_body'];
    				$value = '<b>Dear '.$email['c_name'].' Thank you for the Raise Ticket, hope to see you again Please Find Your Ticket Number.</b> '.$data['s_ticket'];
    				$body = str_replace('{{details}}', $value, $emailcontent);
    				$custemail = $email['c_email'];

    				$email = $this->email_model->sendemail_password($custemail,$gettemplate[0]['et_subject'],$body);
    			} 


    			$response = ["status"=>1,"message"=>"Your Request Submitted Successfully."];
    		}else{
    			$response = ["status"=>0,"message"=>"Unable to add Request"];
    		}
    	}
    	$this->set_response($response);
    }

    public function login_mobile_post(){ 
    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (($input_data->c_mobile) != "") {
    		$data['c_mobile']= $input_data->c_mobile;

    	} else {
    		$error = "Mobile Number is required";
    		goto end;
    	}
      // if (($input_data->device_token) != "") {
      //       $device_token= $input_data->device_token;
      //   } else {
      //       $error = "Device Token is required";
      //       goto end;
      //   }
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else
    	{

    		$this->db->where('c_mobile', $data['c_mobile']);
            // $this->db->where('c_pwd',$data['c_pwd']);
    		$query = $this->db->get("customers");

    		if ($query->num_rows() >= 1) {
    			$result = $query->row_array();

    			if($result['c_isactive']==0) {

    				$response = ["status"=>0,"message"=>"User not active.Please contact admin"];
    			} else {


                    // $where_array=array( "c_mobile"=>$data['c_mobile']);
                    // $update_data=array("device_token"=>$device_token );
                    // $this->comman_model->update('customers', $where_array);
    				$trip_where=array("c_mobile"=>$data['c_mobile']);
    				$data['c_otp'] = rand(1000, 9999);           
    				$trp_data = array('c_otp' =>$data['c_otp']);
    				$update_trip = $this->comman_model->update('customers', $trip_where, $trp_data);
    				if($update_trip){
            // Account details
    					$apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
                // Message details
    					$OTP = $data['c_otp'];
    					$numbers = $data['c_mobile'];
    					$sender = urlencode("Volta");
    					$message = rawurlencode('Dear User, your OTP for Volta App Login is '.$OTP.'.Do not share your OTP with anyone .');   
                // Prepare data for POST request
    					$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
                // Send the POST request with cURL
    					$ch = curl_init('https://api.textlocal.in/send/');
    					curl_setopt($ch, CURLOPT_POST, true);
    					curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    					$response = curl_exec($ch);
    					curl_close($ch);
                // Process your response here
                // echo $response;

    					$response = ["status"=>1,"message"=>"OTP sent to registered Mobile Number"];
    				}
    				$response = ["status"=>1,"message"=>"OTP sent to registered Mobile Number"];
                 // $response = ["status"=>1,"message"=>"You got logged in successfully..","customer_info"=>$result];

    			}
    		} else {
    			$response = ["status"=>0,"message"=>"Invalid Mobile Number Please Enter valid Mobile Number"];
    		}
    	}

    	echo json_encode($response);
    	exit(); 
    }

    public function login_mobile_otp_check_post(){ 

    	$json = file_get_contents('php://input');
    	$input_data = json_decode($json);
    	$error = "";
    	if (($input_data->c_mobile) != "") {
    		$data['c_mobile']= $input_data->c_mobile;

    	} else {
    		$error = "Mobile Number is required";
    		goto end;
    	}
    	if (($input_data->c_otp) != "") {
    		$c_otp= $input_data->c_otp;
    	} else {
    		$error = "OTP is required";
    		goto end;
    	}
    	if (($input_data->device_token) != "") {
    		$device_token= $input_data->device_token;
    	} else {
    		$error = "Device Token is required";
    		goto end;
    	}
    	end :
    	if($error !="")
    	{
    		$result = ["status"=>0,"message"=>$error];
    	}
    	else
    	{

    		$this->db->where('c_mobile', $data['c_mobile']);
    		$this->db->where('c_otp',$c_otp);
    		$query = $this->db->get("customers");

    		if ($query->num_rows() >= 1) {
    			$result = $query->row_array();

    			if($result['c_isactive']==0) {

    				$response = ["status"=>0,"message"=>"User not active.Please contact admin"];
    			} else {

                   /* $password = $data['c_pwd'];
                   $user_id=$data['c_email'];
                   $hash=$password.$user_id.rand();
                   $token = $this->bcrypt->hash_password($hash);
                   $data_where=array("c_email"=>$data['c_email']);
                   $update_data=array("token"=>$token);
                   $update_info = $this->comman_model->update('customers', $data_where, $update_data);  
                   
                   if($update_info){
                        $data_where=array("c_email"=>$data['c_email']);
                        $result_data= $this->comman_model->get_data_where('customers',$data_where);
                        if($result_data){
                            $response = ["status"=>1,"message"=>"You got logged in successfully..","customer_info"=>$result_data];
                        }else{
                            $response = ["status"=>1,"message"=>"unable to get Customer Info.."];
                        }
                   }else{
                       $response = ["status"=>1,"message"=>"Unable to Generate Token Please try again"];
                   } */

                   $where_array=array( "c_mobile"=>$data['c_mobile']);
                   $update_data=array("device_token"=>$device_token);
                   $update_info = $this->comman_model->update('customers', $where_array, $update_data);
                   $response = ["status"=>1,"message"=>"You got logged in successfully..","customer_info"=>$result];

               }
           } else {
           	$response = ["status"=>0,"message"=>"Enter valid OTP"];
           }
       }

       echo json_encode($response);
       exit(); 
   }

   public function driver_login_mobile_post(){ 
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (($input_data->d_mobile) != "") {
   		$data['d_mobile']= $input_data->d_mobile;

   	} else {
   		$error = "Mobile Number is required";
   		goto end;
   	}
      // if (($input_data->device_token) != "") {
      //       $device_token= $input_data->device_token;
      //   } else {
      //       $error = "Device Token is required";
      //       goto end;
      //   }
   	end :
   	if($error !="")
   	{
   		$result = ["status"=>0,"message"=>$error];
   	}
   	else
   	{

   		$this->db->where('d_mobile', $data['d_mobile']);
            // $this->db->where('c_pwd',$data['c_pwd']);
   		$query = $this->db->get("drivers");

   		if ($query->num_rows() >= 1) {
   			$result = $query->row_array();

   			if($result['d_is_active']==0) {

   				$response = ["status"=>0,"message"=>"Driver not active.Please contact admin"];
   			} elseif($result['d_is_active']==-1) {
   				$response = ["status"=>0,"message"=>"Need to upload your documents"];
   			}
   			else{

                    // $where_array=array( "d_mobile"=>$data['d_mobile']);
                    // $update_data=array("device_token"=>$device_token );
                    // $this->comman_model->update('drivers', $where_array);
   				$trip_where=array("d_mobile"=>$data['d_mobile']);
   				$data['d_otp'] = rand(1000, 9999);

   				$trp_data = array('d_otp' =>$data['d_otp']);
   				$update_trip = $this->comman_model->update('drivers', $trip_where, $trp_data);
   				if($update_trip){
            // Account details
   					$apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
                // Message details
   					$OTP = $data['d_otp'];
   					$numbers = $data['d_mobile'];
   					$sender = urlencode("Volta");
   					$message = rawurlencode('Dear User, your OTP for Volta App Login is '.$OTP.'.Do not share your OTP with anyone .'); 

                // Prepare data for POST request
   					$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
                // Send the POST request with cURL
   					$ch = curl_init('https://api.textlocal.in/send/');
   					curl_setopt($ch, CURLOPT_POST, true);
   					curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   					$response = curl_exec($ch);
   					curl_close($ch);
                // Process your response here
                // echo $response;

   					$response = ["status"=>1,"message"=>"OTP sent to registered Mobile Number"];
   				}
   				$response = ["status"=>1,"message"=>"OTP sent to registered Mobile Number"];
                 // $response = ["status"=>1,"message"=>"You got logged in successfully..","customer_info"=>$result];

   			}
   		} else {
   			$response = ["status"=>0,"message"=>"Invalid Mobile Number Please Enter valid Mobile Number"];
   		}
   	}

   	echo json_encode($response);
   	exit(); 
   }



   public function driver_login_mobile_otp_check_post(){ 

   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (($input_data->d_mobile) != "") {
   		$data['d_mobile']= $input_data->d_mobile;

   	} else {
   		$error = "Mobile Number is required";
   		goto end;
   	}
   	if (($input_data->device_token) != "") {
   		$device_token= $input_data->device_token;
   	} else {
   		$error = "Device Token is required";
   		goto end;
   	}
   	if (($input_data->d_otp) != "") {
   		$d_otp= $input_data->d_otp;
   	} else {
   		$error = "OTP is required";
   		goto end;
   	}
   	end :
   	if($error !="")
   	{
   		$result = ["status"=>0,"message"=>$error];
   	}
   	else
   	{



   		$this->db->where('d_mobile', $data['d_mobile']);
   		$this->db->where('d_otp',$d_otp);
   		$query = $this->db->get("drivers");

   		if ($query->num_rows() >= 1) {

   			$this->db->select('*');                
   			$this->db->from('drivers');
   			$this->db->join('organization', 'organization.org_id=drivers.organization_id');
   			$this->db->join('vehicles', 'vehicles.v_driver_id=drivers.d_id');
   			$this->db->join('vehicle_group', 'vehicle_group.gr_id=vehicles.v_group'); 
   			$this->db->where('d_mobile', $data['d_mobile']);
   			$this->db->where('d_otp', $d_otp);
   			$query = $this->db->get(); 
   			$result1 = $query->row_array();

   			$where_array=array( "d_mobile"=>$data['d_mobile']);
   			$update_data=array("device_token"=>$device_token );
   			$update_trip = $this->comman_model->update('drivers', $where_array, $update_data); 

   			$response = ["status"=>1,"message"=>"You got logged in successfully..","driver_info"=>$result1];


   		} else {
   			$response = ["status"=>0,"message"=>"Enter valid OTP "];
   		}
   	}
   	$this->set_response($response);
   	
   }


   public function customer_login_post() { 
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error="";
   	if (($input_data->c_mobile) != ""){
   		$data['c_mobile']= $input_data->c_mobile;
   	}else {
   		$error = "Mobile Number is required";
   		goto end;
   	}
   	end :
   	if($error !="")
   	{
   		$result = ["status"=>0,"message"=>$error];
   	}
   	else
   	{

   		$this->db->where('c_mobile', $data['c_mobile']);
   		$query = $this->db->get("customers");
   		if ($query->num_rows() >= 1) {
   			$trip_where=array("c_mobile"=>$data['c_mobile']);
   			$data['c_otp'] = rand(1000, 9999);

   			$trp_data = array('c_otp' =>$data['c_otp']);
   			$update_trip = $this->comman_model->update('customers', $trip_where, $trp_data);

   			if($update_trip){

   				$apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
                // Message details
   				$OTP = $data['c_otp'];
   				$numbers = $data['c_mobile'];
   				$sender = urlencode("Volta");
   				$message = rawurlencode('Dear User, your OTP for Volta App Login is '.$OTP.'.Do not share your OTP with anyone .'); 

                // Prepare data for POST request
   				$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
                // Send the POST request with cURL
   				$ch = curl_init('https://api.textlocal.in/send/');
   				curl_setopt($ch, CURLOPT_POST, true);
   				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   				$response = curl_exec($ch);
   				curl_close($ch);
                // Process your response here
                // echo $response;

   				$result = ["status"=>1,"message"=>"OTP sent to registered Mobile Number"];
   			}else{
   				$result = ["status"=>0,"message"=>"Unable to get otp"];
   			}
   		}else{

   			$data['c_otp'] = rand(1000, 9999);           
   			$update_trip = $this->comman_model->insert_record('customers',$data);
   			if($update_trip){
   				$apiKey = ('NTkzMjRkMzI3MzMyNDI2ZTczNjI1MDY3NzM1MTZmNzM=');
                // Message details
   				$OTP = $data['c_otp'];
   				$numbers = $data['c_mobile'];
   				$sender = urlencode("Volta");
   				$message = rawurlencode('Dear User, your OTP for Volta App Login is '.$OTP.'.Do not share your OTP with anyone .'); 

                // Prepare data for POST request
   				$data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender"=> $sender, "message" => $message);
                // Send the POST request with cURL
   				$ch = curl_init('https://api.textlocal.in/send/');
   				curl_setopt($ch, CURLOPT_POST, true);
   				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   				$response = curl_exec($ch);
   				curl_close($ch);
   				$result = ["status"=>0,"message"=>"OTP sent to your Mobile Number"];
   			}
   		}

   	}   

   	$this->set_response($result);


   }


   public function dynamic_distance_post(){

   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->t_id) != "") {
   		$t_id= $input_data->t_id;
   	}else {
   		$error = "Trip id  is required";
   		goto end;
   	}
   	if (isset($input_data->to_lat) != "") {
   		$to_lat= $input_data->to_lat;
   	}else {
   		$error = "To latitude is required";
   		goto end;
   	}
   	if (isset($input_data->to_long) != "") {
   		$to_long= $input_data->to_long;
   	}else {
   		$error = "To longitude  is required";
   		goto end;
   	}
   	if (isset($input_data->trip_status) != "") {
   		$trip_status= $input_data->trip_status;
   	}else {
   		$error = "Trip Status is required";
   		goto end;
   	}
   	if (isset($input_data->d_id) != "") {
   		$d_id= $input_data->d_id;
   	}else {
   		$error = "Trip Status is required";
   		goto end;
   	}
   	end:
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{
$lat=$to_lat;
      $lng=$to_long;
$google_api_key = $this->config->item('google_api_key'); 
     $url = 'https://maps.googleapis.com/maps/api/geocode/json?key='.$google_api_key.'&latlng='.trim($lat).','.trim($lng).'&sensor=false';
    $json = @file_get_contents($url);
    $data = json_decode($json);
        if (!empty($data)) {
            $status = $data->status;
            if ($status == "OK") {
              $trip_where=array("t_id"=>$t_id);           
        $trp_data = array('t_trip_tolocation' =>$data->results[1]->formatted_address);
        $update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
                // return $data->results[1]->formatted_address;
            } else {
                return false;
            }
        } else {
            return '';
        }
       

   		$lat = $this->db->select('t_trip_fromlat,t_trip_fromlog,gr_price,t_driver,t_vechicle,t_show_meter_distance')->from('trips')->join('vehicle_group', 'vehicle_group.gr_id=trips.t_vehicle_group_id','left')->where('t_id',$t_id)->get()->row_array();

   		$latitudeFrom =$lat['t_trip_fromlat'];
   		$longitudeFrom =$lat['t_trip_fromlog'];
   		$latitudeTo = $to_lat;
   		$longitudeTo = $to_long;

   		$url ="https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=".$latitudeFrom.",".$longitudeFrom."&destinations=".$latitudeTo.",".$longitudeTo."&key=AIzaSyByZMqOPxhY92T-AxAhSuwiTyfSBKnKAO8";
   		$ch = curl_init();
   		curl_setopt($ch, CURLOPT_URL, $url);
   		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   		curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
   		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
   		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
   		$response = curl_exec($ch);
   		curl_close($ch);
   		$response_a = json_decode($response, true);
// print_r($response_a);
// exit();

   		$status = "ERROR"; 
   		$dist   = 0;
   		$time   = 0;
   		if($response_a['rows'][0]['elements'][0]['status'] === 'OK') {
   			$dist   = $response_a['rows'][0]['elements'][0]['distance']['value'];
   			$time   = $response_a['rows'][0]['elements'][0]['duration']['text'];
   			$status = "OK";
   		}
   		$fare=$dist/1000;

   		$distance=$fare;




   		$this->db
   		->select('gr_mid_night_time_start,gr_mid_night_time_to,gr_mid_night_extra,gr_mid_night_charge,gr_fixed_km,gr_price,gr_fixed_amount')
   		->from('drivers')
   		->join('vehicles','vehicles.v_driver_id=drivers.d_id')
   		->join('vehicle_group', 'vehicle_group.gr_id = vehicles.v_group')
   		->where('drivers.d_id',$d_id);

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

   		$query_result=$query->result();

   		foreach($query_result as $row){
   			$hour = date("H");




   			if ($hour == $row->gr_mid_night_time_start || $hour <= $row->gr_mid_night_time_to)
   			{
   				$test=$distance-$row->gr_fixed_km;
   				$diff=$test > 0 ? $test : 0;
   				if($diff=='0'){
   					$row->actual_price=round($row->gr_mid_night_charge);
   					$trip_where=array("t_id"=>$t_id);           
   					$trp_data = array('t_trip_status' => $trip_status,'t_dyanamic_distance' =>$distance,'t_dyanamic_price' =>$row->actual_price);
   					$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
   				}else{

   					$extra=($row->gr_price*$row->gr_mid_night_extra)/100;
   					$charge=$row->gr_price+$extra;
   					$v=$charge*$test;

   					$row->actual_price=round($v+$row->gr_mid_night_charge);
   					$trip_where=array("t_id"=>$t_id);           
   					$trp_data = array('t_trip_status' => $trip_status,'t_dyanamic_distance' =>$distance,'t_dyanamic_price' =>$row->actual_price);
   					$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);

   				}



   			}else{


   				$test=$distance-$row->gr_fixed_km;

   				$diff=$test > 0 ? $test : 0;
   				if($diff=='0'){
   					$row->actual_price=round($row->gr_fixed_amount);
   					$trip_where=array("t_id"=>$t_id);           
   					$trp_data = array('t_trip_status' => $trip_status,'t_dyanamic_distance' =>$distance,'t_dyanamic_price' =>$row->actual_price);
   					$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);
   				}else{
   					$v=$row->gr_price*$test;

   					$row->actual_price=round($v+$row->gr_fixed_amount);

   					$trip_where=array("t_id"=>$t_id);           
   					$trp_data = array('t_trip_status' => $trip_status,'t_dyanamic_distance' =>$distance,'t_dyanamic_price' =>$row->actual_price);
   					$update_trip = $this->comman_model->update('trips', $trip_where, $trp_data);

   				}


   			}
   		}


   		if($query_result){
   			$response = ["status"=>1,"prize"=>$query_result];
   		}else{
   			$response = ["status"=>0,"message"=>"Unable to get middle distance"];
   		}
   	}
   	$this->set_response($response);
   }

   public function latest_postions_post(){  
// die('ki');     
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->v_id) != "") {
   		$v_id= $input_data->v_id;
   	}else {
   		$error = "Vehicle Id  is required";
   		goto end;
   	}
   	end:
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{


   		$lat = $this->db->select('latitude,longitude')->from('positions')->order_by('id',"desc")->limit(1)->where('v_id',$v_id)->get()->row_array();


   		if($lat){
   			$response = ["status"=>1,"message"=>$lat];
   		}else{
   			$response = ["status"=>0,"message"=>"Unable get details"];
   		}


   		$this->set_response($response);
   	}
   }

   public function payment_check_post(){       
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (isset($input_data->t_id) != "") {
   		$t_id= $input_data->t_id;
   	}else {
   		$error = "Trip Id  is required";
   		goto end;
   	}
   	end: 
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{


   		$money = $this->db->select('tp_trip_id')->from('trip_payments')->where('tp_trip_id',$t_id)->get(); 
   		if($money->num_rows()!=0){
   			$response = ["status"=>1,"message"=>"Payment already added"];
   		}else{
   			$response = ["status"=>0,"message"=>"no Payment added"];
   		}


   		$this->set_response($response);
   	}
   }


   public function  feedback_driver_form_post(){
   	$json = file_get_contents('php://input');
   	$input_data = json_decode($json);
   	$error = "";
   	if (($input_data->d_id) != "") {
   		$data['f_d_id']= $input_data->d_id;
   	}else{
   		$error = "Driver Id is required";
   		goto end;
   	} 
   	if (($input_data->d_name) != "") {
   		$data['f_d_name']= $input_data->d_name;
   	} else{
   		$error = "Driver Name is required";
   		goto end;
   	} 
   	if (($input_data->d_age) != "") {
   		$data['f_d_age']= $input_data->d_age;
   	} else{
   		$error = "Driver age is required";
   		goto end;
   	} 
   	if (($input_data->d_gender) != "") {
   		$data['f_d_gender']= $input_data->d_gender;
   	} else{
   		$error = "Driver gender is required";
   		goto end;
   	} 
   	if (($input_data->rideapp_rating) != "") {
   		$data['f_rideapp_rating']= $input_data->rideapp_rating;
   	} else{
   		$error = "Customer ride app rating is required";
   		goto end;
   	} 
   	if (($input_data->rateapp_usage) != "") {
   		$data['f_rateapp_usage']= $input_data->rateapp_usage;
   	} else{
   		$error = "Customer rate app usage is required";
   		goto end;
   	} 
   	if (($input_data->similar_ola_uber) != "") {
   		$data['f_similar_ola_uber']= $input_data->similar_ola_uber;
   	} else{
   		$error = "Customer similar ola uber  is required";
   		goto end;
   	} 
   	if (($input_data->recommend) != "") {
   		$data['f_recommend']= $input_data->recommend;
   	} else{
   		$error = "Customer recommend is required";
   		goto end;
   	} 
   	if (($input_data->improvements_comments) != "") {
   		$data['f_improvements_comments']= $input_data->improvements_comments;
   	} else{
   		$error = "Customer improvements comments is required";
   		goto end;
   	} 
   	end :
   	if($error !="")
   	{
   		$response = ["status"=>0,"message"=>$error];
   	}
   	else
   	{

   		$update_customer = $this->db->insert('feedback_drivers',$data); 
   		if($update_customer){
   			$response = ["status"=>1,"message"=>"Thank you for the feedback, hope to see you again."];
   		}else{
   			$response = ["status"=>0,"message"=>"Unable to add feedback"];
   		}
   	}
   	$this->set_response($response);
   }
   //  Payment Type Update  method   
public function test11_get(){ 
	// die("jio");
		$this->load->model('email_model');  
             $gettemplate = $this->db->select('*')->from('email_template')->where('et_name','Payment')->get()->result_array();
             if(!empty($gettemplate)) {
                $emailcontent = $gettemplate[0]['et_body']; 
                $value = '<b>Your Payment Successfully Completed </b><br> ';
               $value = "hello hw r u";
                $body = str_replace('{{details}}', $value, $emailcontent);

                $custemail="rakesh@singlepointech.com";
             $email = $this->email_model->sendemail_test($custemail,$gettemplate[0]['et_subject'],$body);

            }


	     

}

}
