 <?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 createServiceProvider($provider_data = array()){
    if(empty($provider_data))
      return 0;
    if(isset($provider_data['email']) && !empty($provider_data['email'])){
      $emailChk = $this->db->get_where('admin_users',array('username'=>$provider_data['email'],'status !='=>'2'));
      if(!empty($emailChk) && $emailChk->num_rows() > 0){
        return 2;
      }
    }
    if(isset($provider_data['phone']) && !empty($provider_data['phone'])){
      $phoneChk = $this->db->get_where('mechanic',array('phone'=>$provider_data['phone']));
      if(!empty($phoneChk) && $phoneChk->num_rows() > 0){
        return 3;
      }
    }
    $status = $this->db->insert('admin_users',
                  array('username'=>$provider_data['email'],
                        'password'=>md5($provider_data['password']),
                        'display_name'=>$provider_data['first_name'].' '.$provider_data['last_name'],
                        'user_type'=>'2','status'=>'1'));
    if(!$status){
      return 0;
    }
    $mechanic_id = $this->db->insert_id();
    $status = $this->db->insert('mechanic', 
                    array('mechanic_id'=>$mechanic_id,
                        'city'=>'',
                        'phone'=>$provider_data['phone'],
                        'state'=>'',
                        'shop_id'=>(isset($provider_data['shop_id']) && !empty($provider_data['shop_id']))? $provider_data['shop_id']:'',
                        'address'=>'',
                        'licence'=>'',
                        'location'=>'',
                        'email_id'=>$provider_data['email'],
                        'end_time'=>'',
                        'last_name'=>$provider_data['last_name'],
                        'start_time'=>'',
                        'first_name'=>$provider_data['first_name'],
                        'location_lat'=>'',
                        'location_lng'=>'',
                        'licence_number'=>'',
                        'licence_exp_date'=>''));
    return ($status)?1:0;
  }

  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 = '',$start='',$per_page='',$type=0){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($id)){
      return $respArr;
    }
    $where = ($type == 1)?array('bookings.booking_id'=>$id):array('bookings.customer_id'=>$id);
    $this->db->select("bookings.booking_id as id,bookings.scheduled_date as booked_date,bookings.scheduled_time as time,customer_vehicle.vehicle_data,customer_vehicle.customer_veh_id as vehicle_id,customer_vehicle.car_model_year as year,customer_vehicle.car_maker as vehcle_make,customer_vehicle.car_model as vehicle_type,bookings.mileage,
      bookings.service_type as is_emergency,bookings.status as service_status,bookings.issues_selected,bookings.custom_issue_data,mechanic.location,mechanic.location_lat,mechanic.location_lng,mechanic_booking.amount,bookings.cost,TRIM(concat(mechanic.first_name,' ',IFNULL(mechanic.last_name,''))) as mechanic_name,mechanic.address,mechanic.phone,mechanic.mechanic_id,mechanic_shop.
      shop_name,bookings.car_location as user_loc,bookings.car_loc_lat as user_lat,bookings.car_loc_lng as user_lng");
    $this->db->join('customer_vehicle','customer_vehicle.customer_veh_id = bookings.customer_veh_id');
    $this->db->join("mechanic_booking","mechanic_booking.booking_id = bookings.booking_id");
    $this->db->join("mechanic","mechanic_booking.mechanic_id = mechanic.mechanic_id");
    $this->db->join("mechanic_shop","mechanic_shop.shop_id = mechanic.shop_id","left");
   // $this->db->where('scheduled_date >',date('Y-m-d h:i'));
    $this->db->where('bookings.status !=','0');
    if($start != 0 || $per_page != 0){
      $this->db->limit($per_page,$start);
    }
    $this->db->group_by('id');
    $this->db->order_by('id','DESC');
    $bookData = $this->db->get_where('bookings',$where)->result_array();
    $respArr['status'] = 'success';
    $respArr['message'] = 'success';  
    if(!empty($bookData) && (count($bookData) > 0)){
      foreach ($bookData as $key => $value) {
        $bookData[$key]['trim'] = json_decode($value['vehicle_data'])->trim;
        $bookData[$key]['engine_no'] = json_decode($value['vehicle_data'])->engine;
        $bookData[$key]['booked_date'] = (string) strtotime($value['booked_date'])*1000;
        $bookData[$key]['booked_date'] = $bookData[$key]['booked_date']."";
        if($value['is_emergency'] == '1'){   
          $bookData[$key]['services'] = !empty($value['issues_selected'])?json_decode($value['issues_selected']):'';
        }
        $bookData[$key]['service_description'] = !empty($value['custom_issue_data'])?json_decode($value['custom_issue_data'])->optionlaDescription:'';
        $bookData[$key]['book_amount'] = ($value['is_emergency'] == '1')?$value['amount']:$value['cost'];
        unset($bookData[$key]['vehicle_data'],$bookData[$key]['issues_selected'],$bookData[$key]['custom_issue_data'],$bookData[$key]['amount'],$bookData[$key]['cost']);
      }
      if($type == 1){  
        $respArr['data'] = $bookData[0];
      }
      $respArr['data'] = $bookData;
    }else{
      $respArr['data'] = [];
    }
    return $respArr;
  }

  public function get_booked_services($id){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    if(empty($id)){
      return $respArr;
    }
    $this->db->select("bookings.booking_id as id,bookings.scheduled_date as date,bookings.scheduled_time as time");
    $this->db->where('scheduled_date >',date('Y-m-d h:i'));
    $bookData = $this->db->get_where('bookings',array('bookings.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;
    }
    if(isset($postData['vehicle_id']) && !empty($postData['vehicle_id'])){
      $result = $this->db->get_where('customer_vehicle',array('customer_veh_id'=>$postData['vehicle_id']))->row();
      $postData['mileage'] = '';
      $last_id = $result->customer_veh_id;
    }else{
      $save_car = (isset($postData['save_car']) && !empty($postData['save_car']))?'1':'3';
      $car_name=$postData['vehicle_year'].' '.$postData['vehicle_make'].' '.$postData['vehicle_model'];
      $vehJson = array(
        'vehicle' => $car_name,
        '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'        => $save_car
      );
      if($this->db->insert('customer_vehicle',$insert_array)){
        $last_id = $this->db->insert_id();
      }
      if($save_car == '1'){
        $respArr['status'] = 'success';
        $respArr['message'] = 'success';
        return $respArr;
      }
    }
    if(isset($postData['save_car']) && !empty($postData['save_car'])){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      return $respArr;
    }
    $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;
    }
    $issues = (isset($postData['is_emergency']) && !empty($postData['is_emergency']))?'':json_encode($postData['service_id']);
    $date =(isset($postData['is_emergency']) && !empty($postData['is_emergency']))?date('Y-m-d'):date('Y-m-d',$postData['date']/1000);
    $time = (isset($postData['is_emergency']) && !empty($postData['is_emergency']))?date('h:i A'):$postData['time'];
    $cost = (isset($postData['is_emergency']) && !empty($postData['is_emergency']))?0:$postData['total_cost'];
    $car_location = (isset($postData['location']) && !empty($postData['location']))?$postData['location']:'';
    $car_loc_lat = (isset($postData['location_lat']) && !empty($postData['location_lat']))?$postData['location_lat']:'';
    $car_loc_lng = (isset($postData['location_lng']) && !empty($postData['location_lng']))?$postData['location_lng']:'';
    $insert_array = array(
                          'cost'=>$cost,
                          'scheduled_date'=>$date,
                          'scheduled_time'=>$time,
                          'issues_selected'=>$issues,
                          'service_type'=>(isset($postData['is_emergency']) && !empty($postData['is_emergency']))?2:1,
                          'status'=>(isset($postData['is_emergency']) && !empty($postData['is_emergency']))?1:5,
                          'car_location'=> $car_location,
                          'car_loc_lat'=>$car_loc_lat,
                          'car_loc_lng'=>$car_loc_lng
                        );
    if($this->db->update('bookings',$insert_array,array('booking_id'=>$postData['booking_id']))){
      $this->db->insert("mechanic_booking",array('booking_id'=>$postData['booking_id'],'mechanic_id'=>$postData['mechanic_id'],'amount'=>$cost,'status'=>'0'));
      
      $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,bookings.customer_id");
      $this->db->join('customer_vehicle','customer_vehicle.customer_veh_id = bookings.customer_veh_id');
      $this->db->join("mechanic_booking","mechanic_booking.booking_id = bookings.booking_id AND mechanic_booking.mechanic_id =".$postData['mechanic_id'],'left');
      $this->db->join('mechanic','mechanic_booking.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('bookings.booking_id'=>$postData['booking_id']));
      if(!empty($mech_data) && !empty($mechanic_data = $mech_data->row_array())){
        $this->db->insert('transaction',array('customer_id'=>$mechanic_data['customer_id'],'booking_id'=>$postData['booking_id'],'payment_for'=>'1','datetime'=>date('Y-m-d h:i:s'),'amount'=>$cost));

        $mechanic_data['trans_id'] = $this->db->insert_id();
        $mech_veh_data = json_decode($mechanic_data['vehicle_data']);
        $mechanic_data['engine_no'] = !empty($mech_veh_data->engine)?$mech_veh_data->engine:'';
        $mechanic_data['vehicle_trim'] = !empty($mech_veh_data->trim)?$mech_veh_data->trim:'';
        unset($mechanic_data['vehicle_data']);
        if(!isset($postData['is_emergency']) || empty($postData['is_emergency'])){
          $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,mechanic_booking.mechanic_id");
    $this->db->join('customer_vehicle','customer_vehicle.customer_veh_id = bookings.customer_veh_id');
    $this->db->join("mechanic_booking","mechanic_booking.booking_id = bookings.booking_id AND mechanic_booking.status = '1'",'left');
    $mech_data = $this->db->get_where('bookings',array('bookings.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'] = !empty($mech_veh_data->engine)?$mech_veh_data->engine:'';
      $mechanic_data['vehicle_trim'] = !empty($mech_veh_data->trim)?$mech_veh_data->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='',$type=0){
    $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 = (isset($postData['is_emergency']) && $postData['is_emergency'] == 1)?'':$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;
    }
    foreach ($mechData as $key => $value) {
      $mechData[$key]['distance'] = round((float)$value['distance'],2);
      $mechData[$key]['review'] = [];

      $this->db->order_by('id','DESC');
      $this->db->limit('2','0');
      $mechRvw = $this->db->get_where('mechanic_rating',array('mechanic_id'=>$value['mechanic_id'],'status'=>'1'));
      if(!empty($mechRvw) && !empty($mechRvw = $mechRvw->result_array())){
        $mechData[$key]['review'] = $mechRvw;
      }
      $rating = $this->db->query("SELECT COUNT(id) AS count, round(AVG(rate),2) AS rating 
                  FROM mechanic_rating 
                  WHERE mechanic_id='".$value['mechanic_id']."'");
      if(!empty($rating) && !empty($rating = $rating->row_array())){
        $mechData[$key]['total_review'] = (empty($rating['count']))?'0':$rating['count'];
        $mechData[$key]['avg_rate'] = (empty($rating['rating']))?'0':$rating['rating'];
      }
    }
    if($type == 0){
      $respArr = $this->getNearMechanicsDetails($mechData,$issue_cat_id);
      if($respArr['status'] == 'success'){
        return $respArr;
      }
    }
    $respArr['status'] = 'success';
    $respArr['message'] = 'success';
    $respArr['data'] = $mechData;
    return $respArr;
  }

  public function getNearMechanicsDetails($mechData,$issue_cat_id){
    $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($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;
    }
    if(empty($postData['title'])){
      $respArr['message'] = 'Title 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 = $mechRate->row_array())){
      $respArr['message'] = 'Sorry, You are already Rated for this mechanic';
      return $respArr;
    }
    $postData['status'] = '1';
    if($this->db->insert('mechanic_rating',$postData)){
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
    }
    return $respArr;
  }

  public function acceptMechanicQuote($postData){
    $respArr = array('status'=>'error','message'=>'Something went Wrong.. Try Again');
    if(empty($postData['bookingId'])){
      $respArr['message'] = 'Booking Id is Required';
      return $respArr;
    }
    if(empty($postData['mechanicId'])){
      $respArr['message'] = 'Mechanic Id is Required';
      return $respArr;
    }
    if(empty($postData['amount'])){
      $respArr['message'] = 'Amount is Required';
      return $respArr;
    }
    if($this->db->update('mechanic_booking',array('status'=>'1'),array('booking_id'=>$postData['bookingId'],'mechanic_id'=>$postData['mechanicId']))){
      $this->db->update('mechanic_booking',array('status'=>'2'),array('booking_id'=>$postData['bookingId'],'mechanic_id !='=>$postData['mechanicId']));
      $this->db->update('bookings',array('status'=>'5','cost'=>$postData['amount']),array('booking_id'=>$postData['bookingId']));
    }
    $book_data = $this->db->get_where('bookings',array('booking_id'=>$postData['bookingId']))->row();
    $transaction_array = array(
                                'customer_id'=>$book_data->customer_id,
                                'booking_id'=>$postData['bookingId'],
                                'datetime'=>date('Y-m-d h:i:s'),
                                'amount'=>$postData['amount']
                              );
    $this->db->insert('transaction',$transaction_array);
    $respArr['data'] = $this->db->insert_id();
    $respArr['status'] = 'success';
    $respArr['message'] = 'Updated Successfully';
    return $respArr;
  }

  public function getMechAmount($transId=''){
    $respArr = array('status'=>'error');
    if(empty($transId)){
      return $respArr;
    }
    $result = $this->db->get_where('transaction',array('id'=>$transId));
    if(empty($result) || $result->num_rows() <= 0){
      return;
    }
    $result = $result->row_array();
    $respArr['status'] = 'success';
    $respArr['data'] = $result;
    $custData = $this->db->get_where('customers',array('customer_id'=>$result['customer_id']))->row();
    if(empty($custData)){
      return;
    }
    $respArr['emailId'] = $custData->email;
    return $respArr;
  }

  public function transactionResp($transId='',$result=array(),$payfor='1'){
    $status = 0;
    $odrStat = 9;
    $trancRef = '';
    $respJson = (!empty($result))?json_encode($result):'';
    if(!empty($result) && isset($result['data']) && !empty($result['data'])){
      $trancReference = $result['data']['id'];
      if(isset($result['data']['status']) && $result['data']['status'] == 'success'){
        $status = 1;
        $odrStat = ($payfor == '2')?2:$odrStat;  
      }
    }
    $this->db->update('transaction',array('transaction_response'=>$respJson,'transaction_reference'=>$trancReference,'status'=>$status),array('id'=>$transId));
    if($payfor == '1'){
      $this->db->query("UPDATE bookings 
                        JOIN transaction ON transaction.booking_id=bookings.booking_id 
                        SET bookings.status = $status WHERE transaction.id = $transId");
    }else if($payfor == '2'){
      $this->db->query("UPDATE orders 
                        JOIN transaction ON transaction.booking_id = orders.order_id 
                        SET orders.status = $odrStat WHERE transaction.id = $transId");
    }
    return 1;
  }

  public function transactionRespApi($transId='',$result=array(),$payfor='1'){
    $status = 0;
    $odr_status = 9;
    if(!empty($result) && isset($result['data']) && !empty($result['data']) && 
       isset($result['data']['status']) && $result['data']['status'] == 'success'){
      $status = 1;
      $odr_status = ($payfor == '2')?2:$odr_status;
    }
    $bookData = $this->db->get_where('transaction',array('id'=>$transId))->row();
    $this->db->update('transaction',array('transaction_response'=>json_encode($result),'transaction_reference'=>$result['data']['id'],'status'=>$status),array('bulk_bkng_unqId'=>$bookData->bulk_bkng_unqId));
    if($payfor == '2'){
      $this->db->query("UPDATE orders JOIN transaction ON transaction.booking_id = orders.order_id SET orders.status = $odr_status WHERE transaction.bulk_bkng_unqId = '".$bookData->bulk_bkng_unqId."'");
    }else if($payfor == '1'){
       $this->db->query("UPDATE bookings 
                        JOIN transaction ON transaction.booking_id=bookings.booking_id 
                        SET bookings.status = $status WHERE transaction.id = $transId");
    }
    return 1;
  }

  public function productSearch($postData,$start='',$per_page=''){
    $respArr = array('status'=>'error');
    if(empty($postData)){
      return $respArr;
    }
    $lmt = '';
    if($start != 0 || $per_page != 0){
      $lmt .= "LIMIT $start,$per_page";
    }       
    $cartSel = '';
    $cartJoin = '';
    if(isset($postData['user_id']) && !empty($postData['user_id'])){
      $cartSel = ',CRT.cart_id';
      $cartJoin = "LEFT JOIN cart AS CRT ON 
                   (CRT.product_id=PRD.product_id AND CRT.customer_id=".$postData['user_id'].")";
    }
    $where = '';
    if(isset($postData['key']) && !empty($postData['key'])){
      $where .= " (PRD.product_name LIKE '%".$postData['key']."%' OR 
                  PRD.short_description LIKE '%".$postData['key']."%' OR 
                  PRD.description LIKE '%".$postData['key']."%') AND ";
    }
    if(isset($postData['brand_id']) && !empty($postData['brand_id'])){
      $where .= " PRD.brand_id IN (".implode(',',$postData['brand_id']).") AND ";
    }
    if(isset($postData['minPrice']) && $postData['minPrice'] != ''){
      $where .= " PRD.amount > ".$postData['minPrice']." AND ";
    }
    if(isset($postData['maxPrice']) && $postData['maxPrice'] != ''){
      $where .= " PRD.amount < ".$postData['maxPrice']." AND ";
    }
    if(isset($postData['year']) && $postData['year'] != ''){
      $where .= " CRD.year = ".$postData['year']." AND ";
    }
    if(isset($postData['maker']) && $postData['maker'] != ''){
      $where .= " VEHM.veh_brand_id = ".$postData['maker']." AND ";
    }
    if(isset($postData['model']) && $postData['model'] != ''){
      $where .= " VEHM.veh_modal_id = ".$postData['model']." AND ";
    }
    $result = $this->db->query("SELECT ROUND(AVG(REV.rating),2) AS rating, 
                                       COUNT(REV.id) AS count,PRD.*,PI.image".$cartSel." 
                                FROM products AS PRD 
                                LEFT JOIN product_cars AS CRD ON (PRD.product_id=CRD.product_id)
                                LEFT JOIN product_rating AS REV ON (REV.product_id=PRD.product_id)
                                LEFT JOIN vehicles_model AS VEHM ON (VEHM.veh_modal_id=CRD.veh_model_id)
                                LEFT JOIN product_images AS PI ON (PI.id=
                                  (SELECT MIN(id) FROM product_images 
                                   WHERE product_id=PRD.product_id AND PRD.status='1')) ".$cartJoin."
                                WHERE $where PRD.status='1'
                                GROUP BY PRD.product_id,PI.product_id $lmt");
    if(!empty($result) && $result->num_rows() > 0){
      $result = $result->result_array();
      foreach ($result as $key => $value) {
        $result[$key]['rating'] = (float)$value['rating'];
      }
      $respArr['status'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public  function getBrands($type='0'){
    $respArr = array('status'=>'error');
    $prdt_brand = $this->db->get_where('product_brand',array('status'=>'1'))->result();  
    if(count($prdt_brand) > 0){
      $query = $this->db->query("SELECT MIN(amount) AS minamount, MAX(amount) AS maxamount 
                                 FROM products WHERE status='1'")->row();
      $respArr['status'] = 'success';
      if($type == '0'){  
        $respArr['minamount'] = $query->minamount;
        $respArr['maxamount'] = $query->maxamount;
        $respArr['brands'] = $prdt_brand;
      }else{
        $respArr['data'] = $prdt_brand;
      }
    }
    return $respArr;
  }

  public function SingleProductSearch($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['product_id'])){
      return $respArr;
    }
    $total = 0;
    $per_page = 10;
    $page = (isset($postData['page']) && $postData['page'] != 1) ?$postData['page'] :1; 
    $page_limit = ($page - 1) * $per_page;
    $cartSel = '';
    $cartJoin = '';
    if(isset($postData['user_id']) && !empty($postData['user_id'])){
      $cartSel = ',CRT.cart_id';
      $cartJoin = "LEFT JOIN cart AS CRT ON 
                   (CRT.product_id=PRD.product_id AND CRT.customer_id=".$postData['user_id'].")";
    }
    $sql = "SELECT ROUND(AVG(REV.rating),2) AS rating, COUNT(REV.id) AS count,PRD.*,PRDB.brand_name".
                   $cartSel."
            FROM products AS PRD
            LEFT JOIN product_brand AS PRDB ON PRDB.brand_id = PRD.brand_id
            LEFT JOIN product_rating AS REV ON REV.product_id = PRD.product_id ".$cartJoin."
            WHERE PRD.product_id =".$postData['product_id'];
            $this->db->query($sql);
    $result =  $this->db->query($sql);
    if(!empty($result) && $result->num_rows() > 0){
      $respArr['status'] = 'success';
      $respArr['data'] = $result->row();
      $respArr['data']->rating = (float)$respArr['data']->rating;
      $prdt_img = $this->db->get_where('product_images',array('product_id'=>$postData['product_id'],'status'=>'1'))->result();
      $review = $this->getReviewCount($postData['product_id'],0,0);
      $reviewList = $this->getReviewCount($postData['product_id'],$page_limit,$per_page);
      if(count($review) > 0){
        $total = count($review);  
      }
      if($total >= $per_page){
        $totalPages = (int)($total%$per_page == 0?$total/$per_page:($total/$per_page)+1);
      }
      else{
        $totalPages = 1;
      }
      $respArr['data']->images = '';
      $respArr['data']->reviews = '';
      if(count($prdt_img) > 0){
        $respArr['data']->images = $prdt_img;
      }
      if(count($reviewList) > 0){
        $respArr['data']->reviews['data'] = $reviewList;
        $respArr['data']->reviews['meta'] = array(
                                                'total_pages' => $totalPages,
                                                'total' => $total,
                                                'current_page' => ($page == 0)?1:$page,
                                                'per_page' => $per_page);
      }else{
        $respArr['data']->reviews['data'] = [];
        $respArr['data']->reviews['meta'] = array(
                                                'total_pages' => $totalPages,
                                                'total' => $total,
                                                'current_page' => ($page == 0)?1:$page,
                                                'per_page' => $per_page);
      }   
    }
    return $respArr;
  }

  public function getReviewCount($product_id,$start,$per_page){
    $this->db->select("PRD.*,TRIM(CONCAT(CUST.first_name,' ',IFNULL(CUST.last_name,''))) as customer_name,CUST.profile_image");
    $this->db->join('customers CUST','CUST.customer_id = PRD.customer_id');
    $this->db->order_by('PRD.id DESC');
    if($start != 0 || $per_page != 0){
      $this->db->limit($per_page,$start);
    }
    $reviews = $this->db->get_where('product_rating PRD',array('PRD.product_id'=>$product_id,'PRD.status'=>'1'))->result();
    foreach ($reviews as $key => $value) {
      $reviews[$key]->rating = (float)$value->rating;
    }
    return $reviews;
  }

  public function saveUserAddress($postData = array()){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.. Try Again Later');
    if(empty($postData)){
      $respArr['message'] = 'All Field is required';
      return $respArr;
    }
    if($this->db->insert('customer_address',$postData)){
      $respArr['status'] = "success";
      $respArr['message'] = "Address Added Successfully";
    }
    return $respArr;
  }

  public function getUserAddress($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['user_id'])){
      $respArr['message'] = 'User Id is required';
      return $respArr;
    }
    $result = $this->db->get_where('customer_address',array('customer_id'=>$postData['user_id'],'status'=>'1'));
    if(!empty($result) && !empty($result = $result->result())){
      $respArr['status'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public function getUserAddressById($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['address_id'])){
      $respArr['message'] = 'Address Id is required';
      return $respArr;
    }
    if(empty($postData['customer_id'])){
      $respArr['message'] = 'Customer Id is required';
      return $respArr;
    }
    $result = $this->db->get_where('customer_address',array('id'=>$postData['address_id'],'customer_id'=>$postData['customer_id']));
    if(!empty($result) && !empty($result = $result->row())){
      $respArr['status'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public function updateUserAddress($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['data'])){
      $respArr['message'] = 'All Field is required';
      return $respArr;
    }
    if(empty($postData['address_id'])){
      $respArr['message'] = 'Address Id is required';
      return $respArr;
    }
    if($this->db->update('customer_address',$postData['data'],array('id'=>$postData['address_id']))){
      $respArr['status'] = 'success';
      $respArr['message'] = 'Address Updated Successfully';
    }
    return $respArr;
  }

   public function update_user_address($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['id'])){
      $respArr['message'] = 'Address Id is required';
      return $respArr;
    }
    if($this->db->update('customer_address',$postData,array('id'=>$postData['id']))){
      $respArr['status'] = 'success';
      $respArr['message'] = 'Address Updated Successfully';
    }
    return $respArr;
  }

  public function initOrderBooking($postData=array()){
    $respArr = array('status'=>'error');
    if(empty($postData['data'])){
      $respArr['message'] = 'All Field is required';
      return $respArr;
    }
    $squence = str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
    $insert_array = array(
                      'format_order_id'=>'ORD'.date('ymd').$squence,
                      'product_id'=>$postData['data']['product_id'],
                      'customer_id'=>$postData['data']['customer_id'],
                      'address_id'=>$postData['data']['address_id'],
                      'quantity'=>$postData['data']['quantity'],
                      'amount'=>$postData['data']['total_amount']
                    );
    $this->db->insert('orders',$insert_array);
    $insert_id = $this->db->insert_id();
    $this->db->insert('transaction',array(
                                        'customer_id'=>$postData['data']['customer_id'],
                                        'booking_id'=>$insert_id,
                                        'payment_for'=>'2',
                                        'datetime'=>date('Y-m-d h:i:s'),
                                        'amount'=>$postData['data']['total_amount']
                                      ));
    $last_id =  $this->db->insert_id();
    $respArr['status'] = 'success';
    $respArr['data'] = $last_id;
    return $respArr;
  }

  public function bulkOrderBooking($postData=array()){
    $respArr = array('status'=>'error');
    if(count($postData['data']) < 0){
      $respArr['message'] = 'All Field is required';
      return $respArr;
    }
    $this->db->delete('cart',array('customer_id'=>$postData['customer_id']));
    $bulk_flag = 0;
    $bulkUnqueId = '';
    if(($bulk_flag = count($postData['data'])) > 1){
      $bulk_flag = 1;
      $bulkUnqueId = 'ORDBK'.time();
    }
    $transId = '';
    foreach ($postData['data'] as $orderKey => $orderValue) {
      $orderValue['customer_id'] = $postData['customer_id'];
      $orderValue['bulkUnqueId'] = $bulkUnqueId;
      $orderValue['bulk_bkng_flag'] = $bulk_flag;
      $transId = $this->insertOrders($orderValue);
    }
    if(empty($transId)){
      $respArr['status'] = 'error';
      return $respArr;
    }
    $respArr['status'] = 'success';
    $respArr['data'] = $transId;
    return $respArr;
  }

  public function insertOrders($orderValue = array()){
    if(empty($orderValue)){
      return;
    }
    $squence = str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
    $insertArray = array(
                      'format_order_id'=>'ORD'.date('ymd').$squence,
                      'product_id'=>$orderValue['product_id'],
                      'customer_id'=>$orderValue['customer_id'],
                      'address_id'=>$orderValue['address_id'],
                      'quantity'=>$orderValue['quantity'],
                      'amount'=>$orderValue['total_amount']
                    );
    $status = $this->db->insert('orders',$insertArray);
    if(!$status) return; 
    $insert_id = $this->db->insert_id();
    $insertArray = array(
                    'customer_id'=>$orderValue['customer_id'],'booking_id'=>$insert_id,
                    'payment_for'=>'2','datetime'=>date('Y-m-d h:i:s'),
                    'amount'=>$orderValue['total_amount'],
                    'bulk_bkng_flag'=>$orderValue['bulk_bkng_flag'],
                    'bulk_bkng_unqId'=>$orderValue['bulkUnqueId'],
                    'bulk_amount'=>$orderValue['bulk_amount']
                  );
    $this->db->insert('transaction',$insertArray);
    if(!$status) return;
    $insert_id = $this->db->insert_id();
    return $insert_id;        
  }

  public function getOrderPayDetails($orderId){
    $respArr = array('status'=>'error');
    if(empty($orderId)){
      $respArr['message'] = 'Order Id is required';
      return $respArr;
    }
    $result = $this->db->query("SELECT TRANS.amount,CUST.email 
                                FROM transaction TRANS 
                                LEFT JOIN customers CUST 
                                ON CUST.customer_id = TRANS.customer_id 
                                WHERE TRANS.id = $orderId"
                              );
    if(!empty($result) && !empty($result = $result->row())){
      $this->db->query("UPDATE orders JOIN transaction ON transaction.booking_id = orders.order_id SET orders.status = '1' WHERE transaction.id = $orderId");
      $respArr['status'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public function getOrderPayDetailsApi($transId){
    $respArr = array('status'=>'error');
    if(empty($transId)){
      $respArr['message'] = 'Order Id is required';
      return $respArr;
    }
    $result = $this->db->query("SELECT TRANS.bulk_amount,CUST.email,TRANS.bulk_bkng_unqId 
                                FROM transaction TRANS 
                                LEFT JOIN customers CUST 
                                ON CUST.customer_id = TRANS.customer_id 
                                WHERE TRANS.id = '".$transId."'"
                              );
    if(!empty($result) && !empty($result = $result->row())){
      $this->db->query("UPDATE orders JOIN transaction ON transaction.booking_id = orders.order_id SET orders.status = '1' WHERE transaction.bulk_bkng_unqId = '".$result->bulk_bkng_unqId."'");
      $respArr['status'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public function getOrderDetail($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['ref_id'])){
      $respArr['message'] = 'Transaction Id is required';
      return $respArr;
    }
    $result = $this->db->query("SELECT TRANS.datetime,TRANS.booking_id,TRANS.amount,TRANS.status,
                                PRD.product_id,PRD.product_name,PRD.short_description,PRD.part_id,ORDS.format_order_id,ORDS.quantity,ORDS.expected_delivery,ORDS.delivered,ORDS.status AS odr_status,PRDR.id AS review_id
                                FROM transaction TRANS
                                JOIN orders ORDS ON  ORDS.order_id = TRANS.booking_id 
                                JOIN products PRD ON  PRD.product_id = ORDS.product_id
                                LEFT JOIN product_rating PRDR ON (ORDS.product_id = PRDR.product_id AND ORDS. customer_id = PRDR.customer_id)
                                WHERE TRANS.id =".$postData['ref_id']);
    if(!empty($result) && !empty($result = $result->row())){
      $prdt_img = $this->db->get_where('product_images',array('product_id'=>$result->product_id))->result();
      $result->images = '';
      if(count($prdt_img) > 0){
        $result->images = $prdt_img;
      }     
      $respArr['status'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public function rateProduct($postData=array()){
    $respArr = array('status'=>'error');
    if(empty($postData)){
      $respArr['message'] = 'All Field is required';
      return $respArr;
    }
    $postData['datetime'] = date('Y-m-d h:i:s');
    $result = $this->db->get_where('product_rating',array('product_id'=>$postData['product_id'],'customer_id'=>$postData['customer_id']));
    if(!empty($result) &&  $result->num_rows > 0 && !empty($result = $result->row())){
      $respArr['status'] = 'error';
      $respArr['message'] = 'Sorry Your are Already Rated for this Product';
      return $respArr;
    }
    if($this->db->insert('product_rating',$postData)){
      $respArr['status'] = 'success';
      $respArr['message'] = 'Rated Successfully';
    }
    return $respArr;
  }

  public function get_latest_product_list($start = '',$per_page='',$postData=array()){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    $lmt = '';
    if($start != 0 || $per_page != 0){
      $lmt .= "LIMIT $start,$per_page";
    }
    $cartSel = '';
    $cartJoin = '';
    if(isset($postData['user_id']) && !empty($postData['user_id'])){
      $cartSel = ',CRT.cart_id';
      $cartJoin = "LEFT JOIN cart AS CRT ON 
                   (CRT.product_id=PRD.product_id AND CRT.customer_id=".$postData['user_id'].")";
    }
    $result = $this->db->query("SELECT ROUND(AVG(REV.rating),2) AS rating, 
                                       COUNT(REV.id) AS reviews,PRD.*,PI.image as product_image,BRND.brand_name".$cartSel." 
                                FROM products AS PRD 
                                LEFT JOIN product_images AS PI ON 
                                  (PI.id=(SELECT MIN(id) 
                                          FROM product_images 
                                          WHERE product_id= PRD.product_id AND 
                                                PRD.status='1'))
                                LEFT JOIN product_rating AS REV ON REV.product_id = PRD.product_id
                                JOIN product_brand AS BRND ON BRND.brand_id = PRD.brand_id ".$cartJoin."
                                WHERE PRD.status='1'
                                GROUP BY PRD.product_id,PI.product_id
                                ORDER BY PRD.product_id DESC
                                $lmt");
    if(!empty($result) && $result->num_rows() > 0){
      $result = $result->result_array();
      foreach ($result as $key => $value) {
        $result[$key]['rating'] = (float)$value['rating'];
      }
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data'] = $result;
    }
    return $respArr;
  }

  public function get_trending_product_list($start='',$per_page='',$postData=array()){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    $lmt = '';
    if($start != 0 || $per_page != 0){
      $lmt .= "LIMIT $start,$per_page";
    }
    $cartSel = '';
    $cartJoin = '';
    if(isset($postData['user_id']) && !empty($postData['user_id'])){
      $cartSel = ',CRT.cart_id';
      $cartJoin = "LEFT JOIN cart AS CRT ON 
                   (CRT.product_id=PRD.product_id AND CRT.customer_id=".$postData['user_id'].")";
    }
    $sql =  $this->db->query("SELECT COUNT(ORDS.product_id) as count,PRD.product_id FROM products PRD LEFT JOIN orders AS ORDS ON ORDS.product_id = PRD.product_id WHERE PRD.status='1' GROUP BY PRD.product_id ORDER BY count DESC $lmt ");
    if(!empty($sql) && $sql->num_rows() > 0){
      foreach ($sql->result_array() as $key => $value) {
        $result = $this->db->query("SELECT ROUND(AVG(REV.rating),2) AS rating, 
                                       COUNT(REV.id) AS reviews,PRD.*,PI.image as product_image,BRND.brand_name".$cartSel." 
                                FROM products AS PRD 
                                LEFT JOIN product_images AS PI ON 
                                  (PI.id=(SELECT MIN(id) 
                                          FROM product_images 
                                          WHERE product_id= PRD.product_id AND 
                                                PRD.status='1'))
                                LEFT JOIN product_rating AS REV ON REV.product_id = PRD.product_id
                                JOIN product_brand AS BRND ON BRND.brand_id = PRD.brand_id ".$cartJoin."
                                WHERE PRD.status='1' AND PRD.product_id =".$value['product_id']);
        if(!empty($result) && $result->num_rows() > 0){
          $result = $result->row_array();
          $result['rating'] = (float)$result['rating'];
          $new_array[$key] =  $result;
        }
      }
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data'] = $new_array;
    }
    return $respArr;
  }

  public function getMyOrders($postData,$start='',$per_page=''){
    $respArr = array('status'=>'error');
    if(empty($postData['customer_id'])){
      $respArr['message'] = "Customer Id is Required";
      return $respArr;
    }
    $lmt = '';
    if($start != 0 || $per_page != 0){
      $lmt .= "LIMIT $start,$per_page";
    }
    $result = $this->db->query("SELECT ROUND(AVG(REV.rating),2) AS rating, 
                                       COUNT(REV.id) AS reviews,PRD.product_name,PRD.short_description,PRD.part_id,TRANS.id AS transId,
                      TRANS.status AS tranStatus,TRANS.datetime,ORD.*,PI.image as product_image,BRND.brand_name   
                      FROM orders ORD 
                      JOIN products PRD ON ORD.product_id = PRD.product_id 
                      JOIN transaction TRANS ON (ORD.order_id = TRANS.booking_id AND TRANS.payment_for= '2') 
                      LEFT JOIN product_rating AS REV ON REV.product_id = PRD.product_id
                      LEFT JOIN product_images AS PI ON (PI.id=
                                          (SELECT MIN(id) 
                                          FROM product_images 
                                          WHERE product_id= PRD.product_id AND 
                                                PRD.status='1'))
                      JOIN product_brand AS BRND ON BRND.brand_id = PRD.brand_id
                      WHERE ORD.customer_id=".$postData['customer_id']." GROUP BY ORD.order_id ORDER BY ORD.order_id DESC $lmt");
    if(empty($result) || empty($result = $result->result())){
      $respArr['status'] = "error";
      return $respArr;
    }
    foreach ($result as $key => $value) {
      $result[$key]->rating = (float)$value->rating;
    }
    $respArr['status'] = "success";
    $respArr['data'] = $result;
    return $respArr;
  }

  public function cancelOrder($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['order_id'])){
      $respArr['message'] = "Order Id is Required";
      return $respArr;
    }
    if($this->db->update('orders',array('status'=>'7'),array('order_id'=>$postData['order_id']))){
      $respArr['status'] = 'success';
      $respArr['message'] = 'Order Cancelled Successfully';
    }
    return $respArr;
  }

  public function getCartData($postData,$start='',$per_page=''){
    $respArr = array('status'=>'error');
    if(empty($postData['customer_id'])){
      $respArr['message'] = "Customer Id is Required";
      return $respArr;
    }
    $lmt = '';
    if($start != 0 || $per_page != 0){
      $lmt .= "LIMIT $start,$per_page";
    }
    $result = $this->db->query("SELECT ROUND(AVG(REV.rating),2) AS rating, 
                                       COUNT(REV.id) AS reviews,PRD.product_name,PRD.short_description,PRD.part_id,CRT.cart_id,CRT.quantity
                                ,CRT.product_id,PI.image as product_image,BRND.brand_name,PRD.amount
                      FROM cart CRT 
                      JOIN products PRD ON CRT.product_id = PRD.product_id
                      JOIN product_brand BRND ON BRND.brand_id = PRD.brand_id
                      LEFT JOIN product_rating AS REV ON REV.product_id = PRD.product_id
                      LEFT JOIN product_images AS PI ON (PI.id=
                                          (SELECT MIN(id) 
                                          FROM product_images 
                                          WHERE product_id= PRD.product_id AND 
                                                PRD.status='1'))
                      WHERE CRT.customer_id=".$postData['customer_id']." GROUP BY CRT.cart_id ORDER BY CRT.cart_id DESC $lmt");
    if(empty($result) || empty($result = $result->result())){
      $respArr['status'] = "error";
      return $respArr;
    }
    foreach ($result as $key => $value) {
      $result[$key]->rating = (float)$value->rating;
    }
    $respArr['status'] = "success";
    $respArr['data'] = $result;
    return $respArr;
  }

  public function removeCartPrdt($postData){
    $respArr = array('status'=>'error');
    if(empty($postData['cart_id'])){
      $respArr['message'] = "Cart Id is Required";
      return $respArr;
    }
    if($this->db->delete('cart',array('cart_id'=>$postData['cart_id']))){
      $respArr['status'] = "success";
    }
    return $respArr;
  }

  public function addToCart($postData){
    $respArr = array('status'=>'error');
    if(empty($postData)){
      $respArr['message'] = "All Field is Required";
      return $respArr;
    }
    $postData['created_date'] = date('Y-m-d h:i:s');
    $cartData = $this->db->get_where('cart',array('product_id'=>$postData['product_id'],'customer_id'=>$postData['customer_id']));
    if($cartData->num_rows < 0 || empty($cartData = $cartData->row())){
      if($this->db->insert('cart',$postData)){
        $respArr['data'] = $this->db->insert_id();
        $respArr['status'] = 'success';
      } 
    }else{
      $respArr['message'] = "Product Already Added to Cart";
    }
    return $respArr;
  }

  public function getMechanicShops(){
    $respArr = array('status'=>'error');
    $result = $this->db->get('mechanic_shop');
     if(empty($result) || empty($result = $result->result())){
      $respArr['status'] = "error";
      return $respArr;
    }
    $respArr['status'] = 'success';
    $respArr['data'] = $result;
    return $respArr;
  }

  public function getVehicleBrand(){
    $respArr = array('status'=>'error');
    $this->db->order_by('maker');
    $this->db->where('status','1');
    $result = $this->db->get('vehicles_brand');
     if(empty($result) || empty($result = $result->result())){
      $respArr['status'] = "error";
      return $respArr;
    }
    $respArr['status'] = 'success';
    $respArr['data'] = $result;
    return $respArr;
  }

  public function getVehicleModel($postData=array()){
    $respArr = array('status'=>'error');
    if(!isset($postData['vehBrand_id']) && empty($postData['vehBrand_id'])){
      $respArr['message'] = 'Vehicle Brand Id is Required' ;
    }
    $this->db->select("DISTINCT(model) as model,veh_modal_id,engine,trim");
    $this->db->order_by('model');
    $result = $this->db->get_where('vehicles_model',
                         array('veh_brand_id'=>$postData['vehBrand_id'],'status'=>'1'));
    if(empty($result) || empty($result = $result->result())){
      $respArr['status'] = "error";
      return $respArr;
    }
    $modArr = array();
    $type = (isset($postData['type']) && $postData['type'] != '')?$postData['type']:0;
    foreach ($result as $key => $model) {
      if($type == 0 && in_array($model->model,$modArr)){
        unset($result[$key]);
      }
      if($type == 1){
        $model->model = $model->model;
        $model->model .= (!empty($model->trim))?' '.$model->trim:'';
        $model->model .= (!empty($model->engine))?', '.$model->engine:'';
        $result[$key]->model =  $model->model;
      }
      $modArr[] = $model->model;
    }
    $result = array_merge($result);
    $respArr['status'] = 'success';
    $respArr['data'] = $result;
    return $respArr;
  }

  public function socialLogin($postData=array()){
    $respArr = array('status'=>'error');
    if(empty($postData['data'])){
      $respArr['message'] = 'All Field is Required' ;
    }
    $result=$this->db->get_where('customers',array('email'=>$postData['data']['email'],'status'=>'1'));
    if(!empty($result) && $result->num_rows() == 1 && !empty($custData = $result->row())){
      $respArr['data'] = $custData;
      $respArr['status'] = 1;
      return $respArr;
    }
    if(empty($result) || $result->num_rows() < 1 || empty($custData = $result->row())){
      $postData['data']['profile_image'] = '';
      $postData['data']['is_otp_verified'] = 1;
      if(isset($postData['data'],$postData['data']['image_url']) && 
         !empty($postData['data']['image_url'])){
        $imageData = file_get_contents($postData['data']['image_url']);
        $userlImg  = 'assets/uploads/services/userImg_'.time().'.jpg';
        file_put_contents($userlImg, $imageData);
        $postData['data']['profile_image'] = $userlImg;
      }
      unset($postData['data']['image_url']);
      $this->db->insert('customers',$postData['data']);
      $last_id = $this->db->insert_id();
      $custData = $this->db->get_where('customers',array('customer_id'=>$last_id))->row();
      $respArr['data'] = $custData;
      $respArr['status'] = 1;
      return $respArr;
    }
  }

  public function getCustRemainders($postData=array()){
    $respArr = array('status'=>'error');
    if(empty($cust_id = $postData['customer_id'])){
      $respArr['message'] = 'Customer Id is Required' ;
    }
    $new = array();
    $result = $this->db->get_where('customer_vehicle',
                             array('customer_id'=>$cust_id,'enable_notification'=>'1','status'=>'1'));
    if(!empty($result) && !empty($result = $result->result_array())){
      foreach ($result AS $veh_value) {
        $veh_id = $veh_value['customer_veh_id'];
        $this->db->where('customer_veh_id',$veh_id);
        $this->db->where_in('status',array('1','3')); 
        $this->db->order_by('booking_id','DESC'); 
        $lstBok = $this->db->get("bookings");
        $lastMainDate = $veh_value['last_maintenance_date'];
        if(!empty($lstBok) && $lstBok->num_rows() > 0 && !empty($lstBok = $lstBok->row_array())){
          if(strtotime($lstBok['scheduled_date']) > strtotime($lastMainDate)){
            $lastMainDate = $lstBok['scheduled_date'];
          }
        }
        if(empty($lastMainDate)){
          continue;
        }
        $interval = (!empty($veh_value['maintanence_interval']))?$veh_value['maintanence_interval']:6;
        $newMainDate = strtotime(date("Y-m-d", strtotime($lastMainDate)) . " +".$interval." month");
        $remindDate  = strtotime(date("Y-m-d", $newMainDate) . " -10 days");
        if(strtotime(date('Y-m-d')) >= $remindDate){
          $veh_value['last_maintenance_date'] = $lastMainDate;
          $veh_value['next_maintenance_date'] = date('Y-m-d',$newMainDate);
          $new[] = $veh_value;
        }
      }
      if(count($new) > 0){
        $respArr['status'] = 'success';
        $respArr['data'] = $new;
      }
    }
    return $respArr;
  }

  public function getOrderData($order_id){
    $this->db->select("CONCAT(CUSTADRS.house_no, ' ', CUSTADRS.area, ' ', CUSTADRS.city, ' ', CUSTADRS.state) as shipping_address,TRIM(CONCAT(CUST.first_name,' ' ,IFNULL(CUST.last_name,''))) as name,PRD.product_name,PRD.amount as prd_amount,PRDBRD.brand_name,ORDS.quantity,ORDS.amount,ORDS.format_order_id,TRANS.datetime");
    $this->db->from("orders AS ORDS");
    $this->db->join("transaction AS TRANS","TRANS.booking_id = ORDS.order_id AND TRANS.payment_for = '2'");
    $this->db->join("products AS PRD","PRD.product_id = ORDS.product_id");
    $this->db->join("product_brand AS PRDBRD","PRDBRD.brand_id = PRD.brand_id");
    $this->db->join("customer_address AS CUSTADRS","ORDS.address_id = CUSTADRS.id");
    $this->db->join("customers AS CUST","ORDS.customer_id = CUST.customer_id");
    $this->db->where('ORDS.format_order_id',$order_id);
    return $this->db->get()->row();
  }

  public function getCustVehDetails($postData =array()){
    $respArr = array('status'=>'error');
    if(empty($cust_id = $postData['car_id'])){
      $respArr['message'] = 'Car Id is Required' ;
    }
    $this->db->select('vehicle_data');
    $carData = $this->db->get_where('customer_vehicle',array('customer_veh_id'=>$postData['car_id']))->row();
    if(empty($carData)){
      $respArr['message'] = "Vehicle Doesnot Exist";
      return $respArr;
    }
    $veh_data = json_decode($carData->vehicle_data);
    $result = $this->db->query("SELECT VEHM.veh_modal_id,VEHM.veh_brand_id 
                                FROM vehicles_model AS VEHM
                                INNER JOIN vehicles_brand AS VEHB ON VEHB.veh_brand_id = VEHM.veh_brand_id
                                WHERE VEHB.maker LIKE '$veh_data->make'
                                AND VEHM.model LIKE '$veh_data->model'
                                AND VEHM.engine LIKE '$veh_data->engine'
                                AND VEHM.trim LIKE '$veh_data->trim'"
                              );
    if(empty($result) || $result->num_rows() <= 0){
      $result = $this->db->query("SELECT VEHM.veh_modal_id,VEHM.veh_brand_id 
                                FROM vehicles_model AS VEHM
                                INNER JOIN vehicles_brand AS VEHB ON VEHB.veh_brand_id = VEHM.veh_brand_id
                                WHERE VEHB.maker LIKE '$veh_data->make'
                                AND VEHM.model LIKE '$veh_data->model'
                                AND VEHM.trim LIKE '$veh_data->trim'"
                              );
    }
    if(empty($result) || $result->num_rows() <= 0){
      $result = $this->db->query("SELECT VEHM.veh_modal_id,VEHM.veh_brand_id 
                                FROM vehicles_model AS VEHM
                                INNER JOIN vehicles_brand AS VEHB ON VEHB.veh_brand_id = VEHM.veh_brand_id
                                WHERE VEHB.maker LIKE '$veh_data->make'
                                AND VEHM.model LIKE '$veh_data->model'"
                              );
    }
    if(!empty($result) && $result->num_rows() > 0 && !empty($data = $result->row())){
      $respArr['data'] = $data;
      $respArr['status'] = 'success';
    } else {
      $respArr['status'] = 'error';
    }
    return $respArr;
  }

  public function remove_vehicle($postData = array()){
    $respArr = array('status'=>'error');
    if(empty($postData['customer_veh_id'])){
      $respArr['message'] = 'Vehicle Id is Required' ;
      return $respArr;
    }

    if($this->db->update("customer_vehicle",array('status'=>'2'),array("customer_veh_id"=>$postData['customer_veh_id']))){
      $respArr['status'] = "success";
      $respArr['message'] = "Vehicle Deleted Successfully";
    }
    return $respArr;
  }

  public function get_mechanics_reviews($postData=array(),$start='',$per_page=''){
    $respArr = array('status'=>'error','message'=>'Something Went Wrong.');
    $this->db->select("mechanic_rating.*,TRIM(CONCAT(customers.first_name,' ' ,IFNULL(customers.last_name,''))) as customers_name");
    $this->db->join('customers','customers.customer_id = mechanic_rating.customer_id');
    if($start != 0 || $per_page != 0){
      $this->db->limit($per_page,$start);
    }
    $review = $this->db->get_where('mechanic_rating',array('mechanic_id'=>$postData['mechanic_id'],'mechanic_rating.status'=>'1'));
    if(!empty($review) && !empty($reviewData = $review->result_array())){
      foreach ($reviewData as $key => $value) {
        $reviewData[$key]['rate'] = (float)$value['rate'];
      }
      $respArr['status'] = 'success';
      $respArr['message'] = 'success';
      $respArr['data'] = $reviewData;
    }
    return $respArr;
  }

  public function getfcmData($transId,$mobile){
    $respArr = array('status'=>'error');
    $this->db->select('bookings.service_type,bookings.booking_id,mechanic.device_id');
    $this->db->join('bookings','bookings.booking_id = transaction.booking_id');
    if($mobile == '1'){
      $this->db->join("mechanic_booking","mechanic_booking.booking_id = bookings.booking_id");     
      $this->db->join('mechanic','mechanic_booking.mechanic_id = mechanic.mechanic_id');
    }else{
      $this->db->join("mechanic_booking","mechanic_booking.booking_id = bookings.booking_id AND mechanic_booking.status='1'");
      $this->db->join("mechanic","mechanic_booking.mechanic_id = mechanic.mechanic_id AND mechanic_booking.status='1'");
    }
    $result = $this->db->get_where('transaction',array('transaction.id'=>$transId,'transaction.payment_for'=>'1'))->row_array();
    if($result){
      $respArr['status'] = "success";
      $respArr['data'] = $result;
    }
    return $respArr;
  }
}
?>
