 <?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) || 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'=>$phoneChk['profile_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 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.*,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");
        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;
        }
        $result['review'] = [];
        $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($roadRvw = $roadRvw->result_array())){
            $result['review'] = $roadRvw;
        }
        $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');
        $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;
    }

    public function get_garageDetails($postData = array()){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT GRG.garage_code,GRG.name,GRG.code,GRG.phone_no,GROUP_CONCAT(AMT.name SEPARATOR ', ') AS amenities,GRGRES.quote_type,GRGRES.labour_cost,GRGRES.parts_cost FROM garage_response AS GRGRES INNER JOIN garage AS GRG ON (GRG.garage_id = GRGRES.garage_id) INNER JOIN amenities AS AMT ON find_in_set(AMT.id,GRG.amenities) WHERE GRGRES.garage_id=".$postData['garage_id']." AND GRGRES.req_id = ".$postData['req_id']);
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $result['review'] = [];
        $this->db->select("rating.id,rating.rate,rating.caption,rating.description");
        $this->db->join('garage_booking','garage_booking.id = rating.booking_id AND rating.type=2');
        $grgeRvw = $this->db->get_where('rating',array('garage_booking.garage_id'=>$postData['garage_id'],'rating.type'=>'2'));
        if(!empty($grgeRvw) && !empty($garageRvw = $grgeRvw->result_array())){
            $result['review'] = $garageRvw;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr; 
    }

    public function book_garage($postData = array()){
        $respArr = array('status'=>'error');
        //$squence = str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);'booking_id'=>'BKGID'.date('ymd').$squence,
        if($this->db->update('garage_request',array('resp_id'=>$postData['resp_id']),array('id'=>$postData['req_id']))){
            $respArr['status'] = "success";
            $respArr['message'] = "Garage Booked Successfully";
        }
        return $respArr;
    }

    public function search_product($keyword = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT unique_name,id,part_number FROM pos_parts WHERE unique_name LIKE '%$keyword%' OR part_number LIKE '%$keyword%'");
        if(empty($sql) || empty($result = $sql->result_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        foreach ($result as $key => $value) {
          $this->db->select("round(AVG(rate),2) AS rating ");
          $this->db->join('pos_booking','pos_booking.id = rating.booking_id AND rating.type=3');
          $this->db->join('pos_response','pos_response.id = pos_booking.resp_id');
          $posRvw = $this->db->get_where('rating',array('pos_response.pos_parts'=>$value['id']));
          if(!empty($posRvw) && !empty($posRvws = $posRvw->row_array())){
            $result[$key]['rating'] = (empty($posRvws['rating']))?'0':$posRvws['rating'];
          }
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function product_detail($prod_id = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT unique_name,id,part_number FROM pos_parts WHERE id=$prod_id");
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $this->db->select("round(AVG(rate),2) AS rating ");
        $this->db->join('pos_booking','pos_booking.id = rating.booking_id AND rating.type=3');
        $this->db->join('pos_response','pos_response.id = pos_booking.resp_id');
        $posRvw = $this->db->get_where('rating',array('pos_response.pos_parts'=>$prod_id));
        if(!empty($posRvw) && !empty($posRvws = $posRvw->row_array())){
            $result['rating'] = (empty($posRvws['rating']))?'0':$posRvws['rating'];
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function add_newadress($postData = array()){
        $respArr = array('status'=>'error');
        $postData['customer_id'] = $postData['user_id'];
        unset($postData['user_id']);
        if($this->db->insert("customer_address",$postData)){
            $respArr['status'] = "success";
            $respArr['message'] = "Address added Successfully";
        }
        return $respArr;
    }

    public function get_deliveryadress($user_id = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->get_where("customer_address",array('customer_id'=>$user_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 get_deliveryadressbyid($address_id=''){
        $respArr = array('status'=>'error');
        $sql = $this->db->get_where("customer_address",array('id'=>$address_id));
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function editaddress($postData = array()){
        $respArr = array('status'=>'error');
        $postData['customer_id'] = $postData['user_id'];
        $postData['id'] = $postData['adress_id'];
        unset($postData['user_id'], $postData['adress_id']);
        if($this->db->update("customer_address",$postData,array('id'=>$postData['id']))){
            $respArr['status'] = "success";
            $respArr['message'] = "Address Updated Successfully";
        }
        return $respArr;
    }

    public function request_product($postData = array()){
        $respArr = array('status'=>'error');
        $insert_array = array(
                            'cust_id'=>$postData['user_id'],
                            'address'=>$postData['delivery_adressId'],
                            'part_ids'=>$postData['prod_id'],
                            'vehicle_id'=>$postData['car_id']
                            );
        if($this->db->insert('pos_request',$insert_array)){
            $respArr['status'] = "success";
            $respArr['message'] = "Request For Product Inserted Successfully";
        }
        return $respArr;
    }

    public function get_requestedetails($userId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT POS.id,POS.part_number,POS.unique_name,POS.pos_parts_img,PSRSPNSE.req_id AS pos_req_id,PSBKNG.status FROM pos_booking AS PSBKNG INNER JOIN pos_response AS PSRSPNSE ON PSRSPNSE.id = PSBKNG.resp_id  INNER JOIN pos_parts AS POS ON pos_parts.id = PSRSPNSE.pos_parts WHERE PSBKNG.cust_id = $userId");
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function get_productrequestdetailsbyId($requestId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT POS.id,POS.part_number,POS.unique_name AS prdt_name,POS.pos_parts_img,PSRSPNSE.req_id AS pos_req_id,PSBKNG.status,VEHM.make,VEHM.model,VEHM.year,VEHM.vehicle_name,CUSTAD.name AS cust_name,CUSTAD.area AS cust_area,CUSTAD.country AS cust_country,CUSTAD.district AS cust_district,CUSTAD.phone_no AS cust_phone_no,CUSTAD.house_no AS cust_house_no,CUSTAD.city AS cust_city 
            FROM pos_request AS POSRQST 
            INNER JOIN pos_response AS PSRSPNSE ON PSRSPNSE.req_id = POSRQST.id  
            INNER JOIN pos_booking AS PSBKNG ON PSBKNG.resp_id = PSRSPNSE.id  
            INNER JOIN pos_parts AS POS ON pos_parts.id = PSRSPNSE.pos_parts 
            INNER JOIN vehicle_model AS VEHM ON POSRQST.vehicle_id  = VEHM.id  
            INNER JOIN customer_address AS CUSTAD ON POSRQST.address = CUSTAD.id 
            WHERE POSRQST.id = $requestId");
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function get_requestacceptedshoplist($requestId =''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT POS.pos_id,POS.profile_photo,POS.name AS shop_name,PSRSPNSE.cost
                                ,PSRSPNSE.pos_parts,PSRSPNSE.req_id
                                FROM pos_response AS PSRSPNSE  
                                INNER JOIN pos AS POS ON POS.pos_id = PSRSPNSE.pos_parts
                                WHERE PSRSPNSE.req_id = $requestId");
        if(empty($sql) || empty($result = $sql->result_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        foreach ($result as $key => $value) {
            $this->db->select("round(AVG(rate),2) AS rating ");
            $this->db->join('pos_booking','pos_booking.id = rating.booking_id AND rating.type=3');
            $this->db->join('pos_response','pos_response.id = pos_booking.resp_id');
            $posRvw = $this->db->get_where('rating',array('pos_response.pos_parts'=>$value['pos_parts']));
            if(!empty($posRvw) && !empty($posRvws = $posRvw->row_array())){
                $result[$key]['rating'] = (empty($posRvws['rating']))?'0':$posRvws['rating'];
            }
        }
        foreach ($result as $key => $row)
        {
            $rate[$key] = $row['rating'];
        }
        array_multisort($rate, SORT_DESC, $result);
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function get_shopdetails($requestId = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT POS.pos_id,POS.profile_photo,POS.name AS shop_name,PSRSPNSE.cost
                                FROM pos_response AS PSRSPNSE  
                                INNER JOIN pos AS POS ON POS.pos_id = PSRSPNSE.pos_parts
                                WHERE PSRSPNSE.req_id = $requestId");
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        $result['review'] = [];
        $this->db->select("rating.id,rating.rate,rating.caption,rating.description");
        $this->db->join('pos_booking','pos_booking.id = rating.booking_id AND rating.type=3');
        $posRvw = $this->db->get_where('rating',array('pos_booking.pos_id'=>$result['pos_id']));
        if(!empty($posRvw) && !empty($posRvws = $posRvw->result_array())){
            $result['review'] = $posRvws;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function purchaseproduct($postData = array()){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT PSRSP.total,PSRSP.pos_id,PSRQT.address FROM pos_response AS PSRSP INNER JOIN pos_request AS PSRQT ON PSRSP.req_id = PSRQT.id WHERE PSRSP.req_id =".$postData['req_id']." AND PSRSP.id =".$postData['response_id']);
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No Bookings Found";
            return $respArr;
        }
        $squence = str_pad(rand(1111,9999),4,0,STR_PAD_LEFT);
        $insert_array = array(
                                'book_id'=>'BKGID'.date('ymd').$squence,
                                'cust_id'=>$postData['user_id'],
                                'pos_id'=>$result['pos_id'],
                                'resp_id'=>$postData['response_id'],
                                'cost'=>$result['total'],
                                'address'=>$result['address'],
                                'status'=>1,
                            );
        if($this->db->insert("pos_booking",$insert_array)){
            $respArr['status'] = "Success";
            $respArr['message'] = "Success";
        }
        return $respArr;
    }

    public function get_bookedpartdetail($booking_id = ''){
        $respArr = array('status'=>'error');
        $sql = $this->db->query("SELECT PSBKNG.book_id,PSPTS.part_number,PSPTS.unique_name,PSPTS.id AS part_id,
                                PSPTS.pos_parts_img,POS.pos_code,POS.name AS pos_name,VEHM.make,VEHM.model,VEHM.year,VEHM.vehicle_name,PSBKNG.status 
                                FROM pos_booking AS PSBKNG 
                                INNER JOIN pos_response AS PSRSPNSE ON PSRSPNSE.id = PSBKNG.resp_id 
                                INNER JOIN pos_request AS PSRQST ON PSRQST.id = PSRSPNSE.req_id 
                                INNER JOIN pos_parts AS PSPTS ON PSPTS.id = PSRQST.part_ids 
                                INNER JOIN pos AS POS ON POS.pos_id = PSRSPNSE.pos_id 
                                INNER JOIN vehicle_model AS VEHM ON VEHM.id = PSRQST.vehicle_id 
                                WHERE PSBKNG.id=$booking_id"
                            );
        if(empty($sql) || empty($result = $sql->row_array())){
            $respArr['message'] = "No Booking Found";
            return $respArr;
        }
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr;
    }

    public function get_requestacceptedgarage($requestId = ''){
        $respArr = array('status'=>'error'); 
         $sql = $this->db->query("SELECT GRG.garage_id,GRG.garage_code,GRG.name,GRG.code,GRG.phone_no,GRGRES.quote_type,GRGRES.labour_cost,GRGRES.parts_cost,GRGRES.id AS garage_response_id FROM garage_response AS GRGRES INNER JOIN garage AS GRG ON (GRG.garage_id = GRGRES.garage_id) WHERE GRGRES.req_id = $requestId");
        if(empty($sql) || empty($result = $sql->result_array())){
            $respArr['message'] = "No data Found";
            return $respArr;
        }
        foreach ($result as $key => $value) {
            $this->db->select("COUNT(rating.id) AS count, round(AVG(rate),2) AS rating");
            $this->db->join('garage_booking','garage_booking.id = rating.booking_id AND rating.type=2');
            $grgeRvw = $this->db->get_where('rating',array('garage_booking.garage_id'=>$value['garage_id'],'rating.type'=>'2'));
            if(!empty($grgeRvw) && !empty($garageRvw = $grgeRvw->row_array())){
                $result[$key]['total_review'] = (isset($garageRvw['count']) && !empty($garageRvw['count']))?$garageRvw['count']:0;
                $result[$key]['rating'] = (isset($garageRvw['rating']) && !empty($garageRvw['rating']))?$garageRvw['rating']:0;
            }
        }
        foreach ($result as $key => $row)
        {
            $rate[$key] = $row['rating'];
        }
        array_multisort($rate, SORT_DESC, $result);
        $respArr['status'] = "success";
        $respArr['data'] = $result;
        return $respArr; 
    }
}
?>
