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

    public function createCustomer($postData = array()){
        if(empty($postData))
            return 0;
        if(isset($postData['user_email']) && !empty($postData['user_email'])){
           // $this->db->join('customer AS CUST','CUST.cust_id = USR.profile_id');
            $emailChk = $this->db->get_where('users AS USR',array('USR.username'=>$postData['user_email'], 'USR.status !='=>'2','USR.user_type'=>'1'));
            if(!empty($emailChk) && $emailChk->num_rows() > 0){
                return 2;
            }
        }
        if(isset($postData['user_phonenumber']) && !empty($postData['user_phonenumber'])){
            $phoneChk = $this->db->get_where('users',array('phone_no'=>$postData['user_phonenumber'],'status !='=>'2'));
            if(!empty($phoneChk) && $phoneChk->num_rows() > 0){
                return 3;
            }
        }
        $insert_array = array(
                            'name'=>$postData['user_name'],
                            'email_id'=>$postData['user_email'],
                            'code'=>$postData['user_phonecode'],
                            'phone_no'=>$postData['user_phonenumber'],
                            'device_id'=>$postData['device_id'],
                            'address'=>$postData['user_address'],
                            // 'country'=>$postData['user_country'],
                            // 'region'=>$postData['user_region'],
                            // 'city'=>$postData['user_city'],
                            'area'=>$postData['user_area'],
                            'lat'=>$postData['user_lat'],
                            'lng'=>$postData['user_lng'],
                            //'password'=>$postData['user_password'],
                        );
        $status = $this->db->insert('customer',$insert_array);
        $last_id = $this->db->insert_id();

        $status = $this->db->insert('users',array('user_type'=>'1','profile_id'=>$last_id,'username'=>$postData['user_email'],'phone_no'=>$postData['user_phonenumber'],'password'=>$postData['user_password'],'status'=>'1'));
        return ($status)?1:0;
    }

    public function checkCustomerLogin($userLogData){
        $respArr = array('status'=>'error');
        if(empty($userLogData)){
            return $respArr;
        }
        //$this->db->join('customer AS CUST','CUST.cust_id = USR.profile_id');
        $result = $this->db->get_where('users AS USR',array('USR.username'=>$userLogData['user_email'], 'USR.status'=>'1'));

        if(empty($result) || $result->num_rows() < 1 || empty($custData = $result->row())){
            $respArr['message'] = "Invalid Email Address";
            return $respArr;
        }
        //$this->db->join('customer AS CUST','CUST.cust_id = USR.profile_id');
        $result = $this->db->get_where('users AS USR',array('USR.username'=>$userLogData['user_email'], 'USR.status'=>'1','USR.user_type'=>'1','USR.password'=>$userLogData['user_password']));

        $respArr['message'] = "Invalid Password";

        if(!empty($result) && $result->num_rows() == 1 && !empty($custData = $result->row())){
            $respArr['data'] = $custData;
            $respArr['status'] = 1;
            $respArr['message'] = "success";
        }
        return $respArr;
    }

    public function userLogin($postData = array()){
        $respArr = array('status'=>'error');
        if(empty($postData)){
            return $respArr;
        }
        $result = $this->checkCustomerLogin($postData);
        if($result['status'] == 'error'){
            return $result;
        }
        if($this->db->update('customer',array('lat'=>$postData['user_lat'],'lng'=>$postData['user_lng'],'device_id'=>$postData['device_id']),array('cust_id'=>$result['data']->profile_id))){
            $respArr['status'] = "success";
            $respArr['message'] = "success";
            $respArr['data'] = $result['data'];
        } 
        return $respArr;
    }

    public function updateCustomer($postData){
         if(empty($postData))
            return 0;
        if(isset($postData['user_email']) && !empty($postData['user_email'])){
            //$this->db->join('customer AS CUST','CUST.cust_id = USR.profile_id');
            $emailChk = $this->db->get_where('users AS USR',array('USR.username'=>$postData['user_email'], 'USR.status !='=>'2','USR.user_type'=>'1','USR.profile_id !='=>$postData['user_id']));
            if(!empty($emailChk) && $emailChk->num_rows() > 0){
                return 2;
            }
        }
        if(isset($postData['user_phonenumber']) && !empty($postData['user_phonenumber'])){
            $phoneChk = $this->db->get_where('users',array('phone_no'=>$postData['user_phonenumber'],'status !='=>'2','profile_id !='=>$postData['user_id']));
            if(!empty($phoneChk) && $phoneChk->num_rows() > 0){
                return 3;
            }
        }
        $insert_array = array(
                            'name'=>$postData['user_name'],
                            'email_id'=>$postData['user_email'],
                            'code'=>$postData['user_phonecode'],
                            'phone_no'=>$postData['user_phonenumber'],
                            'address'=>$postData['user_address'],
                            'area'=>$postData['user_area'],
                            'lat'=>$postData['user_lat'],
                            'lng'=>$postData['user_lng']
                        );
        if($this->db->update('customer',$insert_array,array('cust_id'=>$postData['user_id']))){
            $status = $this->db->update('users',array('user_type'=>'1','username'=>$postData['user_email'],'phone_no'=>$postData['user_phonenumber'],'status'=>'1'),array('profile_id'=>$postData['user_id']));
            return ($status)?1:0;
        }
    }

    public function upload_profilePic($postData = array()){
        if($this->db->update('customer',array('profile_photo'=>$postData['profile_photo']),array('cust_id'=>$postData['user_id']))){
            return 1;
        }
    }

    public function add_UserCar($postData = array()){
        $respArr = array('status'=>'error');
        $vehicle = $postData['car_year'].' '.$postData['car_brand'].' '.$postData['car_model'];
        if($this->db->insert('vehicle_model',array('cust_id'=>$postData['user_id'],'vin'=>$postData['car_VinNumber'],'make'=>$postData['car_brand'],'model'=>$postData['car_model'],'year'=>$postData['car_year'],'vehicle_name'=>$vehicle,'mileage'=>$postData['car_milege'],'vehicle_image'=>$postData['vehicle_image']))){
            $respArr['status'] = "success";
            $respArr['message'] = "Car Added Successfully";
        }
        return $respArr;
    }

    public function user_forgetpsw($postData = array()){
        $respArr = array('status'=>'error');
        $this->db->join("customer","customer.cust_id = users.profile_id");
        $phoneChk = $this->db->get_where('users',array('users.phone_no'=>$postData['user_phonenumber'],'status !='=>'2','users.user_type'=>'1','customer.code'=>$postData['user_countrycode']));
        if(empty($phoneChk) || $phoneChk->num_rows() < 0 || empty($phoneChk = $phoneChk->row_array())){
            $respArr['message'] = "Phone Number Doesnot Exist";
            return $respArr;
        }
        $otp = rand(1000,9999);
        if($this->db->update("users",array("otp"=>$otp),array('profile_id'=>$postData['user_id'],'user_type'=>'1'))){
            $respArr['status'] = "success";
            $respArr['data'] = $otp;
        }
        return $respArr;
    }

    public function user_otp($postData = array()){
        $respArr = array('status'=>'error','message'=>'OTP Doesnot Match');
        $otpChk = $this->db->get_where('users',array('profile_id'=>$postData['user_id'],'user_type'=>'1'));
        if(empty($otpChk) || empty($otpChk = $otpChk->row_array())){
            $respArr['message'] = "User Doesnot Exist";
            return $respArr;
        }
        if($postData['otp'] == $otpChk['otp']){
            $respArr['status'] = "success";
            $respArr['message'] = "success";
        }
        return $respArr;
    }

    public function people_most_purchased(){
        $respArr = array('status'=>'error');
        $sql =  $this->db->query("SELECT count(PTS.id) AS count,PTS.id,PTS.unique_name,PTS.part_number FROM pos_parts AS PTS LEFT JOIN booking_parts AS BKPTS ON BKPTS.pos_part_id = PTS.id WHERE PTS.status='1' GROUP BY PTS.id ORDER BY count DESC");
        if(!empty($sql) && !empty($data=$sql->result_array())){
            $respArr['status'] = "success";
            $respArr['data'] = $data;
        }
        return $respArr;
    }

    public function products_for_user($userId =''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT * FROM vehicle_model WHERE cust_id=$userId");
        if(!empty($sql) && !empty($data=$sql->result_array())){
            $name = '';
            foreach ($data as $key => $value) {
                $eCond = ($key != count($data)-1)?' OR ':'';
                $name .= " unique_name LIKE '%".$value['vehicle_name']."%' ".$eCond;
            }
            $res = $this->db->query("SELECT unique_name,id,part_number pos_parts FROM pos_parts WHERE $name GROUP BY unique_name");
            if(!empty($res) && !empty($prdtData=$res->result_array())){
                $respArr['data'] = $prdtData;
            }else{
                $result = $this->people_most_purchased();    
                $respArr['data'] = $result['data'];
            }
        }else{
            $result = $this->people_most_purchased();
            $respArr['data'] = $result['data'];
        }
        $respArr['status'] = "success";
        return $respArr;
    }

    public function user_bookedService($userId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT GRBK.booking_id,GRBK.booking_date,GROUP_CONCAT(SBSRVCE.sub_services SEPARATOR ', ') AS subservices FROM garage_booking AS GRBK LEFT JOIN sub_services AS SBSRVCE ON find_in_set(SBSRVCE.id,GRBK.subservices_ids) WHERE GRBK.cust_id=$userId AND GRBK.status=1");
        if(empty($sql) || empty($data=$sql->result_array())){
            $respArr['message'] = "No Bookings";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $data;
        return $respArr;
    }

    public function get_MainServices(){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT * FROM services WHERE status=1");
        if(empty($sql) || empty($data=$sql->result_array())){
            $respArr['message'] = "No Service";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $data;
        return $respArr;    
    }

    public function get_subServices($serviceId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT * FROM sub_services WHERE service_id=$serviceId AND status=1");
        if(empty($sql) || empty($data=$sql->result_array())){
            $respArr['message'] = "No SubService";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $data;
        return $respArr;
    }

    public function get_userProfile($userId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT customer.*,users.username,users.password,users.phone_no FROM customer JOIN users ON (users.profile_id = customer.cust_id AND users.user_type=1) WHERE customer.cust_id =$userId");
        if(empty($sql) || empty($data=$sql->result_array())){
            $respArr['message'] = "No Users Exist";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $data;
        return $respArr;
    }

    public function get_carDetails($userId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT * FROM vehicle_model WHERE cust_id =$userId");
        if(empty($sql) || empty($data=$sql->result_array())){
            $respArr['message'] = "No Cars Added";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $data;
        return $respArr;
    }

    public function road_assistanceList($postData = array()){
        $respArr = array('status'=>'error');
        $current_lat = $postData['user_lat'];
        $current_lng = $postData['user_lng'];
        $sql = "SELECT RDAST.road_assist_id,RDAST.road_assist_code,RDAST.name,RDAST.profile_photo,
                 3956*2*ASIN(SQRT(POWER(SIN(($current_lat-RDAST.lat)*pi()/180/2),2)+
                 COS($current_lat*pi()/180 )*COS(RDAST.lat*pi()/180)*
                 POWER(SIN(($current_lng-RDAST.lng)*pi()/180/2),2) )) AS distance
            FROM road_assist AS RDAST
            INNER JOIN users AS USR ON (RDAST.road_assist_id=USR.profile_id AND USR.user_type=5)
            WHERE USR.status='1'
            HAVING distance<10 ";
        $res = $this->db->query($sql);
        if(empty($res) || empty($result = $res->result_array())){
            $respArr['message'] = "No Mechanics Near to You";
            return $respArr;
        }
        foreach ($result as $key => $value) {
          $result[$key]['distance'] = round((float)$value['distance'],2);
          $this->db->select("COUNT(rating.id) AS count, round(AVG(rate),2) AS rating ");
          $this->db->join('road_booking','road_booking.id = rating.booking_id AND rating.type=5');
          $roadRvw = $this->db->get_where('rating',array('road_booking.road_assist_id'=>$value['road_assist_id']));
          if(!empty($roadRvw) && !empty($roadRvw = $roadRvw->row_array())){
            $result[$key]['total_review'] = (empty($roadRvw['count']))?'0':$roadRvw['count'];
            $result[$key]['avg_rate'] = (empty($roadRvw['rating']))?'0':$roadRvw['rating'];
          }
        }
        if(!empty($result)){
            $respArr['status'] = "success";
            $respArr['data'] = $result;
        }
        return $respArr;
    }

    public function road_assistanceDetail($road_assist_id=''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT RDAST.road_assist_id,RDAST.road_assist_code,RDAST.name,RDAST.profile_photo,RDAST.phone_no,RDAST.email_id,RDAST.address FROM road_assist AS RDAST WHERE road_assist_id=$road_assist_id");
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No Road Assist";
            return $respArr;
        }
        $this->db->select("rating.id,rating.rate,rating.caption,rating.description");
        $this->db->join('road_booking','road_booking.id = rating.booking_id AND rating.type=5');
        $roadRvw = $this->db->get_where('rating',array('road_booking.road_assist_id'=>$road_assist_id));
        if(!empty($roadRvw) && !empty($roadRvwroadRvw = $roadRvw->result_array())){
            $result['review'] = (empty($roadRvw))?[]:$roadRvwroadRvw;
        }
        $respArr['status'] = "success";
        $respArr['data '] = $result;
        return $respArr;
    }

    public function book_roadassistance($postData = array()){
        $respArr = array('status'=>'error');
        $insert_array = array(
                            'cust_id'=>$postData['user_id'],
                            'vehicle_id'=>$postData['user_carId'],
                            'date'=>$postData['date'],
                            'requirement'=>(isset($postData['message']) && !empty($postData['message']))?$postData['message']:'',
                            'lat'=>$postData['user_lat'],
                            'lng'=>$postData['user_lng'],
                            'road_assist_id'=>$postData['roadassistance_id'],
                            'status'=>'1'
                        );
        if($this->db->insert("road_booking",$insert_array)){
            $respArr['status'] = "success";
            $respArr['message'] = "Road Booking Inserted Successfully";
        }
        return $respArr;
    }

    public function road_assistanceDetail_history($road_assist_id=''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT CUST.name,CUST.cust_id,CUST.phone_no,RDBK.id AS roadservicerequestid,RDBK.lat,RDBK.lng,VM.make,VM.model FROM road_booking AS RDBK INNER JOIN customer AS CUST ON (CUST.cust_id = RDBK.cust_id) INNER JOIN vehicle_model AS VM ON (VM.id = RDBK.vehicle_id) WHERE RDBK.road_assist_id =$road_assist_id");
        if(empty($sql) || empty($result = $sql->result_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function status_roadassistancerequest($postData = array()){
        $respArr = array('status'=>'error');
        if($this->db->update("road_booking",array('status'=>$postData['status']),array('id'=>$postData['roadservice_requestId']))){
            $respArr['status'] = "success";
        }
        return $respArr;
    }

    public function road_assistancerequestlist($userId =''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT CUST.name,RDBK.road_assist_id,CUST.phone_no,RDBK.id AS roadservicerequestid,RDBK.status,RDBK.date FROM road_booking AS RDBK INNER JOIN customer AS CUST ON (CUST.cust_id = RDBK.cust_id) WHERE RDBK.cust_id =$userId");
        if(empty($sql) || empty($result = $sql->result_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr; 
    }

    public function write_review($postData = array()){
        $respArr = array('status'=>'error');
        $insert_array = array(
                            'user_id'=>$postData['user_id'],
                            'type'=>$postData['reviewing_type'],
                            'booking_id'=>$postData['booking_id'],
                            'rate'=>$postData['review_rate'],
                            'caption'=>$postData['review_caption'],
                            'description'=>$postData['review_description']
                        );
        if($this->db->insert("rating",$insert_array)){
            $respArr['status'] = "success";
            $respArr['message'] = "Reviewed Successfully";
        }
        return $respArr;
    }

    public function user_requestService($postData = array()){
        $respArr = array('status'=>'error');
        // $squence = str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);'booking_id'=>'BKGID'.date('ymd').$squence
        $insert_array = array(
                            'cust_id'=>$postData['user_id'],
                            'subservice_ids'=>implode(',',$postData['subservice_id']),
                            'booking_date'=>$postData['booking_date'],
                            'vehicle_id'=>$postData['car_id'],
                            'requirement'=>(isset($postData['message']) && !empty($postData['message']))?$postData['message']:''
                        );
        if($this->db->insert("garage_request",$insert_array)){
            $respArr['status'] = "success";
            $respArr['message'] = "Request Inserted Successfully";
        }
        return $respArr;
    }

}
?>
