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

  /***************************************************************************************/
  /****************************************Mobile API's***********************************/

  public function checkMobAvailability($data = array()){
    $res = array('status'=>'success', 'message'=>'Mobile Number Available','data'=>array('phone'=>$data['phone'],'is_available'=>true));
    if(empty($data)){
      $res = array('status'=>'error','error'=>'901','message'=>'Something went wrong.');
      return $res;
    }
    $result = $this->db->get_where('customers',array('phone'=>$data['phone'],'country_code'=>$data['country_code']));
    if(!empty($result) && $result->num_rows() > 0){
      $res=array('status'=>'error','error'=>'902','message'=>'Mobile number already in use.');
    }
    return $res;
  }

  public function checkCustomerLogin($userLogData){
    $respArr = array('status'=>0);
    if(empty($userLogData)){
      return $returnStatus;
    }
    $result = $this->db->get_where('customers',array('email'=>$userLogData['email'],'status'=>'1'));
    if(empty($result) || $result->num_rows() < 1 || empty($custData = $result->row())){
      $respArr['status'] = 2;
      return $respArr;
    }
    $this->db->select("customer_id as id,is_otp_verified,phone as phone_number,TRIM(CONCAT(first_name,' ' ,IFNULL(last_name,''))) as user_name");
    $result = $this->db->get_where('customers',array('email'=>$userLogData['email'],
     'password'=>$userLogData['password'],
     'status'=>'1'));
    $respArr['status'] = 3;
    if(!empty($result) && $result->num_rows() == 1 && !empty($custData = $result->row())){
      $authdata = $this->insert_auth($custData->id);
      if($authdata){
        $custData->auth_token = $authdata;
        $respArr['data'] = $custData;
        $respArr['status'] = 1;
      }
    }
    return $respArr;
  }

  public function insert_auth($id){
    $static_string = time();
    $authToken = 'Dcarfixs'.sha1($static_string);
    $custData = $this->db->get_where('authtable',array('customer_id'=>$id));
    if(!empty($custData) && $custData->num_rows() > 0){
      $custData = $custData->row();
      $authToken = $custData->authtoken;
    } else {
      $this->db->insert('authtable',array('customer_id'=>$id,'authtoken'=>$authToken));
    }
    
    return $authToken;
  }

  public function createCustomer($customer_data = array()){
    $respArr = array('status'=>0);
    if(empty($customer_data)){
      $respArr['status'] = 0;
      return $respArr;
    }
    if(isset($customer_data['email']) && !empty($customer_data['email'])){
      $emailChk = $this->db->get_where('customers',array('email'=>$customer_data['email'],'status !='=>'2'));
      if(!empty($emailChk) && $emailChk->num_rows() > 0){
        $respArr['status'] = 2;
        return $respArr;
      }
    }
    if(isset($customer_data['phone']) && !empty($customer_data['phone'])){
      $phoneChk = $this->db->get_where('customers',array('phone'=>$customer_data['phone'],'status !='=>'2'));
      if(!empty($phoneChk) && $phoneChk->num_rows() > 0){
        $respArr['status'] = 3;
        return $respArr;
      }
    }
    $customer_data['first_name'] = $customer_data['name'];
    unset($customer_data['name']);
    if($this->db->insert('customers',$customer_data)){
      $last_id = $this->db->insert_id();
      $this->db->select("TRIM(CONCAT(first_name,' ' ,IFNULL(last_name,''))) as name,customer_id as user_id");
      $custData = $this->db->get_where('customers',array('customer_id'=>$last_id))->row();
      $authdata = $this->insert_auth($last_id);
      $custData->auth_token = $authdata;
      $respArr['data'] = $custData;
      $respArr['status'] = 1;
    }
    return $respArr;
  }

  public function get_customer_authtoken($auth = ''){
    $respArr = array('status'=>0,'error'=>'901','message'=>'Something Went Wrong.');
    if(empty($auth)){
      return $respArr;
    }
    $auth = $this->db->get_where('authtable',array('authtoken'=>$auth));
    if(!empty($auth) && $auth->num_rows() >= 1 && !empty($custAuth = $auth->row_array())){
      $respArr['status'] = 'success';
      $respArr['data'] = $custAuth;
    }else{
      $respArr['status'] = 'error';
      $respArr['error'] = '902';
      $respArr['message'] = 'Authtoken is not Valid';
    }
    return $respArr;
  }

  public function getBookedService($id = ''){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($id)){
      return $respArr;
    }
    $this->db->select('booking_id as id,scheduled_date as date,scheduled_time as time');
    $this->db->where('scheduled_date >',date('Y-m-d h:i'));
    $bookData = $this->db->get_where('bookings',array('customer_id'=>$id))->result_array();
    $respArr['status'] = 'success';
    $respArr['message'] = 'success';  
    if(!empty($bookData) && (count($bookData) > 0)){
      foreach ($bookData as $key => $value) {
        $bookData[$key]['date'] = (string) strtotime($value['date'])*1000;
        $bookData[$key]['date'] = $bookData[$key]['date']."";
      }
      $respArr['data']['booked_services'] = $bookData;
    }else{
      $respArr['data']['booked_services'] = [];
    }
    return $respArr;
  }

  public function addVehicleDetails($postData = array(),$customer_id = ''){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($postData)){
      return $respArr;
    }
    $car_name = $postData['vehicle_year'].' '.$postData['vehicle_make'].' '.$postData['vehicle_model'];
    $vehJson = array(
      'vehicle'    => $car_name,
      'attributes' => array(
          'Year'  => $postData['vehicle_year'],
          'Make'  => $postData['vehicle_make'],
          'Trim'  => $postData['vehicle_trim'],
          'Model' => $postData['vehicle_model'],
          'Engine'=> $postData['engine_no']
      )
    );
    $insert_array = array(
      'customer_id'   => $customer_id,
      'car_name'      => $car_name,
      'car_model'     => $postData['vehicle_model'],
      'car_maker'     => $postData['vehicle_make'],
      'car_loc_lat'   => $postData['car_loc_lat'],
      'car_loc_lng'   => $postData['car_loc_lng'],
      'car_location'  => $postData['car_location'],
      'vehicle_data'  => json_encode($vehJson),
      'car_model_year'=> $postData['vehicle_year'],
      'status'        => '3'
    );
    if($this->db->insert('customer_vehicle',$insert_array)){
      $last_id = $this->db->insert_id();
      $book_data = array(
        'mileage'        => $postData['mileage'],
        'customer_id'    => $customer_id,
        'customer_veh_id'=> $last_id,
        'status'         => '5'
     );
      if($this->db->insert('bookings',$book_data)){
        $book_id = $this->db->insert_id();
        $respArr['status'] = 'success';
        $respArr['message'] = 'success';
        $respArr['data']['booking_id'] = $book_id;
        return $respArr;
      }
    }
    return $respArr;
  }

  public function get_service_list($postData = '',$start,$per_page){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    $this->db->select("issue_id as id,issue as service_name,IF(issue_image != NULL OR issue_image != '' , concat('".base_url()."',issue_image) , '') as icon");
    if(!empty($postData['query'])){
      $where = "issue LIKE '".$postData['query']."%'";
      $this->db->where($where);
    }
    $this->db->where('status','1');
    if($start != 0 || $per_page != 0){
      $this->db->limit($per_page,$start);
    }
    $service = $this->db->get('issues');
    if(!empty($service) && !empty($serviceData = $service->result_array())){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data']= $serviceData;
    }
    return $respArr;
  }

  public function search_sub_services($postData = '',$start,$per_page){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(!isset($postData['service_id']) && empty($postData['service_id'])){
      $respArr['status'] = 1;
      $respArr['message'] = 'Service Id is Required';
      return $respArr;
    }
    $this->db->select("issue_cat_id as id,issue_category as sub_service_name,IF(issue_cat_image != NULL OR issue_cat_image != '' , concat('".base_url()."',issue_cat_image) , '') as icon");
    if(!empty($postData['query'])){
      $where = "issue_category LIKE '".$postData['query']."%'";
      $this->db->where($where);
    }
    if($start != 0 || $per_page != 0){
      $this->db->limit($per_page,$start);
    }
    $subservice = $this->db->get_where('issues_category',array('status'=>'1','issue_id'=>$postData['service_id']));
    if(!empty($subservice) && !empty($subserviceData = $subservice->result_array())){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data']= $subserviceData;
    }
    return $respArr;
  }

  public function book_service($postData){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($postData)){
      $respArr['message'] = 'All Field is required';
      return $respArr;
    }
    $insert_array = array('cost'=>$postData['total_cost'],'mechanic_id'=>$postData['mechanic_id'],'scheduled_date'=>date('Y-m-d',$postData['date']/1000),'scheduled_time'=>$postData['time'],'issues_selected'=>json_encode($postData['service_id']));
    if($this->db->update('bookings',$insert_array,array('booking_id'=>$postData['booking_id']))){
      $this->db->select("bookings.scheduled_time,bookings.scheduled_date,customer_vehicle.car_model as vehicle_model,customer_vehicle.car_maker as vehicle_make,customer_vehicle.car_model_year as vehicle_year,customer_vehicle.vehicle_data,TRIM(concat(mechanic.first_name,' ',IFNULL(mechanic.last_name,''))) as mechanic_name,mechanic_shop.shop_name as mechanic_shop,mechanic.address,mechanic.phone,admin_users.profile_image as image,bookings.mileage,bookings.issues_selected");
      $this->db->join('customer_vehicle','customer_vehicle.customer_veh_id = bookings.customer_veh_id');
      $this->db->join('mechanic','bookings.mechanic_id = mechanic.mechanic_id');
      $this->db->join('admin_users','admin_users.id = mechanic.mechanic_id');
      $this->db->join('mechanic_shop','mechanic_shop.shop_id = mechanic.shop_id','left');
      $mech_data = $this->db->get_where('bookings',array('booking_id'=>$postData['booking_id']));
      if(!empty($mech_data) && !empty($mechanic_data = $mech_data->row_array())){
        $mech_veh_data = json_decode($mechanic_data['vehicle_data']);
        $mechanic_data['engine_no'] = $mech_veh_data->attributes->Engine;
        $mechanic_data['vehicle_trim'] = $mech_veh_data->attributes->Trim;
        unset($mechanic_data['vehicle_data']);
        $mechanic_data['services'] = json_decode($mechanic_data['issues_selected']);
        unset($mechanic_data['issues_selected']);
        $mechanic_data['scheduled_date'] = strtotime($mechanic_data['scheduled_date']);
        $respArr['status'] = 'success';
        $respArr['message'] = 'success';
        $respArr['data'] = $mechanic_data;
      }
    } 
    return $respArr;
  }

  public function get_booking_summary($postData = ''){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($postData['booking_id'])){
      $respArr['message'] = 'Booking Id is required';
      return $respArr;
    }
    $this->db->select("customer_vehicle.car_model as vehicle_model,customer_vehicle.car_maker as vehicle_make,customer_vehicle.car_model_year as vehicle_year,customer_vehicle.vehicle_data,bookings.mileage,bookings.issues_selected,bookings.custom_issue_data,bookings.mechanic_id");
    $this->db->join('customer_vehicle','customer_vehicle.customer_veh_id = bookings.customer_veh_id');
    $mech_data = $this->db->get_where('bookings',array('booking_id'=>$postData['booking_id']));
    if(!empty($mech_data) && !empty($mechanic_data = $mech_data->row_array())){
      $mech_veh_data = json_decode($mechanic_data['vehicle_data']);
      $mechanic_data['engine_no'] = $mech_veh_data->attributes->Engine;
      $mechanic_data['vehicle_trim'] = $mech_veh_data->attributes->Trim;
      unset($mechanic_data['vehicle_data']);
      $mechanic_data['services'] = json_decode($mechanic_data['issues_selected']);
      if(!empty($mechanic_data['services'])){
        foreach($mechanic_data['services'] as $key => $value){
          $sql = "SELECT IC.*, MI.custom_description, MI.custom_service_fee
                  FROM issues_category AS IC
                  LEFT JOIN mechanic_issues AS MI ON (MI.issue_cat_id=IC.issue_cat_id AND 
                    MI.mechanic_id='".$mechanic_data['mechanic_id']."' AND MI.status='1')
                  WHERE IC.status='1' AND IC.issue_cat_id='".$value->sub_issue_id."'";
          $issue_data = $this->db->query($sql)->row();
          if(!empty($issue_data)){
            if($issue_data->custom_description != '' && $issue_data->custom_service_fee != ''){
              $mechanic_data['services'][$key]->description = $issue_data->custom_description;
              $mechanic_data['services'][$key]->service_fee = $issue_data->custom_service_fee;
            }else{
              $mechanic_data['services'][$key]->description = $issue_data->default_description;
              $mechanic_data['services'][$key]->service_fee = $issue_data->default_service_fee;
            }
          }
        }
      }else{
        $mechanic_data['services'] = [];
      }
      unset($mechanic_data['issues_selected']);
      $issue_data = json_decode($mechanic_data['custom_issue_data']);

      $mechanic_data['optional_images'][] = (isset($issue_data->optionalImages))?$issue_data->optionalImages:'';
      $mechanic_data['optional_video'][] = (isset($issue_data->optionalVideos))?$issue_data->optionalVideos:'';
      $mechanic_data['booking_description'] = (isset($issue_data->optionlaDescription))?$issue_data->optionlaDescription:'';
      unset($mechanic_data['custom_issue_data']);
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data'] = $mechanic_data;
    }
    return $respArr;
  }

  public function getNearMechanics($postData = '',$start,$per_page){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($postData)){
      return $respArr;
    }
    $current_lat = $postData['location_lat'];
    $current_lng = $postData['location_lng'];
    $issue_cat_id = $postData['service_id'];
    if($start != 0 || $per_page != 0){
      $limt = "limit ".$start.",".$per_page;
    }else{
      $limt = "";
    }
    $sql = "SELECT AU.display_name,AU.profile_image,ME.*,MS.shop_name,MS.address AS shop_address,
                 MS.phone AS shop_phone,MS.email_id AS shop_email_id,
                 3956*2*ASIN(SQRT(POWER(SIN(($current_lat-ME.location_lat)*pi()/180/2),2)+
                 COS($current_lat*pi()/180 )*COS(ME.location_lat*pi()/180)*
                 POWER(SIN(($current_lng-ME.location_lng)*pi()/180/2),2) )) AS distance
            FROM mechanic AS ME
            INNER JOIN admin_users AS AU ON (AU.id=ME.mechanic_id)
            LEFT JOIN mechanic_shop AS MS ON (MS.shop_id=ME.shop_id AND MS.status='1')
                WHERE AU.status='1'
                -- HAVING distance<30 
                ".$limt;
    $mechData = $this->db->query($sql);
    if(empty($mechData) || empty($mechData = $mechData->result_array())){
      return 0;
    }
    $estimate = 0;
    $mechDataArr = array();
    foreach($mechData AS $index => $data){
      if(empty($data['start_time']) || empty($data['end_time'])){
        $scheduleTiming = array('09:00 AM','10:00 AM','11:00 AM','12:00 PM','01:00 PM',
                      '02:00 PM','03:00 PM','04:00 PM','05:00 PM','06:00 PM');
      } else {
        $endTime = strtotime($data['end_time']);
        $schTime = strtotime($data['start_time']);
        $scheduleTiming = array();
        for( ; $schTime <= ($endTime-3600) ; $schTime += 3600){
          $scheduleTiming[] = date('h:i A',$schTime);
        }
      }

      $rating = $this->db->query("SELECT round(avg(rate),2) AS rating 
                  FROM mechanic_rating 
                  WHERE mechanic_id='".$data['mechanic_id']."'");
      $rating = (!empty($rating) && !empty($rating = $rating->row_array()))?$rating['rating']:'0';

      $mechanic_id = $data['mechanic_id'];
      $sql = "SELECT ISS.*, IC.*, MI.mechanic_id, MI.custom_description, MI.custom_service_fee
          FROM issues_category AS IC
          INNER JOIN issues AS ISS ON (IC.issue_id=ISS.issue_id)
          LEFT JOIN mechanic_issues AS MI ON (MI.issue_cat_id=IC.issue_cat_id AND 
            MI.mechanic_id='$mechanic_id' AND MI.status='1')
          WHERE ISS.status='1' AND IC.status='1' AND IC.issue_cat_id IN ($issue_cat_id)";

      $subIssData = $this->db->query($sql);
      $sIssueData = array();
      if(!empty($subIssData) && !empty($subIssData = $subIssData->result_array())){
        $sIssueData = $subIssData;
      }
      $estimate = 0;
      foreach($sIssueData AS $sIndex => $sIssue){
        if(!empty($sIssue['custom_service_fee'])){
          $estimate += $sIssue['custom_service_fee'];
          $sIssueData[$sIndex]['service_fee'] = $sIssue['custom_service_fee'];
        } else {
          $estimate += $sIssue['default_service_fee'];
          $sIssueData[$sIndex]['service_fee'] = $sIssue['default_service_fee'];
        }
      }
      $mechData[$index]['rating'] = $rating;
      $mechData[$index]['estimate'] = $estimate;
      $mechData[$index]['sub_issues'] = $sIssueData;
      $mechData[$index]['scheduleTiming'] = $scheduleTiming;
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data'] = $mechData;
    }
    return $respArr;
  }

  public function add_service_details($postData){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong');
    if(empty($postData['booking_id'])){
      $respArr['message'] = 'Booking Id is Required';
      return $respArr;
    }
    $custom_issue_data = array(
      'optionlaDescription'=>(isset($postData['description']) && !empty($postData['description']))?$postData['description']:"",
      'optionalImages'=>(isset($postData['image']) && !empty($postData['image']))?$postData['image']:[],
      'optionalVideos'=>(isset($postData['video']) && !empty($postData['video']))?$postData['video']:[],
    );
    if($this->db->update('bookings',array('custom_issue_data'=>json_encode($custom_issue_data)),array('booking_id'=>$postData['booking_id']))){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      return $respArr;
    }
  }

  public function remove_booking($postData = array()){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong..!');
    if(empty($postData['booking_id'])){
      $respArr['message'] = 'Booking Id is Required';
      return $respArr;
    }else if(empty($postData['service_id'])){
      $respArr['message'] = 'Service Id is Required';
      return $respArr;
    }
    $booked_data = $this->db->get_where('bookings',array('booking_id'=>$postData['booking_id']));
    if(!empty($booked_data) && !empty($booked_data = $booked_data->row_array())){
      $issues_selected = json_decode($booked_data['issues_selected']);
      foreach($issues_selected as $key => $value){
        if($value->sub_issue_id == $postData['service_id']){
          unset($issues_selected[$key]);
        }
      }
      $issues_selected = array_values($issues_selected);
      if($this->db->update('bookings',array('issues_selected'=>json_encode($issues_selected)),array('booking_id'=>$postData['booking_id']))){
        $respArr['status'] = 'success';
        $respArr['message'] ='success';
      }
      return $respArr;
    }
  }

  public function get_service($postData = array()){
    $respArr = array('status'=>'error','message'=>'Something went Wrong.. Try Again');
    if(empty($postData['booking_id'])){
      $respArr['message'] = 'Booking Id is Required';
      return $respArr;
    }
    $booked_data = $this->db->get_where('bookings',array('booking_id'=>$postData['booking_id']));
    if(!empty($booked_data) && !empty($booked_data = $booked_data->row_array())){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data']['services'] = json_decode($booked_data['issues_selected']);
    }
    return $respArr;
  }

  public function rate_mechanic($auth,$postData){
    $respArr = array('status'=>'error','message'=>'Something went Wrong.. Try Again');
    if(empty($postData['rate'])){
      $respArr['message'] = 'Rating is Required';
      return $respArr;
    }
    if(empty($postData['mechanic_id'])){
      $respArr['message'] = 'Mechanic Id is Required';
      return $respArr;
    }
    if(empty($postData['description'])){
      $respArr['message'] = 'Description is Required';
      return $respArr;
    }
    $mechRate = $this->db->get_where('mechanic_rating',array('customer_id'=>$postData['customer_id'],'mechanic_id'=>$postData['mechanic_id']));
    if(!empty($mechRate) && !empty($mechRate = $booked_data->row_array())){
      $respArr['message'] = 'Sorry, You are already Rated for this mechanic';
      return $respArr;
    }
    if($this->db->insert('mechanic_rating',$postData)){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
    }
    return $respArr;
  }
  
}
?>