<?php
ob_start();
defined('BASEPATH')OR exit('No direct script access allowed');
header('Content-Type: text/html; charset=utf-8');
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');
}

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 Webservices extends CI_Controller {  
  public function __construct() {
    parent::__construct();
    $this->load->model('Webservice_model');
    $this->load->helper('url');
    $this->load->library('form_validation');
    $class = $this->router->fetch_class();
    $method = $this->router->fetch_method();
  if ($this->input->server('REQUEST_METHOD') == 'GET')
    $postdata = json_encode($_GET);
    else if ($this->input->server('REQUEST_METHOD') == 'POST')
      $postdata = file_get_contents("php://input");
  $auth = '';
    if (isset(apache_request_headers()['Auth'])) {
      $auth = apache_request_headers()['Auth'];
    }
    $this->last_id = set_log($class, $method, $postdata, $auth);
  }  

  public function user_registration() {
    header('Content-type: application/json');
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata, true);
  if(isset($request)){
      $config = array(
        array(
          'field'=>'phone_number',
          'label'=>'Phone Number',
          'rules'=>'required',
          'errors'=>array(
            'required'=>'You must provide your phone number',          ),
        ),
        array(
          'field'=>'password',
          'label'=>'Password',
          'rules'=>'required',
          'errors'=>array(
            'required'=>'You must provide your password.',
          )
        ),
        array(
          'field'=>'company_id',
          'label'=>'company_id',
          'rules'=>'required',
          'errors'=>array(
            'required'=>'You must provide company Id',
          )
        ),
        array(
          'field'=>'first_name',
          'label'=>'first name',
          'rules'=>'required',
          'errors'=>array(
            'required'=>'You must provide your first name',
          )
        )
      );
    $this->form_validation->set_data($request);
      $this->form_validation->set_rules($config);
    if($this->form_validation->run()==FALSE){
        $err = $this->form_validation->error_array();
        $result = array('status'=>'error','message'=>$err, 'error'=>'505');
        $this->response($result);
      }else{
        $result = $this->Webservice_model->user_reg($request);
        if ($result['status'] == 'success') {
          $result = array('status'=>"success", 
            'data'=>array('auth_token'=>$result['auth_token'], 
              'user'=>array('user_id'=>$result['user_id'], 
                'phone'=>$result['phone'], 'name'=>$result['name'])));
        } else {
          $result = array('status'=>'error','message'=>$result['message'], 'error'=>'501');
        }
        $this->response($result);
      }
    } else {
      $result = array('status'=>'error','message'=>'invalid Request','error'=>'505');
      $this->response($result);
    }
  }  

  public function response($res) {
    print json_encode($res);
  } 

  public function do_login() {
    header('Content-type: application/json'); 
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata, true);
    $result = $this->Webservice_model->login($request);

  if ($result['status'] == 'success') {
      $result = array('status'=>"success", 
        'data'=>array('auth_token'=>$result['auth_token'], 
          'user'=>array('user_id'=>$result['user_id'], 
            'phone'=>$result['phone'], 'name'=>$result['name'])));
    } else {
      $result = array('status'=>'error','message'=>'Unknown Credential! Try Again','error'=>'502');
    }
    $this->response($result);
  }  
  
  public function company_list() {
    header('Content-type: application/json');
    $result = $this->Webservice_model->company_list();
   if ($result) {
      print json_encode(array('status'=>'success','data'=>$result));
    } else {
      print json_encode(array('status'=>'error','message'=>'No Result Found','error'=>'502'));
    }
  }

  public function edit_user() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {
      $auth = apache_request_headers()['Auth'];
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true);
      $request['auth'] = $auth;

      $query = $this->db->where('unique_id', $auth)->get('auth_table');
      if ($query->num_rows() > 0) {    
        $rs = $query->row();
        $cust_id = $rs->cust_id;
        $phone = $request['phone'];
        $this->db->where('phone', $phone);
        $this->db->where('customer_id!=', $cust_id);
        $count = $this->db->get('customers')->result();

        if (count($count) == 0) {     
          $result = $this->Webservice_model->edit_user($request);

          if ($result) {       
            print json_encode(array('status'=>'success'));
          } else {       
            print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'508'));
          }   
        } else {     
          print json_encode(array('status'=>'error','message'=>'Mobile Number Already Exists','error'=>'508'));
        } 
      } else {   
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'508'));
      }
    }
  }

  public function complaints() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {
      $auth = apache_request_headers()['Auth'];
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true);
      $request['auth'] = $auth;
      $result = $this->Webservice_model->complaints($request);

      if ($result['status'] == 'success') {     
        print json_encode(array('status'=>'success'));
      } else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'601'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'You are not authorized to access the server', 
                              'error'=>'Authentication Failed'));
    }
  }

  public function save_fcmtoken() { 
    header('Content-type: application/json'); 

    if (isset(apache_request_headers()['Auth'])) {   
      $auth = apache_request_headers()['Auth'];
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true);
      $request['auth'] = $auth;
 
      if (isset($request['fcm_token'])) {
        $result = $this->Webservice_model->save_token($request);
        
        if ($result) {
          print json_encode(array('status'=>'success'));
        } else {
          print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'605'));
        }
      } else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'605'));
      } 
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'605'));
    }
  }

  public function forgot_password() { 
    header('Content-type: application/json');
    $postdata = file_get_contents("php://input"); 
    $request = json_decode($postdata, true); 

    if(isset($request['phone_number'])){
      $res = $this->Webservice_model->forgetPassword($request);
      if ($res) {
        echo json_encode(array('status'=>'success'));
      } else {   
        echo json_encode(array('status'=>'error','message'=>'Sorry. Please Enter Valid Phone Number'));
      }
    } else{  
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'508'));
    }
  }

  public function update_password() { 
    header('Content-type: application/json'); 

    if(isset(apache_request_headers()['Auth'])) {  
      $auth = apache_request_headers()['Auth'];
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true);
      $request['auth'] = $auth;
      $query = $this->db->where('unique_id', $auth)->get('auth_table');

      if ($query->num_rows() > 0) {    
        $rs = $query->row();
        $cust_id = $rs->cust_id;
        $this->db->where('customer_id=', $cust_id);
        $query1 = $this->db->get('customers');
        $result = $query1->row();

        if ($result->password == md5($request['current_password'])) {    
          $result = $this->Webservice_model->update_password($request);
          if ($result) {       
            print json_encode(array('status'=>'success'));
          } else { 
            print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'508'));
          }
        } else {     
          print json_encode(array('status'=>'error','message'=>'Invalid Old Password','error'=>'508'));
        } 
      } else {  
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'508')); 
      }
    }
  }

  public function get_profile() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {   
      $auth = apache_request_headers()['Auth'];
      $request = $_GET;
      $request['auth'] = $auth;
      $result = $this->Webservice_model->profile($request);

      if ($result) {
        print json_encode(array('status'=>'success','data' =>$result));
      } else {
        print json_encode(array('status'=>'error','code'=>'205','message'=>'Something Went wrong'));
      } 
    } else {
      print json_encode(array('status'=>'error','code'=>'205','message'=>'Something Went wrong')); 
    }
  }

  public function update_user_location() { 
    header('Content-type: application/json'); 

    if (isset(apache_request_headers()['Auth'])) {  
        $auth = apache_request_headers()['Auth'];
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata, true);
        $request['auth'] = $auth;

        if ($request['latitude'] && $request['longitude']) {
          $result = $this->Webservice_model->update_user_location($request);
        if ($result) {
          print json_encode(array('status'=>'success'));
        } else {
          print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'605'));
        }
      } else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'605'));
      } 
    } else {
     print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'605'));
    }
  }

  public function update_profile_photo() {
    header('Content-type: application/json');

    if (isset(apache_request_headers()['Auth'])) {
      $auth = apache_request_headers()['Auth'];
    
      if (is_uploaded_file($_FILES['profile_photo']['tmp_name'])) {
        $uploads_dir = 'assets/uploads/profile_pic/';
        $tmp_name = $_FILES['profile_photo']['tmp_name'];
        $pic_name = $_FILES['profile_photo']['name'];
        $pic_name = str_replace(' ','_', mt_rand().$pic_name);
        move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
        $request = $_POST;
        $request['profile_photo'] = $uploads_dir.$pic_name;
        $request['auth'] = $auth;
        $result = $this->Webservice_model->update_profile_photo($request);

        if ($result) {
          print json_encode(array('status'=>'success'));
        } else {
          print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'207'));
        }
      } else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'207'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'207'));
    }
  }

  public function call_ambulance() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true);
      $auth = apache_request_headers()['Auth'];
      $request['auth'] = $auth;
      if(!empty($request) && isset($request['trip_type']) && $request['trip_type'] != '' && 
         isset($request['source_name']) && !empty($request['source_name']) && 
         isset($request['source_latitude']) && !empty($request['source_latitude']) && 
         isset($request['destination_name']) && !empty($request['destination_name']) && 
         isset($request['source_longitude']) && !empty($request['source_longitude']) && 
         isset($request['destination_latitude']) && !empty($request['destination_latitude']) && 
         isset($request['destination_longitude']) && !empty($request['destination_longitude'])){

        $result = $this->Webservice_model->call_ambulance($request);
        if ($result) {
          print json_encode(array('status'=>'success','data'=>$result));
        } else {
          print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'507'));
        }
      } else {
        print json_encode(array('status'=>'error','message'=>'Required fields are empty','error'=>'508'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'Authentication Error','error'=>'509'));
    }
  }

  public function nearest_ambulance() {
    header('Content-type: application/json');
    if (!isset(apache_request_headers()['Auth']) || empty($auth = apache_request_headers()['Auth'])) {
      print json_encode(array('status'=>'error','message'=>'Auth Tocken Missing','error'=>'503'));exit;
    }

    $postdata = $_GET;
    if(empty($postdata) || 
       !isset($postdata['latitude']) || empty($postdata['latitude']) || 
       !isset($postdata['longitude']) || empty($postdata['longitude'])){
      print json_encode(array('status'=>'error','message'=>'Data missing','error'=>'504'));exit;
    }
    $postdata['auth'] = $auth;
    $result = $this->Webservice_model->nearest_ambulance($postdata);
    
    if($result) {
      print json_encode(array('status'=>'success','data'=>$result));exit;
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'505'));exit;
    }
  }

  public function trip_completion_details() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {   
      $auth = apache_request_headers()['Auth'];
      $request = $_GET;
      $request['auth'] = $auth;
      $result = $this->Webservice_model->trip_completion_details($request);
      if ($result) {
          print json_encode(array('status'=>'success','data'=>$result));
      } else {
        print json_encode(array('status'=>'error','message'=>'No Result Found','error'=>'602'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'602')); 
    }
  }
  public function request_cancelled() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {
      $auth = apache_request_headers()['Auth'];
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true); ;
      $request['auth'] = $auth;
      if (isset($request['request_id'])) {
        $result = $this->Webservice_model->cancel_request($request);
        if ($result) {
            print json_encode(array('status'=>'success'));
        } else {
          print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'602'));
        }
      } else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'602'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'602'));
    }
  }
  public function trip_cancel() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {   
      $auth = apache_request_headers()['Auth'];
      $postdata = file_get_contents("php://input");
      $request = json_decode($postdata, true); ;
      $request['auth'] = $auth;
      if (isset($request['trip_id'])) {
        $result = $this->Webservice_model->trip_cancel($request);
        if ($result) {
          print json_encode(array('status'=>'success'));
        } else {
          print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'1602'));
        }
      } else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'608'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'602'));
    }
  }

  public function trip_history() {  
    header('Content-type: application/json');
    if (isset(apache_request_headers()['Auth'])) {    
      $auth = apache_request_headers()['Auth'];
      $request['auth'] = $auth;
      $result = $this->Webservice_model->trip_history($request);
      if ($result) {
        print json_encode(array('status'=>'success','data'=>$result));
      } else {
        print json_encode(array('status'=>'success','data'=>[]));
      }  
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'503'));
    }
  }

  public function request_status() { 
    header('Content-type: application/json'); 
    $request = $_GET;
    if (isset($request['request_id'])) {   
      $result = $this->Webservice_model->req_status($request);

      if ($result->request_status == '0' || $result->request_status == '1' || $result->request_status == '3') {
        print json_encode(array('status'=>'success','data'=>array('request_status'=>'0')));
      } else if($result->request_status == '4' || $result->request_status == '5' || $result->request_status == '6' || $result->request_status == '8') {
          $result->request_status = '1';
          print json_encode(array('status'=>'success','data'=>$result));
      }   else {
        print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'606'));
      }
    } else {
      print json_encode(array('status'=>'error','message'=>'Something Went wrong','error'=>'607')); 
    }
  }

  public function app_status() { 
    header('Content-type: application/json'); 
    if (isset(apache_request_headers()['Auth'])) {   
      $auth = apache_request_headers()['Auth'];
      $request['auth'] = $auth;
      $result = $this->Webservice_model->statusof_app($request);

      if ($result) {
        $result->app_status = '1';
        $id = $result->trip_id;
        $drvr_status = $this->Webservice_model->status_driver($id);
        print json_encode(array('status'=>'success','data'=>$result));
      } else {
        print json_encode(array('status'=>'success','data'=>array('app_status'=>'0')));
      }
    } else { 
      print json_encode(array('status'=>'error','code'=>'209','message'=>'Something Went wrong'));
    }
  }

  public function phone_number_availability(){
    header('Content-type: application/json'); 
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata, true);

    if (!empty($request) && isset($request['phone']) && !empty($request['phone'])) {
      $phStatus = $this->Webservice_model->phone_number_availability($request);
      if($phStatus <= 0){
        print json_encode(array('status'=>'success','data'=>array('is_available'=>true)));
      } else {
        print json_encode(array('status'=>'success','data'=>array('is_available'=>false)));
      }
    } else {
      print json_encode(array('status'=>'error','code'=>'210','message'=>'Required Fields are empty.'));
    }
  }

  public function reminderCrone(){
    $ride_data = $this->Webservice_model->getReminderRide();
    if(empty($ride_data)){
      return;
    }
    foreach ($ride_data AS $ride) {
      $fcm_data = array('title'=>'Reminder','message'=>'Reminder Ride Request',
                        'request_id'=>$ride['transport_id']);
      push_sent_cancel($type,$ride['fcm_token'],$fcm_data);
    }
  }  

  public function driverAssignCrone(){
    $ride_data = $this->Webservice_model->driverAssignCrone();
    if(empty($ride_data)){
      return;
    }
    foreach ($ride_data AS $ride) {
      if(empty($ride['pickup_lat']) || empty($ride['pickup_lng'])){
        continue;
      }
      $ride_id = $ride['transport_id'];
      if($ride['request_type'] == 3 && 
        (empty($ride['appointment_time']) || 
         $ride['appointment_time'] < strtotime(date('Y-m-d H:i:s')) || 
         $ride['appointment_time'] > (strtotime(date('Y-m-d H:i:s'))+7200))){
        continue;
      }
      $driver_data = $this->Webservice_model->getAvailableDrivers($ride['pickup_lat'],$ride['pickup_lng'],$ride_id);
      if(empty($driver_data)){
        continue;
      }
      if(!empty($driver_data) && !empty($driver_data['driver_id']) && 
         !empty($driver_data['distance']) && !empty($driver_data['fcm_token'])){

          $this->db->update('transport_details',array('status'=>'3'),array('transport_id'=>$ride_id));
          $this->db->insert('driver_request',array('trip_id'=>$ride_id,
                                                   'driver_id'=>$driver_data['driver_id'],
                                                   'request_time'=>date('Y-m-d H:i:s'),'status'=>'0'));

        $type = ($ride['request_type'] == 3)?'2':'1';
        $fcm_data = array('title'=>'Ride Request','message'=>'Emergency Ride Request',
                          'request_id'=>$ride['transport_id']);
        push_sent_cancel($type,$driver_data['fcm_token'],$fcm_data);
      }
    }
  }
}?>