<?php
require_once './Twilio/autoload.php';
use Twilio\Rest\Client;
use Twilio\Exceptions;
error_reporting(0);


$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
/* $countm      = count($request);
  if($countm <= 0)
  {

  exit('No direct script access allowed');
  } */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

class Web_service extends CI_Controller {

    const FACEBOOK_USER_INFORMATION_URL = 'https://graph.facebook.com/me?fields=email,name';
    const GOOGLE_USER_INFORMATION_URL = 'https://www.googleapis.com/plus/v1/people/me';

    public function __construct() {

        parent::__construct();

        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->helper('file');

        // $this->load->library('form_validation');
        $this->load->model('Model_web_service');
        $this->load->database();
        // $this->load->library('session');
        $this->load->library('image_lib');
        // $this->load->helper('cookie');
        $this->load->library('email');
        // $this->load->library('pagination');
    }
 //client login.
    public function login() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        //print_r($request); exit;
        $result = $this->Model_web_service->login($request);
        if ($result) {

            $finresult = array('status' => 'success', 'message' => 'Successfully Logged in', 'flag' => '1', 'Login Details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Unknown credential , please try again!',
                'code' => 'Unknown credential , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
//code for facebook and gmail login
    public function social_login() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $email = $request->email;
         //$password = md5($request->password);
       $socialmedia_auth_id = $request->socialmedia_auth_id;
        $loginby = $request->loginby;
        $first_name = $request->first_name;
        $last_name = $request->last_name;
        $flag = $request->flag;
        $token = $request->token;
        
         $query1 = $this->db->query("SELECT * FROM  clients_tbl where email= '".$email."'");
        $result = $query1->row_array();
       $con_query = $this->db->query("SELECT * FROM  attorneys_tbl where email= '$email'");
        $con_result = $con_query->row_array();
        
        
         $total_count = $query1->num_rows();
        
         if (($result) && ($flag=='Client')) {
            $query = $this->db->query("update clients_tbl set token='$token' where email='" . $email . "'");
            
                $data['ClientId'] = $result['client_id'];
                $data['UserName'] = $result['first_name'] . ' ' . $result['last_name'];
                $data['Email'] = $result['email'];
                $data['Flag'] = 'client';
                $data['Token'] = $token;
                $var[] = $data;
                //echo '<pre>'; print_r($var); exit;
                //return $var;
            
             $finresult = array('status' => 'success', 'message' => 'Successfully Logged in', 'Login Details' => $var);
             print json_encode($finresult);
        }
  else if((empty($result))&&($flag=='Client')){
	 
  $table = 'clients_tbl';
            $ins = array(
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                'token' => $socialmedia_auth_id,
                'loginby' => $loginby
            );
            $insert_result = $this->db->insert($table, $ins);
            $last_id = $this->db->insert_id();  
            
             $query1 = $this->db->query("SELECT * FROM  clients_tbl where client_id = '".$last_id."'");
             $res = $query1->row_array();
            
                $data['ClientId'] = $res['client_id'];
                $data['UserName'] = $res['first_name'] . ' ' . $res['last_name'];
                $data['Email'] = $res['email'];
                $data['Flag'] = 'client';
                $data['Token'] = $socialmedia_auth_id;
                $var[] = $data;
                //echo '<pre>'; print_r($var); exit;
                //return $var;
            
             $finresult = array('status' => 'success', 'message' => 'Registration successfully done','Client Details' => $var);
             print json_encode($finresult);
  }
  
   else if((empty($con_result))&&($flag=='Attorney')){
  $table = 'attorneys_tbl';
            $ins = array(
                'first_name' => $first_name,
                'last_name' => $last_name,
                'email' => $email,
                 'token' => $socialmedia_auth_id,
                'loginby' => $loginby
            );
            $insert_result12 = $this->db->insert($table, $ins);
            $last_id12 = $this->db->insert_id(); 
            
             $query1 = $this->db->query("SELECT * FROM attorneys_tbl where attorney_id = '".$last_id12."'");
             $res = $query1->row_array();
             
               $data['ContractorId'] = $res['attorney_id'];
                $data['UserName'] = $res['first_name'] . ' ' . $res['last_name'];
                $data['Email'] = $res['email'];
                $data['Flag'] = 'contractor';
				$data['Token'] = $socialmedia_auth_id;
                $var[] = $data;
            
             $finresult = array('status' => 'success', 'message' => 'Registration successfully done','Contractor Details' => $var);
             print json_encode($finresult);
            
  }
      
     else if (($con_result) && ($flag=='Attorney')) {
            $query = $this->db->query("update clients_tbl set token='$token' where email='" . $email . "'");
             $con_query = $this->db->query("SELECT * FROM  attorneys_tbl where email = '".$email."'");
             $con_res = $con_query->row_array();
            
                $data['ContractorId'] = $con_res['attorney_id'];
                $data['UserName'] = $con_res['first_name'] . ' ' . $con_res['last_name'];
                $data['Email'] = $con_res['email'];
                $data['Flag'] = 'contractor';
				$data['Paid Status'] = $con_res['paid_status'];
				$data['Paid Date'] = $con_res['paid_date'];
				$data['Token'] = $token;
				
                $var[] = $data;
                //echo '<pre>'; print_r($var); exit;
                //return $var;
            
             $finresult = array('status' => 'success', 'message' => 'Successfully Logged in', 'Login Details' => $var);
             print json_encode($finresult);
        }
       else {
            $error_list[] = array(
                'message' => 'Unknown credential , please try again!',
                'code' => 'Unknown credential , please try again!'
            );
            $finresult = array(
                'status' => 'success',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
      if (isset($loginby) && ($loginby == 'facebook' || $loginby == 'google')) {

            if (isset($socialmedia_auth_id)) {

                $access_token = $socialmedia_auth_id;
            } else {

                $access_token = $access_token;
            }
            $social = $this->requestUserDataFromProvider($loginby, $access_token,$flag);

            if (empty($social) || $social['email'] != $email) {

                $this->json['error'][] = "Social email and posted email mismatch";
                $this->statusCode = 400;
            } else {

                if (isset($social['name'])) {

                    $exploded = explode(' ', $social['name']);

                    $firstname = array_shift($exploded);
                    $lastname = implode(' ', $exploded);
                }
            }
        }
    }

    private function requestUserDataFromProvider($loginby, $access_token,$flag) {
        $ch = curl_init();
        if ($loginby == 'facebook') {
            //echo 'test'; exit;
            curl_setopt($ch, CURLOPT_URL, static::FACEBOOK_USER_INFORMATION_URL);
        } elseif ($loginby == 'google') {
            curl_setopt($ch, CURLOPT_URL, static::GOOGLE_USER_INFORMATION_URL);
        }

        $headers = array("Authorization: Bearer " . $access_token);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        // execute the CURL request.
        $data = curl_exec($ch);
        
        
        
//echo '<pre>'; print_r($data); exit;
        if (!curl_errno($ch)) {
            curl_close($ch);
            $ret = json_decode($data, true);

            if ($loginby == 'google') {
                $ret["name"] = $ret['displayName'];
                $ret["email"] = $ret['emails'][0]['value'];
                //$var[] = $ret;
                //return $var;
                //echo '<pre>'; print_r($ret); exit;
            }
           
            //return $ret;
            // $finresult = array('status' => 'success', 'message' => 'Successfully Logged in', 'flag' => $flag, 'Login Details' => $ret);
          // print json_encode($ret);
          // print json_encode($finresult);
        } else {
            curl_close($ch);
            return NULL;
        }
    }
//delete client record
    public function delete_client_record() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->delete_client_record($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'client record deleted successfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
    public function delete_card() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->delete_card($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'card  deleted successfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

//delte contractor record
    public function delete_contractor_record() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->delete_contractor_record($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'contractor record deleted successfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    

    // client registration
    public function client_registration() {

        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->client_registration($request);

        if ($result) {

            $finresult = array('status' => 'success', 'message' => 'Registration successfully done', 'Client Details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Error, email already exit use other one',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );

            print json_encode($finresult);
        }
    }

//contractor registration
    public function attorney_registration() {

        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->attorney_registration($request);

        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Registration successfully done', 'Contractor Details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Error, email already exit use other one',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );

            print json_encode($finresult);
        }
    }

   

    public function add_jobInformation() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->add_jobInformation($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Job Details added sucessfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    // add job categories
    public function add_jobCategories() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->add_jobCategories($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Job Categories added sucessfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    //to update client profile
    public function update_client_profile() {
       
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->update_client_profile($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Client Profile  details updated successfully',);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    // contractor update profile details

    public function update_contractor_profile() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->update_contractor_profile($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Contractor Profile details updated successfully',);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

     // to view the client profile details
    public function client_profile_details() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->client_profile_details($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Client Profile  details', 'client_profile_details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    // to view the contractor profile details
    public function contractor_profile_details() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->contractor_profile_details($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Contractor Profile details', 'contractor_profile_details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    //forgot password
    public function forgot_password() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->forgot_password($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Password has been sent successful to your email id');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

     // change client password
    public function change_client_password() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->change_client_password($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Password has been changed successfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
     
	 //change contractor password
    public function change_attorney_password() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->change_attorney_password($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Password has been changed successfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went worong, please try again!',
                'code' => '404'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    //add new payment
    public function payment() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->payment($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Payment added sucessfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Unknown credential , please try again!',
                'code' => 'Unknown credential , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
	//for selecting the default card
     public function default_card() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->default_card($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Payment details displyed sucessfully', 'payment_details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Unknown credential , Something is went wrong!',
                'code' => 'Unknown credential , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }

    // view the number of cards
    public function cardList() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->cardList($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Payment details displyed sucessfully', 'payment_details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'success',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
    // for default payment
     public function default_payment() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->default_payment($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Default Payment added sucessfully','flag' => '1');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'success',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
	//for creating the new request
     function request_type() {
        $postdata            = file_get_contents("php://input");
        $request            = json_decode($postdata);
        $user_id            = $request->user_id;
        $request_type       = $request->request_Type;
        $latitude           = $request->latitude;
        $longitude          = $request->longitude;
        $pickup_address     = $request->pickup_address;
        $request_date       = $request->request_date;
		$payment            = $request->payment;
		$description        = $request->description;
        $sub_request_type   = $request->sub_request_type;
		$old_date_timestamp = strtotime($request_date);
		$current_datetime1  = date('Y-m-d H:i:s');
		$converted_date     = date('Y-m-d H:i:s', $old_date_timestamp);  
        
       $query = $this->db->query("select (6387 * acos( cos( radians('$latitude') ) * cos( radians(latitude) )*  cos( radians(longitude) - radians('$longitude') ) + sin( radians('$latitude') ) * sin( radians(latitude) ) ) ) AS distance, `attorney_id`  from `attorneys_tbl`"
                . " where (6387 * acos( cos( radians('$latitude') )*  cos( radians(latitude) )  * cos( radians(longitude) - radians('$longitude') ) + sin( radians('$latitude') ) * sin( radians(latitude) ) ) ) <= 100  order by `distance` asc");
        $res = $query->result_array();
		
	
	   if($query){
		   $table = 'request_list';
            $ins = array(
			   // 'attorney_id'      => $contractor_id,
                'user_id'          => $user_id,
                'latitude'         => $latitude,
                'longitude'        => $longitude,
                'pickup_address'   => $pickup_address,
                'request_type'     => $request_type,
                'sub_request_type' =>$sub_request_type,
                'description'      => $description,
                'request_date'     => $converted_date,
				'ride_payment'     => $payment,
				'current_datetime' => $current_datetime1
		);
           $result = $this->db->insert($table, $ins);
            $last_id = $this->db->insert_id();
			
		foreach ($res as  $res12) {
		
			$contractor_id = $res12['contractor_id'];
			$distance = $res12['distance'];
			
		
			
			 $table1 = 'requested_attorney_details';
            $ins1 = array(
                'attorney_id'     => $contractor_id,
                'client_id'       => $user_id,
				'request_id'      =>$last_id,
                'distance'        => $distance,
               'current_datetime' => $current_datetime1
			);
            $result1 = $this->db->insert($table1, $ins1);
	
    $title = 'New request';
	$body = 'New request offer for  '  .$request_type;
	$productData = array('latitude'=>$latitude,'logitude'=>$longitude,'flag'=>'ride_offer','new request id'=>$user_id);
      
	if($res12->latitude != ' ' && $res12->longitude != ' ' && $distance <=30){
	$temp = $this->sendNotification($title,$body,$productData,$contractor_id,$request_type,$latitude,$longitude,$pickup_address,$user_id,$description,$sub_request_type,$distance,$converted_date,$payment);
      }
	}
	
}
if($result){
	$finresult = array('status' => 'success','request_id'=>$last_id);
  print json_encode($finresult, JSON_UNESCAPED_SLASHES);	
	  //get the emeregency contact number
		 $client_query = $this->db->query("SELECT * FROM  clients_tbl where client_id='" . $user_id . "'");
		 $client_res = $client_query->row_array();
		 
        $emeregency_number = $client_res['emergency_contact'];	
        $user_name = $client_res['first_name'].''.$client_res['last_name'];	
				$res = '';		
                 if(isset($emeregency_number)){
				// Find your Account Sid and Auth Token at twilio.com/console
				// DANGER! This is insecure. See http://twil.io/secure
				$sid    = "AC5d621429c6a4a06c40a8b6fd12117bf0";
				$token  = "8a26c39624970c5cce4f9f82c2d1199e";
				//$twilio = new Client($sid, $token);
				

			//$message = $twilio->messages
								  //->create(".$emeregency_number.", // to
										  // ["body" =>$user_name ." submitted request for ".$request_type ,"from" => "+12058501371"]
							//);
							

				// print($message->sid);
				 }
  
 }
  else{
     if($query->num_rows()==0) {
		$error_list[] = array(
                'message' => 'Attorney not found near you',
                'code' => '502'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
     }
 }
	 }
   //for sending the notification for nearby attorneys 
    public function sendNotification($title, $body, $productData, $user_id1,$request_type,$latitude,$longitude,$pickup_address,$user_id,$description,$sub_request_type,$distance,$converted_date,$payment) {
         $ch = curl_init();
         $query15 = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $user_id1 . "'");
		 $res_arr = $query15->row_array();
		 $request_attorney_id = $res_arr['attorney_id'];
		 $token = $res_arr['token']; //token here
		 $title = $title;
          $body = $body;
          $notification = array('title' => $title, 'text' => $body, 'data'=>$productData);
		 
         $arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
         $json = json_encode($arrayToSend);
        
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key= AAAAWTbR6U8:APA91bHGBC6AeEmDpNEjmUnd58XnWwKUFp1KbPUV7hASXiF7tJp85HPlWBYdsp7TZWaHn3HAcbaDrnCiXrWCw5iGsrUqQSxyUTGzg3r0rDsWLVAJ1kuluYpflIxpidxZpu2VBDNdn0wP'; // key here
        //Setup curl, add headers and post parameters.
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        
        $response = curl_exec($ch);
		
       if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }
		$current_datetime = date('Y-m-d H:i:s');
        curl_close($ch);
         $cur_message = json_decode($response);
       /* if ($cur_message->success == 1){
			
			$this->db->select('*');
			$this->db->order_by('request_id','desc');
			$this->db->limit(1);
			$query14 = $this->db->get('request_list');
			$last_inserted_id = $query14->row_array();
			$req_id = $last_inserted_id['request_id'];

             $data = json_decode($response, true);
             if($data){
              $table1 = 'requested_attorney_details';
            $ins1 = array(
                'attorney_id' => $request_attorney_id,
                'client_id' => $user_id,
				'request_id' =>$req_id,
                'distance' => $distance,
               'current_datetime' => $current_datetime
			);
            $result1 = $this->db->insert($table1, $ins1);
        }
         
              
		}*/
		
        
    } 
    
    //to update the attorney location
    public function updateAttorneyLocation() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->updateAttorneyLocation($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Data updated successfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'something went wrong , please try again!',
                'code' => 'something went wrong , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    	
	//attorney to show the users request
    public function requestList() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->requestList($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Request details displyed sucessfully', 'request_details' => $result);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'No Data is Available',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
	// code for attorney to accept or decline the request
    public function accept_decline() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $attorney_id = $request->attorney_id;
        $flag = $request->flag;
        $request_id = $request->request_id;
         $con_query = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $attorney_id . "'");
         $con_res = $con_query->row_array();
        $attorney_name = $con_res['first_name'].' '.$con_res['last_name'];
        if($flag=='1'){
           $decision = 'accept';
            $query = $this->db->query("update requested_attorney_details set flag='".$decision."' where request_id='". $request_id."' and attorney_id='".$attorney_id."'");
          $query12 = $this->db->query("update request_list set flag='".$decision."' where request_id='". $request_id."'");
             if($query){
			//$del_query = $this->db->query("delete  from requested_attorney_details where request_id ='". $request_id."' and attorney_id !='".$attorney_id."'");	 
         $finresult = array('status' => 'success', 'message' => 'Request is Accepted');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);  
             $title = 'Request Accepted';
	$body = $attorney_name.'accepted your request';
        
	$productData = array('request_id'=>$request_id);
         $temp = $this->sendAcceptNotification($title,$body,$productData,$request_id);
       }
         else {
            $error_list[] = array(
                'message' => 'something went wrong , please try again!',
                'code' => 'something went wrong , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        } 
           
   }
     else if($flag=='0'){
         $decision = 'decline'; 
         $query12 = $this->db->query("update request_list set flag='".$decision."',cancel='1'  where request_id='". $request_id."'");
	$query = $this->db->query("update requested_attorney_details set flag='".$decision."',cancel='1' where request_id='". $request_id."'");
         if($query){
			 $del_query = $this->db->query("delete  from requested_attorney_details where request_id ='". $request_id."' and attorney_id ='".$attorney_id."'");	 
         $finresult = array('status' => 'success', 'message' => 'Request is declined','request_id'=>$request_id);
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);     
       }
         else {
            $error_list[] = array(
                'message' => 'something went wrong , please try again!',
                'code' => 'something went wrong , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        } 
       }
       else {
        $decision = 'pending';    
       }
       
        }
   
    // when attorney is accepted then send the notification to the user
    public function sendAcceptNotification($title, $body, $productData,$request_id) {
    $ch = curl_init();
    
    $query154 = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $request_id . "'");
         $res_arr4 = $query154->row_array();
         $user_id = $res_arr4['user_id'];
         $query15 = $this->db->query("SELECT * FROM  clients_tbl where client_id='" . $user_id . "'");
         $res_arr = $query15->row_array();
         $request_attorney_id = $res_arr['contractor_id'];
         $token = $res_arr['token']; //token here
         $title = $title;
        $body = $body;
       $notification = array('title' => $title, 'text' => $body, 'data'=>$productData);
       $arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
        $json = json_encode($arrayToSend);
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key= AAAAWTbR6U8:APA91bHGBC6AeEmDpNEjmUnd58XnWwKUFp1KbPUV7hASXiF7tJp85HPlWBYdsp7TZWaHn3HAcbaDrnCiXrWCw5iGsrUqQSxyUTGzg3r0rDsWLVAJ1kuluYpflIxpidxZpu2VBDNdn0wP'; // key here
        //Setup curl, add headers and post parameters.
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        //Send the request
        $response = curl_exec($ch);
       if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);
       $cur_message = json_decode($response);
       if ($cur_message->success == 1){
             $data = json_decode($response, true);
          //  $finresult = array('status' => 'success','request_id'=>$request_id);
              // print json_encode($finresult, JSON_UNESCAPED_SLASHES);
		}
        else{
            return false;
		}
    } 
  
  //make payment api//
    public function make_payment(){
      $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
       $request_id = $request->request_id; 
	   $category_id =  $request->category_id; 
       $query1 = $this->db->query("update  request_list set payment = '$10' where request_id='" .$request_id."'");
      
        $query123 = $this->db->query("SELECT * FROM  request_list where request_id='" .$request_id."'");
		 $res = $query123->row_array();
		$cat_query = $this->db->query("SELECT * FROM  jobcategories_tbl where job_category_id='" .$category_id."'");
        $cat_res = $cat_query->row_array();
        if($query123->num_rows()>0 || $cat_query->num_rows()>0){
       $data['Price'] = $cat_res['price'];
        $var[]=$data;
        
         $finresult = array('status' => 'success', 'message' => 'Payment details','payment_details' => $var);
        print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        }
     }
     
	 //code for to cancel the request
      function cancel_request() {
         $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $request_id = $request->request_id;
        $reason = $request->reason;
        $table = 'cancel_requests';
        $ins = array(
            'request_id' => $request_id,
            'reason' => $reason
           
        );
         $query12 = $this->db->query("select * from requested_attorney_details where request_id ='" . $request_id . "'");
         $res =  $query12->row_array();
		 
         $attorney_id = $res['attorney_id'];
         $user_id = $res['client_id'];
         $query123 = $this->db->query("select * from clients_tbl where client_id ='" . $user_id . "'");
         $res123 =  $query123->row_array();
         $user_name = $res123['first_name'].' '.$res123['last_name'];
        $result = $this->db->insert($table, $ins);
       if($result){
       //$query = $this->db->query("delete from requested_attorney_details where request_id ='" . $request_id . "'");
	   $query = $this->db->query("update requested_attorney_details set request_cancel_flag = '1' ,reason = '".$reason."' where request_id = '".$request_id."'"); 
	   $query = $this->db->query("update request_list set request_cancel_flag = '1' ,reason = '".$reason."' where request_id = '".$request_id."'"); 
      if ($query) {
            $title = 'Request Cancelled';
	    $body = $user_name.'cancelled your request';
	    $productData = array('request_id'=>$request_id);
            $temp = $this->sendCancelRequestNotification($title,$body,$productData,$attorney_id);
             $finresult = array('status' => 'success','message' => 'Request is cancelled successfully');
               print json_encode($finresult, JSON_UNESCAPED_SLASHES);
            
            return true;
        }  else {
            $error_list[] = array(
                'message' => 'something went wrong , please try again!',
                'code' => 'something went wrong , please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        } 
    }
    }
    
    //to send the cancel notification
     public function sendCancelRequestNotification($title, $body, $productData,$attorney_id) {
         $ch = curl_init();
         $query15 = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $attorney_id . "'");
         $res_arr = $query15->row_array();
         $token = $res_arr['token'];
         $title = $title;
       $body = $body;
       $notification = array('title' => $title, 'text' => $body, 'data'=>$productData);
       $arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
       $json = json_encode($arrayToSend);
       $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key= AAAAWTbR6U8:APA91bHGBC6AeEmDpNEjmUnd58XnWwKUFp1KbPUV7hASXiF7tJp85HPlWBYdsp7TZWaHn3HAcbaDrnCiXrWCw5iGsrUqQSxyUTGzg3r0rDsWLVAJ1kuluYpflIxpidxZpu2VBDNdn0wP'; // key here
        //Setup curl, add headers and post parameters.
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        //Send the request
        $response = curl_exec($ch);
       if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);
    $cur_message = json_decode($response);
      if ($cur_message->success == 1){
             $data = json_decode($response, true);
           
              //$finresult = array('status' => 'success');
              // print json_encode($finresult, JSON_UNESCAPED_SLASHES);
		}
        else{
            return false;
		}
    } 
    
    //code for rating to attorney given by user
    public function ratingToAttorney() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->ratingToAttorney($request);
        if ($result) {
            $finresult = array('status' => 'success');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
	// code for when driver started the task
     function start_task() {
         $postdata = file_get_contents("php://input");
         $request = json_decode($postdata);
         $comment = $request->comment;
         $request_id = $request->request_id;
         $taskStatus = $request->taskStatus;
         $query = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $request_id . "'");
         $res = $query->row_array();
         $client_id = $res['client_id'];
         $attorney_id = $res['attorney_id'];
         $query12 = $this->db->query("SELECT * FROM  clients_tbl where client_id='" . $client_id . "'");
         $res12 = $query12->row_array();
         $query123 = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $attorney_id . "'");
         $res123 = $query123->row_array();
          $attorney_name = $res123['first_name'].' '.$res123['last_name'];
       
       if($taskStatus=='StartTask'){
           
            $update_query = $this->db->query("update requested_attorney_details set comment = '".$comment."',start_task='1' where request_id= '".$request_id."'"); 
           $update_query1 = $this->db->query("update request_list set comment = '".$comment."',start_task='1' where request_id= '".$request_id."'"); 
            if($update_query){
				$finresult = array('status' => 'success');
               print json_encode($finresult, JSON_UNESCAPED_SLASHES);
                
         $title = 'Start task';
	$body = 'Started task'.$attorney_name;
        
	$productData = array('request_id'=>$request_id);
        $temp = $this->sendStartTasktNotification($title,$body,$productData,$request_id);
            }
           
       }
       
    }
    
	//when  attorney has started the task then send the notification to the user
     public function sendStartTasktNotification($title, $body, $productData,$request_id) {
    $ch = curl_init();
         $query15 = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $request_id . "'");
         $res_arr = $query15->row_array();
         $user_id  = $res_arr['client_id'];
         $query17 = $this->db->query("SELECT * FROM  clients_tbl where client_id='" . $user_id . "'");
         $res_arr17 = $query17->row_array();
         $token = $res_arr17['token']; //token here
         $title = $title;
        $body = $body;
        $notification = array('title' => $title, 'text' => $body, 'data'=>$productData);
        $arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
        $json = json_encode($arrayToSend);
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key= AAAAWTbR6U8:APA91bHGBC6AeEmDpNEjmUnd58XnWwKUFp1KbPUV7hASXiF7tJp85HPlWBYdsp7TZWaHn3HAcbaDrnCiXrWCw5iGsrUqQSxyUTGzg3r0rDsWLVAJ1kuluYpflIxpidxZpu2VBDNdn0wP'; // key here
        //Setup curl, add headers and post parameters.
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        //Send the request
        $response = curl_exec($ch);
       if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);
       $cur_message = json_decode($response);
       if ($cur_message->success == 1){
             $data = json_decode($response, true);
            
		}
        else{
            return false;
		}
    } 
    
	//code for when attorney has completed there task
    function end_task() {
          $postdata = file_get_contents("php://input");
          $request = json_decode($postdata);
          $comment = $request->comment;
          $request_id = $request->request_id;
          $taskStatus = $request->taskStatus;
          $query = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $request_id . "'");
          $res = $query->row_array();
          $attorney_id = $res['attorney_id'];
          $query12 = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $attorney_id . "'");
          $res12 = $query12->row_array();
       $attorney_name = $res12['first_name'].' '.$res12['last_name'];
       
       if($taskStatus=='EndTask'){
           $update_query = $this->db->query("update requested_attorney_details set comment = '".$comment."',end_task='1' where request_id= '".$request_id."'"); 
           $update_query12 = $this->db->query("update request_list set comment = '".$comment."',end_task='1' where request_id= '".$request_id."'"); 
            if($update_query){
				 $finresult = array('status' => 'success');
               print json_encode($finresult, JSON_UNESCAPED_SLASHES);
         $title = 'Completed task';
	$body = 'Completed task by'.$attorney_name;
        
	$productData = array('request_id'=>$request_id);
        $temp = $this->sendEndTasktNotification($title,$body,$productData,$request_id);
            }
           
       }
       
    }
    
	//code for send the notification when attorney has completed there task
     public function sendEndTasktNotification($title, $body, $productData,$request_id) {
    $ch = curl_init();
         $query15 = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $request_id . "'");
         $res_arr = $query15->row_array();
        $user_id  = $res_arr['client_id'];
       $query17 = $this->db->query("SELECT * FROM  clients_tbl where client_id='" . $user_id . "'");
         $res_arr17 = $query17->row_array();
        $token = $res_arr17['token']; //token here
         $title = $title;
        $body = $body;
       $notification = array('title' => $title, 'text' => $body, 'data'=>$productData);
      $arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
        $json = json_encode($arrayToSend);
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key= AAAAWTbR6U8:APA91bHGBC6AeEmDpNEjmUnd58XnWwKUFp1KbPUV7hASXiF7tJp85HPlWBYdsp7TZWaHn3HAcbaDrnCiXrWCw5iGsrUqQSxyUTGzg3r0rDsWLVAJ1kuluYpflIxpidxZpu2VBDNdn0wP'; // key here
        //Setup curl, add headers and post parameters.
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
       $response = curl_exec($ch);
       if (curl_errno($ch)) {
            return 'Curl error: ' . curl_error($ch);
        }
        curl_close($ch);
       $cur_message = json_decode($response);
       if ($cur_message->success == 1){
             $data = json_decode($response, true);
            
		}
        else{
            return false;
		}
    }
   
  // code for user to view there upcoming and past journeys   
   function upcomingOrpast() {
          $postdata = file_get_contents("php://input");
          $request = json_decode($postdata);
          $user_id = $request->user_id;
          $flag = $request->flag;
        
          $current_date = date('Y-m-d H:i:s');
    
    $sel_query = $this->db->query("SELECT * FROM  request_list rl where user_id='" . $user_id . "' and  request_date != ' ' and request_date != '0' and request_date > '$current_date'");
	$upcoming_res = $sel_query->result_array();
			
           foreach($upcoming_res as $up_res){
	       if(($up_res['flag'] =='accept')&& ($up_res['flag'] !='')){
			 
				$get_att_details = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $up_res['request_id'] . "' and client_id='".$user_id."' and flag='accept'");
				$att_res = $get_att_details->row_array();
				$accept_query = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $att_res['attorney_id'] . "'");
				$accept_res = $accept_query->row_array();
				
				$data2['Attorney Id'] = $accept_res['attorney_id'];
				$data2['Attorney Name'] = $accept_res['first_name'].' '.$accept_res['last_name'];
                $req_date = $up_res['request_date'];
			    $new = date('M d, Y h:m a', strtotime($req_date));  
                $data2['Request_id'] = $up_res['request_id'];
                $data2['Request Type'] = $up_res['request_type'];
             
                $data2['Latitude'] = $up_res['latitude'];
                $data2['Longitude'] = $up_res['longitude'];
                $data2['Pickup Address'] = $up_res['pickup_address'];
                $data2['Description'] = $up_res['description'];
                $data2['Request Date'] = $new;
			    $data2['Start Task'] =  $up_res['start_task'];
				 $data2['End Task'] =  $up_res['end_task'];
				  $data2['Agree By Client'] = $up_res['agree_by_client'];
			   $data2['Agree By Contractor'] = $up_res['agree_by_attorney'];
				 $data2['Request Flag'] =  $up_res['request_cancel_flag'];
				 $data2['Cancel Reason'] = $up_res['reason'];
				
		       $data2['Payment'] = $up_res['ride_payment'];
			  
			   
               $var[] = $data2; 			   
		 }
	          else{
				  
				  $req_date1 = $up_res['request_date'];
			    $new1 = date('M d, Y h:m a', strtotime($req_date1)); 
			   $data['Request_id'] = $up_res['request_id'];
                $data['Request Type'] = $up_res['request_type'];
                $data['Latitude'] = $up_res['latitude'];
                $data['Longitude'] = $up_res['longitude'];
                $data['Pickup Address'] = $up_res['pickup_address'];
                $data['Description'] = $up_res['description'];
               $data['Request Date'] = $new1;
			   $data['Start Task'] =  $up_res['start_task'];
				 $data['End Task'] =  $up_res['end_task'];
				  $data['Agree By Client'] = $up_res['agree_by_client'];
			   $data['Agree By Contractor'] = $up_res['agree_by_attorney'];
			   
				 $data['Request Flag'] =  $up_res['request_cancel_flag'];
				 $data['Cancel Reason'] = $up_res['reason'];
			    $data['Payment'] = $up_res['ride_payment'];	
				
                  $var[] = $data; 				
		}
	   
		 }
	$sel_query12 = $this->db->query("SELECT * FROM  request_list rl where user_id='" . $user_id . "' and  request_date != ' ' and request_date != '0' and request_date < '$current_date'");
             $past_result = $sel_query12->result_array();
       foreach($past_result as $past_res){
		    if(($past_res['flag'] =='accept')&& ($past_res['flag'] !='')){
			 
				$get_att_details = $this->db->query("SELECT * FROM  requested_attorney_details where request_id='" . $past_res['request_id'] . "' and client_id='".$user_id."' and flag='accept'");
					$att_res = $get_att_details->row_array();
				 $accept_query = $this->db->query("SELECT * FROM  attorneys_tbl where attorney_id='" . $att_res['attorney_id'] . "'");
				$accept_res = $accept_query->row_array(); 
				
               $req_date12 = $past_res['request_date'];
                $new12 = date('M d, Y h:m a', strtotime($req_date12)); 
                $data1['Attorney Id'] = $accept_res['attorney_id'];
				$data1['Attorney Name'] = $accept_res['first_name'].' '.$accept_res['last_name'];				
                $data1['Request_id'] = $past_res['request_id'];
                $data1['Request Type'] = $past_res['request_type'];
                $data1['Latitude'] = $past_res['latitude'];
                $data1['Longitude'] = $past_res['longitude'];
                $data1['Pickup Address'] = $past_res['pickup_address'];
                $data1['Description'] = $past_res['description'];
                $data1['Request Date'] = $new12;
				$data1['Start Task'] =  $past_res['start_task'];
				 $data1['End Task'] =  $past_res['end_task'];
				 $data1['Agree By Client'] = $past_res['agree_by_client'];
			    $data1['Agree By Contractor'] = $past_res['agree_by_attorney'];
				 
				 if($past_res['request_cancel_flag']== '1'){
				
				$data1['Cancel Reason'] = $past_res['reason'];
				$data1['Payment'] = $past_res['ride_payment'];
				
				
				 }
				 $var2[] = $data1; 
			}
			
			
			else{
				$req_date12 = $past_res['request_date'];
                $new12 = date('M d, Y h:m a', strtotime($req_date12)); 
               	
                $data12['Request_id'] = $past_res['request_id'];
                $data12['Request Type'] = $past_res['request_type'];
                $data12['Latitude'] = $past_res['latitude'];
                $data12['Longitude'] = $past_res['longitude'];
                $data12['Pickup Address'] = $past_res['pickup_address'];
                $data12['Description'] = $past_res['description'];
                $data12['Request Date'] = $new12;
				$data12['Start Task'] =  $past_res['start_task'];
				 $data12['End Task'] =  $past_res['end_task'];
				 $data12['Agree By Client'] = $past_res['agree_by_client'];
			    $data12['Agree By Contractor'] = $past_res['agree_by_attorney'];
				 
				 if($past_res['request_cancel_flag']== '1'){
					
				
				$data12['Cancel Reason'] = $past_res['reason'];
				$data12['Payment'] = $past_res['ride_payment'];
				
				
			}
				 $var2[] = $data12; 
			}
	}
	
 if($flag == 'upcoming'){
     $finresult = array('status' => 'success','message' => 'Upcoming Request Details','upcoming_details'=>$var);
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
           
       
    }
    elseif($flag == 'past'){
      $finresult = array('status' => 'success','message' => 'Past Request Details','past_details'=>$var2);
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
    }
 else {
     $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult); 
 }
 
 }
        
 //attorney upcoming or past request list
 function attorneyUpcomingOrPast() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        
         $attorney_id = $request->attorney_id;
         $flag = $request->flag;
         $current_date = date('Y-m-d H:i:s');
         $sel_query = $this->db->query("SELECT * FROM  request_list rl join requested_attorney_details ra on(rl.request_id=ra.request_id)where ra.attorney_id='" . $attorney_id . "' and ra.flag='accept' and rl.request_date != ' ' and rl.request_date != '0' and rl.request_date > '$current_date'");
         $upcoming_res = $sel_query->result_array();
		foreach($upcoming_res as $up_res){
             
                $req_date = $up_res['request_date'];
                //  $new = date('M d, Y h:m a', strtotime($req_date));  
                 $new = date('M d, Y h:m a', strtotime($req_date)); 
              
                $data['Request_id'] = $up_res['request_id'];
                $data['Request Type'] = $up_res['request_type'];
                $data['UserId'] = $up_res['user_id'];
                $data['Latitude'] = $up_res['latitude'];
                $data['Longitude'] = $up_res['longitude'];
                $data['Pickup Address'] = $up_res['pickup_address'];
                $data['Description'] = $up_res['description'];
               $data['Request Date'] = $new;
			    $data['Start Task'] =  $up_res['start_task'];
				 $data['End Task'] =  $up_res['end_task'];
			   $data['Payment'] = $up_res['payment'];
			    $var[] = $data; 
            }
            
             $sel_query12 = $this->db->query("SELECT * FROM  request_list rl join requested_attorney_details ra on(rl.request_id=ra.request_id)where ra.attorney_id='" . $attorney_id . "' and ra.flag='accept' and rl.request_date != ' ' and rl.request_date != '0' and rl.request_date < '$current_date'");
             $past_result = $sel_query12->result_array();
            //echo '<pre>'; print_r($past_result); 
            foreach($past_result as $past_res){
                //echo '<pre>'; print_r($past_res); 
               $req_date12 = $past_res['request_date'];
                $new12 = date('M d Y M H:i:sA', strtotime($req_date12));  
             // echo $new12; exit;
                $data1['Request_id'] = $past_res['request_id'];
                $data1['Request Type'] = $past_res['request_type'];
                $data1['UserId'] = $past_res['user_id'];
                $data1['Latitude'] = $past_res['latitude'];
                $data1['Longitude'] = $past_res['longitude'];
                $data1['Pickup Address'] = $past_res['pickup_address'];
                $data1['Description'] = $past_res['description'];
                $data1['Request Date'] = $new12;
				$data1['Start Task'] =  $past_res['start_task'];
				 $data1['End Task'] =  $past_res['end_task'];
				$data1['Payment'] = $past_res['payment'];
               $var2[] = $data1;
            }
          
    if($flag == 'upcoming'){
     $finresult = array('status' => 'success','message' => 'Upcoming Request Details','upcoming_details'=>$var);
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
           
       
    }
    else if($flag == 'past'){
      $finresult = array('status' => 'success','message' => 'Past Request Details','past_details'=>$var2);
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
    }
 else {
     $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult); 
 }
 
 }
 
 //code for receipt information
  public function receiptInformation() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->receiptInformation($request);
        if ($result) {
            $finresult = array('status' => 'success');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
	//code for tips information
	public function tipsInformation() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->tipsInformation($request);
        if ($result) {
            $finresult = array('status' => 'success');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
	
	
	//code for support and faq details 
	function supportFaqDetails() {
       
        $query = $this->db->query("SELECT * FROM  support_faq_tbl");
        if ($query->num_rows() > 0) {
            foreach ($query->result_array('news') as $row) {
                $data['SupportId'] = $row['support_id'];
               $data['Questions'] = $row['questions'];
                $data['Answers'] = $row['answers'];
               $var[] = $data;
            }
      $finresult = array('status' => 'success','message' => 'Support & Faq  Details','details'=>$var);
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
           
        } else {
             $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
	
	//code for for message information
	public function messageInformation() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->messageInformation($request);
        if ($result) {
            $finresult = array('status' => 'success');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'success',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
    
	
	//chat history
	function chatHistory() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
		 $attorney_id = $request->attorney_id;
		$client_id = $request->client_id;
        $query = $this->db->query("SELECT * FROM  message_tbl where attorney_id='" . $attorney_id . "'  and client_id ='".$client_id."' ORDER BY date_time DESC");
		
        if ($query->num_rows() > 0) {
            foreach ($query->result_array('news') as $row) {
				if($row['flag']=='client'){
					$query12 = $this->db->query("SELECT * FROM  clients_tbl  where client_id ='".$client_id."'");
					$client_res = $query12 ->row_array();
					$data['MessageId'] = $row['message_id'];
					$data['AttorneyId'] = $row['attorney_id'];
					$data['ClientId'] = $row['client_id'];
					$data['Message'] = $row['message'];
					$data['Flag'] = $row['flag'];
					$data['Name'] = $client_res['first_name'].' '.$client_res['last_name'];
					$data['DateTime'] = $row['date_time'];
					
					$var[] = $data;			   
				}
				else if($row['flag']=='contractor'){
					$query12 = $this->db->query("SELECT * FROM  attorneys_tbl  where attorney_id ='".$attorney_id."'");
					$client_res = $query12 ->row_array();	
					
					$data['MessageId'] = $row['message_id'];
					$data['AttorneyId'] = $row['attorney_number'];
					$data['ClientId'] = $row['client_id'];
					$data['Message'] = $row['message'];
					$data['Flag'] = $row['flag'];
					$data['Name'] = $client_res['first_name'].' '.$client_res['last_name'];
					$data['DateTime'] = $row['date_time'];
					
					$var[] = $data;
				}
			}
			$finresult = array('status' => 'success','message' => 'Message Details','details'=>$var);
			print json_encode($finresult, JSON_UNESCAPED_SLASHES);
           
        } else {
             $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'success',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
	
	//to show the all chats 
	function messageList() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
		$user_id = $request->user_id;
		$flag = $request->flag;
		/*
		if($flag == 'client'){
		$this->db->select('*');
		$this->db->where('flag',$flag);
		$this->db->group_by('client_id');
		$query12 = $this->db->get('message_tbl');
		$res12 = $query12->result_array();
		if($res12){
			foreach($res12 as $row){
				$att_id = $row['client_id'];
				$this->db->select('*');
				$this->db->where('flag',$flag);
				$this->db->where('client_id',$att_id);
				$this->db->order_by('message_id','desc');
				$this->db->limit(1);
				$query = $this->db->get('message_tbl');
				$client_res = $query->result_array();	
				$count1 = count($client_res);
				foreach($client_res as $cli){
					$query13 = $this->db->query("SELECT * FROM  clients_tbl  where client_id ='".$cli['client_id']."'");
					$att_res = $query13 ->row_array();
					$data['Name'] = $att_res['first_name'].' '.$att_res['last_name'];	
					$data['ClientId'] = $cli['client_id'];	
					$data['AttorneyId'] = $cli['attorney_id'];		
					$data['Message'] = $cli['message'];	
					$data['DateTime'] = $cli['date_time'];
					$var[] = $data;
				}
			}
			$finresult = array('status' => 'success','message' => 'Message Details','details'=>$var);
			print json_encode($finresult, JSON_UNESCAPED_SLASHES); 
		}
		else{
		$error_list[] = array(
						'message' => 'Data is not Available!',
						'code' => ' please try again!'
					);
					$finresult = array(
						'status' => 'success',
						'error_list' => $error_list
					);
					print json_encode($finresult);	
		}
		}

		else if($flag == 'contractor'){
			$this->db->select('*');
			$this->db->where('flag',$flag);
			$this->db->group_by('attorney_id');
			$query12 = $this->db->get('message_tbl');
			$res12 = $query12->result_array();
			if($res12){
				foreach($res12 as $row){
					$client_id = $row['attorney_id'];
					$this->db->select('*');
					$this->db->where('flag',$flag);
					$this->db->where('attorney_id',$client_id);
					$this->db->order_by('message_id','desc');
					$this->db->limit(1);
					$query = $this->db->get('message_tbl');
					$client_res = $query->result_array();	
					$count1 = count($client_res);
					foreach($client_res as $cli){
						$query13 = $this->db->query("SELECT * FROM  attorneys_tbl  where attorney_id ='".$cli['attorney_id']."'");
						$att_res = $query13 ->row_array();
						$data['Name'] = $att_res['first_name'].' '.$att_res['last_name'];		
						$data['ClientId'] = $cli['client_id'];	
						$data['AttorneyId'] = $cli['attorney_number'];		
						$data['Message'] = $cli['message'];	
						$data['DateTime'] = $cli['date_time'];
						$var[] = $data;
					}
				}
			
				$finresult = array('status' => 'success','message' => 'Message Details','details'=>$var);
				print json_encode($finresult, JSON_UNESCAPED_SLASHES); 
			}
			else {
			$error_list[] = array(
							'message' => 'Data is not Available!',
							'code' => ' please try again!'
						);
			$finresult = array(
					'status' => 'success',
					'error_list' => $error_list
				);
				print json_encode($finresult);	
			}
		}

		else{
		$error_list[] = array(
						'message' => 'Something is went wrong!',
						'code' => ' please try again!'
					);
					$finresult = array(
						'status' => 'failed',
						'error_list' => $error_list
					);
					print json_encode($finresult);	
		}
		*/
		if($flag == 'client') {
			$this->db->select('message_tbl.*,attorneys_tbl.first_name,attorneys_tbl.last_name');
			$this->db->from('message_tbl');
			$this->db->join('attorneys_tbl', 'message_tbl.attorney_id = attorneys_tbl.attorney_id');
			$this->db->where('flag',$flag);
			$this->db->where('client_id', $user_id);
			$this->db->group_by('attorney_id'); 
			$this->db->order_by('date_time', 'DESC');
			// $this->db->limit('1');
			$query12 = $this->db->get();
			$str = $this->db->last_query();
			// echo $str;			
			$res12 = $query12->result_array();
			if($res12){
				
				/*foreach($res12 as $row){
				}*/
				$finresult = array('status' => 'success','message' => 'Message Details','details'=>$res12);
				print json_encode($finresult, JSON_UNESCAPED_SLASHES);
			} else {
				$error_list[] = array(
								'message' => 'Data is not Available!',
								'code' => ' please try again!'
							);
				$finresult = array(
						'status' => 'success',
						'error_list' => $error_list
					);
				print json_encode($finresult);	
			}
		} 
		else if($flag == 'contractor' || $flag == 'attorney') {
			$this->db->select('*');
			$this->db->where('flag',$flag);
			$this->db->where('attorney_id', $user_id);
			$this->db->group_by('client_id'); 
			$this->db->order_by('date_time', 'DESC');
			// $this->db->limit('1');
			$query12 = $this->db->get('message_tbl');
			$res12 = $query12->result_array();
			if($res12){
				
				/*foreach($res12 as $row){
				}*/
				$finresult = array('status' => 'success','message' => 'Message Details','details'=>$res12);
				print json_encode($finresult, JSON_UNESCAPED_SLASHES);
			} else {
				$error_list[] = array(
								'message' => 'Data is not Available!',
								'code' => ' please try again!'
							);
				$finresult = array(
						'status' => 'success',
						'error_list' => $error_list
					);
				print json_encode($finresult);	
			}
		}
		else {
			$error_list[] = array(
				'message' => 'Something is went wrong!',
				'code' => ' please try again!'
			);
			$finresult = array(
				'status' => 'failed',
				'error_list' => $error_list
			);
			print json_encode($finresult);
		}
	}

    //get category list api
	function getCategories() {
			   
				$query = $this->db->query("SELECT * FROM  jobcategories_tbl");
				if ($query->num_rows() > 0) {
					foreach ($query->result_array('news') as $row) {
						$data['CategoryId'] = $row['job_category_id'];
					    $data['CategoryName'] = $row['category_name'];
						$data['CategoryPrice'] = $row['price'];
					    $var[] = $data;
					}
			  $finresult = array('status' => 'success','message' => 'Category Details','details'=>$var);
			 print json_encode($finresult, JSON_UNESCAPED_SLASHES);
				   
				} else {
					 $error_list[] = array(
						'message' => 'Data is not Available',
						'code' => ' please try again!'
					);
					$finresult = array(
						'status' => 'failed',
						'error_list' => $error_list
					);
					print json_encode($finresult);
				}
		}
		
	//Retainer Agreement
	public function retainerAgreement() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $result = $this->Model_web_service->retainerAgreement($request);
        if ($result) {
            $finresult = array('status' => 'success', 'message' => 'Retainer Agreement added sucessfully');
            print json_encode($finresult, JSON_UNESCAPED_SLASHES);
        } else {
            $error_list[] = array(
                'message' => 'Data is not Available!',
                'code' => 'please try again!'
            );
            $finresult = array(
                'status' => 'success',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
		

//update status of attorney

function update_status() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
		$attorney_id = $request->attorney_id;
	   $current_date = date('Y-m-d H:i:s');
        $query = $this->db->query("update attorneys_tbl set paid_status='1' , paid_date='".$current_date."' where attorney_id='".$attorney_id."'");
        if ($query) {
           
      $finresult = array('status' => 'success','message' => 'status updated successfully');
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
           
        } else {
             $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
	
	
//update paid status 
function update_paid_status() {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
		
		$request_id = $request->request_id;
		$transaction_id = $request->transaction_id;
		$paid_amount = $request->paid_amount;
	  
        $query = $this->db->query("update request_list set transaction_id='".$transaction_id."',paid_amount='".$paid_amount."',paid_flag='1' where request_id='".$request_id."'");
        if ($query) {
           
      $finresult = array('status' => 'success','message' => 'Paid status updated successfully');
     print json_encode($finresult, JSON_UNESCAPED_SLASHES);
      } else {
             $error_list[] = array(
                'message' => 'Something is went wrong!',
                'code' => ' please try again!'
            );
            $finresult = array(
                'status' => 'failed',
                'error_list' => $error_list
            );
            print json_encode($finresult);
        }
    }
}

?>