<?php

 class Webservice_model extends CI_Model {
      function __construct() {
            parent::__construct();
            date_default_timezone_set('Asia/Kolkata');
      }

      public function user_reg($data='') {

            $num = $this->db->where('phone', $data['phone_number'])->get('customers')->num_rows();
            if ($num > 0) {
                  $result = array('status'=>'error','message'=>'Mobile number Already Exists');
            }
            else {
                  $unique_id = $this->generate_unique();
                  $this->db->insert('customers', array('phone'=>$data['phone_number'],'first_name'=>$data['first_name'],'last_name'=>$data['last_name'],'password'=>md5($data['password'])));
                  $db_data = array();

                  $user_id = $this->db->insert_id();

                  $this->db->insert('cust_company_list', array('user_id'=>$user_id,'company_id'=>$data['company_id']));

                  $this->EncryptedPatientKey($unique_id, $user_id);

                  if ($user_id) {

                        $result = array('status'=>'success','auth_token'=>$unique_id,'user_id'=>$user_id, 
                        'phone'=>$data['phone_number'],'name'=>$data['first_name']." ".$data['last_name']);
                  } else {
                       $result = array('status'=>'error','message'=>'Something Went wrong');
                  }
            }
            return $result;

      }

      public function generate_unique() {

      $unqe = md5(uniqid(time().mt_rand(), true));

      return $unqe;

      }
      public function EncryptedPatientKey($unique_id, $user_id) {

            $this->db->insert('auth_table', array('cust_id'=>$user_id,'unique_id'=>$unique_id));

      }

      public function login($request='') {

            $this->db->where("phone = '".$request['phone_number']."'");

            $this->db->where('password', md5($request['password']));

            $this->db->where('status !=', 0);

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

            if ($query->num_rows() > 0) {

                  $unique_id = $this->generate_unique();

                  $rs = $query->row();

                  $this->EncryptedPatientKey($unique_id, $rs->customer_id);

                  return $result = array('status'=>'success','user_id'=>$rs->customer_id, 
                        'auth_token'=>$unique_id,'phone'=>$rs->phone, 
                        'name'=>$rs->first_name." ".$rs->last_name);

            } else {

                  return false;
            }

      }

      public function company_list() {

            $data = "SELECT id AS company_id, company_name AS company_name FROM `company` ORDER BY id DESC";

            $query = $this->db->query($data)->result();

            if($query){

                  return $query;

            }else{ 

                  return false;

            }

      }

      public function edit_user($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $data = array();

                  $custCompanyId = array();

                  if (isset($request['company_id']) && $request['company_id'] != '') {

                        $custCompanyId['company_id'] = $request['company_id'];

                  }

                  if (isset($request['first_name']) && $request['first_name'] != '') {

                        $data['first_name'] = $request['first_name'];

                  }

                  if (isset($request['last_name']) && $request['last_name'] != '') {

                        $data['last_name'] = $request['last_name'];

                  }

                  if (EMPTY($request['last_name'])) {

                        $data['last_name'] = "";

                  }

                  if (isset($request['phone']) && $request['phone'] != '') {

                        $data['phone'] = $request['phone'];

                  }

                  $rs = $query->row();

                  $this->db->where('customer_id', $rs->cust_id)->update('customers', $data);

                  $this->db->where('user_id', $rs->cust_id)->update('cust_company_list', $custCompanyId);

                  return true;

            } else {

                  return false;

            }

      }

      public function complaints($request) {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $data = array('complaint'=>$request['complaint'],'user_id'=>$rs->cust_id);

                  $this->db->insert('complaints', $data);

                  return $result = array('status'=>'success');

            } else {

                  return false;

            }

      }

      public function save_token($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $id = $rs->cust_id;

                  $data = array('fcm_token'=>$request['fcm_token']);

                  $result = $this->db->where('customer_id', $id)->update('customers', $data);

                  return $result;

            } else {

                  return false;

            }

      }

      public function forgetpassword($request='') {

            $query = $this->db->where('phone', $request['phone_number'])->get('customers');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $user_id = $rs->customer_id;

                  $data = array('password'=>md5($request['new_password']));

                  $this->db->where('customer_id', $user_id);

                  $this->db->update('customers',$data);

                  return $result = array('status'=>'success');

            } else {

                  return false;

            }

      }

      public function update_password($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $user_id = $rs->cust_id;

                  $data = array('password'=>md5($request['new_password']));

                  $this->db->where('customer_id', $user_id);

                  $this->db->update('customers',$data);

                  return $result = array('status'=>'success');

            } else {

                  return false;

            }

      }

      public function profile($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $query_result = $query->row();

                  $customer_id = $query_result->cust_id;

                  $data = "SELECT company.id AS company_id, customers.customer_id, customers.phone AS phone, 
                  CONCAT(customers.first_name,' ',customers.last_name) AS name, 
                  company.company_name AS company_name, customers.profile_image
                  FROM customers INNER JOIN cust_company_list ON customers.customer_id = cust_company_list.user_id 
                  INNER JOIN company ON cust_company_list.company_id = company.id  
                  WHERE customers.customer_id = '$customer_id' ";
      				  //print_r($data);exit();
                  $result = $this->db->query($data);  

                  $rs = $result->row();

                  return $result = array('id'=>$rs->customer_id,'phone'=>$rs->phone, 
                        'name'=>$rs->name,'company_name'=>$rs->company_name, 
                        'profile_photo'=>$rs->profile_image,'company_id'=>$rs->company_id);
                  
            } else {

                  return false;
            }

      }

      public function update_user_location($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $id = $rs->cust_id;

                  $data = array('user_latitude'=>$request['latitude'],'user_longitude'=>$request['longitude']);

                  $result = $this->db->where('customer_id', $id)->update('customers', $data);
                  if($result){

                        return $result;

                  }else{

                        return false;

                  }


            } else {

                  return false;

            }

      }

      public function update_profile_photo($request) {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $data = array('profile_image'=>$request['profile_photo']);

                  $this->db->where('customer_id', $rs->cust_id)->update('customers', $data);

                  return true;

            } else {

                  return false;
            }

      }

      public function call_ambulance($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $cusrimer_id = $rs->cust_id;

                  $customerDetails = $data = "SELECT CONCAT(c.first_name,' ',c.last_name) AS patient_name,
                  cust_company_list.company_id AS company_id, c.phone FROM customers AS c 
                  LEFT JOIN cust_company_list ON cust_company_list.user_id = c.customer_id 
                  WHERE c.customer_id = '$cusrimer_id'";

                  $result = $this->db->query($customerDetails)->row();

                  $getDistance = $this->GetDrivingDistance($request['source_latitude'], $request['destination_latitude'], $request['source_longitude'], $request['destination_longitude']);

                  $distanceValue = $getDistance['distanceValue'] * 0.001;

                  $timeValue = $getDistance['timeValue'] * 0.0166667;

                  if($result){

                        $data = array('total_time'=>$timeValue,
                              'trip_distance'=>$distanceValue,
                              'company_id'=>$result->company_id,
                              'customer_id'=>$cusrimer_id,
                              'patient_name'=>$result->patient_name,
                              'phone'=>$result->phone,
                              'pickup_location'=>$request['source_name'],
                              'pickup_lat'=>$request['source_latitude'],
                              'pickup_lng'=>$request['source_longitude'],
                              'drop_location'=>$request['destination_name'],
                              'drop_lat'=>$request['destination_latitude'],
                              'drop_lng'=>$request['destination_longitude'],
                              'request_type'=>$request['trip_type'],
                              'driver_assign_status'=>2,
                              'payment_mode'=>0,
                              'status'=>'3');
                        $this->db->insert('transport_details', $data);
                        $last_id = $this->db->insert_id();
                  }else{

                        return false;

                  }
                  return $result = array('request_id'=>$last_id);

            } else {

                  return false;

            }

      }

      public function nearest_ambulance($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $cust_id = $rs->cust_id;

                  $data1 = "SELECT * FROM setting WHERE id = '1' ";

                  $query1 = $this->db->query($data1);

                  $rs = $query1->row();

                  $radius = $rs->radius;

                  $customerDetails = $this->db->query("SELECT customers.user_latitude, 
                        customers.user_longitude FROM `customers` WHERE customers.customer_id =".$cust_id)->row();

                  $data = $this->db->query("SELECT d.book_status, d.driver_id, d.status, d.is_online, d.online_start_time, d.online_end_time, (((acos(sin((".$customerDetails->user_latitude."*pi()/180)) * sin((lat_driver*pi()/180)) + cos((".$customerDetails->user_latitude."*pi()/180)) * cos((lat_driver*pi()/180)) * cos(((".$customerDetails->user_longitude." - lng_driver)*pi()/180))))*180/pi())*60*1.1515) as distance FROM drivers AS d WHERE d.status = '1' AND d.is_online = '1' AND d.book_status = '0' AND d.online_start_time < DATE_FORMAT(now(),'%H:%i') AND d.online_end_time > DATE_FORMAT(now(),'%H:%i') HAVING distance < ".$radius."")->result_array();

                  $nonScheduledDriver = $this->db->query("SELECT driver_id FROM `transport_details` WHERE is_scheduled = 1")->result_array();

                  if (EMPTY($nonScheduledDriver)){

                        $nonScheduledDriver[] =  array('driver_id'=>'0' );;
                  }

                  foreach($data as $row){

                        $driverList[] = $row['driver_id'];

                        foreach ($nonScheduledDriver as $row1) {

                              $nonScheduledDriver1[] = $row1['driver_id'];
                        }

                  }
                  $nonScheduledDriverList = array_diff($driverList,$nonScheduledDriver1);

                  if($nonScheduledDriverList){

                        return $result = array('ambulace_count'=>COUNT($nonScheduledDriverList),'distance'=>$radius.'Km');

                  }else{

                        return $result = array('ambulace_count'=>'0','distance'=>'0'.'Km');
                  }     

            } else {

                  return false;
            }

      }

      public function trip_completion_details($request='') {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $cust_id = $rs->cust_id;

                  $id = $request['trip_id'];

                  $data = "SELECT CONCAT(transport_details.trip_distance,' ','km') AS distance, transport_details.total_time AS time, transport_details.trip_cost AS total_amount, drivers.profile_image AS driver_photo, CONCAT(drivers.first_name,' ',drivers.last_name) AS driver_name FROM transport_details LEFT JOIN drivers ON transport_details.driver_id = drivers.driver_id WHERE transport_details.transport_id = '$id' AND transport_details.status = '6' AND transport_details.customer_id = '$cust_id' ";

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

                  $result = $query->row();

                  return $result;

            } else {

                  return false;

            }

      }

      public function cancel_request($request) {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            $queryResult = $this->db->where('transport_id', $request['request_id'])->get('transport_details');

            if ($query->num_rows() > 0 && $queryResult->num_rows()) {

                  $rs = $query->row();

                  $user_id = $rs->cust_id;

                  $id = $request["request_id"];

                  $result = $this->db->where('transport_id', $id)->where('customer_id', $user_id)->update('transport_details', array('status'=>'9'));

                  if($result){

                        return $result;

                  }else{

                        return false;
                  }


            } else {

                  return false;

            }

      }

      public function trip_cancel($request) {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            $rs = $query->row();

            $cust_id = $rs->cust_id;

            if ($query->num_rows() > 0) {

                  $id = $request["trip_id"];

                  $result = $this->db->where('transport_id', $id)->update('transport_details', array('status'=>'2'));

                  $data2 = "SELECT * FROM transport_details WHERE customer_id = '$cust_id' AND transport_id = '$id' ORDER BY transport_id DESC";

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

                  $rs2 = $query->row();

                  $driv_id = $rs2->driver_id;

                  $this->db->where('driver_id', $driv_id)->update('drivers', array('book_status'=>0));

                  $data3 = "SELECT * FROM drivers WHERE driver_id = '$driv_id'";

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

                  $rs3 = $query->row();

                  $fcm = $rs3->fcm_token;

                  $fcm_data = array('id'=>$id,'title'=>'NEMT','message'=>'Request Cancelled');

                  $this->push_sent_cancel($fcm, $fcm_data);

                  return $result;

            } else {

                  return false;

            }

      }

      public function push_sent_cancel($fcm_token, $fcm_data) {

            $data1 = "SELECT * FROM setting WHERE id = '1' ";
            $query1 = $this->db->query($data1);
            $rs = $query1->row();
            $key = $rs->google_api_key;
            $data = "{ \"notification\": { \"title\": \"".$fcm_data['title']."\", \"text\": \"".$fcm_data['message']."\", \"sound\": \"ringtone_driver\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"trip_id\" : \"".$fcm_data['id']."\", \"trip_status\" : 0}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_token."\"}";

            $ch = curl_init("https://fcm.googleapis.com/fcm/send");

            $header = array('Content-Type: application/json','Authorization: key='.$key);

            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

            $out = curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            curl_exec($ch);

            curl_close($ch);

      }

      public function trip_history($request) {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $cust_id = $rs->cust_id;


                  $data1 = "SELECT * FROM setting WHERE id = '1' ";

                  $query1 = $this->db->query($data1);

                  $rs = $query1->row();

                  $currency = $rs->currency;

                  $data = "SELECT transport_details.total_time AS time,
                  vehicles.vehicle_reg_no AS ambulance_number,
                  CONCAT(transport_details.trip_cost,'.$currency.') AS total_amount, 
                  CONCAT(drivers.first_name,' ',drivers.last_name) AS driver_name,
                  transport_details.trip_distance AS total_distance,
                  transport_details.pickup_location AS source_name,
                  transport_details.drop_location AS destination_name,
                  drivers.profile_image AS driver_photo
                  FROM `transport_details` LEFT JOIN drivers 
                  ON transport_details.driver_id = drivers.driver_id LEFT JOIN
                  vehicles ON drivers.vehicle = vehicles.vehicle_id
                  WHERE transport_details.customer_id = '$cust_id' 
                  ORDER BY transport_details.transport_id DESC  ";
                  $query1 = $this->db->query($data)->result();

                  return $query1;

            } else {

                  return false;

            }

      }

      public function req_status($request='') {

            $query = $this->db->where('transport_id', $request['request_id'])->get('transport_details');

            if ($query->num_rows() > 0) {

                  $query = $this->db->select("transport_details.status AS request_status, transport_details.transport_id AS trip_id,
                        CONCAT(transport_details.total_time,' ','min') AS time, CONCAT(transport_details.trip_distance,' ','km') AS distance, CONCAT(drivers.first_name,' ',drivers.last_name) AS driver_name, vehicles.vehicle_reg_no AS car_number, drivers.profile_image AS driver_photo, drivers.phone AS driver_phone_number, transport_details.pickup_lat AS source_latitude, transport_details.pickup_lng AS source_longitude, transport_details.drop_lat AS destination_latitude, transport_details.drop_lng AS destination_longitude")->from('transport_details')->join('drivers','transport_details.driver_id = drivers.driver_id','left')->join('vehicles','drivers.vehicle = vehicles.vehicle_id','left')->where('transport_details.transport_id', $request['request_id'])->get();

                  if ($query->num_rows() > 0) {

                        $result = $query->row();

                        return $result;

                  }
            } else {

                  return false;

            }

      }

      function statusof_app($request) {

            $query = $this->db->where('unique_id', $request['auth'])->get('auth_table');

            if ($query->num_rows() > 0) {

                  $rs = $query->row();

                  $cust_id = $rs->cust_id;

                  $res = "SELECT * FROM transport_details WHERE customer_id = '$cust_id' ORDER BY transport_id DESC LIMIT 0,1";

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

                  $rs = $query->row();

                  $booking_status = $rs->status;

                  $driver_id = $rs->driver_id;

                  $book_id = $rs->transport_id;

                  if ($booking_status == 4 || $booking_status == 5) {

                        $query1 = $this->db->select('CONCAT(transport_details.total_time," ","min") AS time,transport_details.transport_id AS trip_id,vehicles.vehicle_reg_no AS car_number,  CONCAT(transport_details.trip_distance," ","km") AS distance, drivers.profile_image AS driver_photo, drivers.phone AS driver_phone_number, transport_details.status AS request_status,  transport_details.pickup_lat AS source_latitude, transport_details.pickup_lng AS source_longitude, transport_details.drop_lat AS destination_latitude, transport_details.drop_lng AS destination_longitude, CONCAT(drivers.first_name," ",drivers.last_name) AS driver_name')->from('transport_details')->join('drivers','transport_details.driver_id = drivers.driver_id','left')->join('vehicles','drivers.vehicle = vehicles.vehicle_id','left')->where('transport_details.transport_id', 
                              $book_id)->get();

                        $result = $query1->row();
                        
                        return $result;

                  } else {

                        return 0;

                  }

            } else {
                 print json_encode(array('status'=>'error','code'=>'209','message'=>'Something Went wrong'));die();

           }
      }

      function status_driver($id) {

            $data = $this->db->query("SELECT *  FROM `transport_details` WHERE transport_id = '$id'")->row();

            if ($data->status == 6 && $data->cash_collection == 1) {
                  $driver_status = 4;
                  return $driver_status;
            }
            elseif($data->status == 6 && $data->cash_collection == 0) {
                  $driver_status = 3;
                  return $driver_status;
            }
            elseif($data->status == 5) {
                  $driver_status = 2;
                  return $driver_status;
            }
            elseif($data->car_arrival == 1 OR $data->car_arrival == 2) {
                  $driver_status = 1;
                  return $driver_status;
            }
            else {
                  $driver_status = 0;
                  return $driver_status;
            }
      }

      public function GetDrivingDistance($lat1, $lat2, $long1, $long2) {

            $data1 = "SELECT * FROM setting WHERE id = '1' ";

            $query1 = $this->db->query($data1);

            $rs = $query1->row();

            $key = $rs->google_api_key;

            $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL"."&key=".$key;

            $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);

            $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];

            $distValue = $response_a['rows'][0]['elements'][0]['distance']['value'];

            $time = $response_a['rows'][0]['elements'][0]['duration']['text'];

            $timeValue = $response_a['rows'][0]['elements'][0]['duration']['value'];

            return array('distance'=>$dist,'distanceValue'=>$distValue,'time'=>$time,'timeValue'=>$timeValue);

      }

      public function phone_number_availability($data = array()){
            if(empty($data) || !isset($data['phone']) || empty($data['phone'])){
                  return 0;
            } 
            $sql = "SELECT * FROM customers WHERE phone LIKE '%".$data['phone']."' AND status IN (0,1)";
            $isAvailable = $this->db->query($sql);
            $isAvailable = $isAvailable->num_rows();

            return $isAvailable;
      }
}
?>