<?php 
class Booking_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
 	}
  //Schedule Booking
 	public function scheduleBooking($postData = array()){
  	if(empty($postData) || 
  	  !isset($postData['customer_id']) || empty($postData['customer_id']) || 
  	  !isset($postData['pickup_data']) || empty($postData['pickup_data']) || 
  	  !isset($postData['vechile_info']) || empty($postData['vechile_info']) || 
      !isset($postData['mechanic_id']) || empty($postData['mechanic_id']) || 
  	  !isset($postData['selected_issues']) || empty($postData['selected_issues'])){
    	return 0;
  	}
		$vehData = $postData['vechile_info'];
		$car_name = $vehData['modelYear'].' '.$vehData['maker'].' '.$vehData['modelName'].' '.$vehData['trim'];
  	$vehJson = array('vehicle'    => $car_name,
                    'year'      => $vehData['modelYear'],
  								  'make'      => $vehData['maker'],
  								  'trim'      => $vehData['trim'],
  								  'model'     => $vehData['modelName'],
  								  'engine'    => $vehData['emgine']
                   );
    $last_date = NULL;
    if(isset($vehData['lastMaintanceDate']) && !empty($vehData['lastMaintanceDate'])){
      $last_date = $vehData['lastMaintanceDate'];
    }
    $last_maintanence_date ='';
    if(isset($vehData['maintanenceInterval']) && !empty($vehData['maintanenceInterval'])){
      $last_maintanence_date = $vehData['maintanenceInterval'];
    }
    $last_id = '';
    if(isset($postData['customer_vehicle_id']) && !empty($postData['customer_vehicle_id'])){
      $last_id = $postData['customer_vehicle_id'];
      $this->db->update('customer_vehicle',array('last_maintenance_date'=>$last_date,'maintanence_interval'=>$last_maintanence_date),array('customer_veh_id'=>$postData['customer_vehicle_id']));
    }
  	$insert_array = array('customer_id'          => $postData['customer_id'],
                          'car_name'             => $car_name,
                          'car_model'            => $vehData['modelName'],
                          'car_maker'            => $vehData['maker'],
                          'car_loc_lat'          => $postData['pickup_data']['pickup_lat'],
                          'car_loc_lng'          => $postData['pickup_data']['pickup_lng'],
                          'car_location'         => $postData['pickup_data']['pickup_loc'],
                          'vehicle_data'         => json_encode($vehJson),
                          'car_model_year'       => $vehData['modelYear'],
                          'last_maintenance_date'=> $last_date,
                          'maintanence_interval' => (int)$last_maintanence_date,
                          'status'               => '3');
  	$selected_issues = array();
  	foreach($postData['selected_issues'] AS $selIssue){
  		$selected_issues[] = array('issue'             => $selIssue['issue'],
              								   'issue_id'		       => $selIssue['issue_id'],
              								   'sub_issue_id'	     => $selIssue['sub_issue_id'],
              								   'issue_category'    => $selIssue['issue_category']);
  	}
    if(empty($last_id)){
      $this->db->insert('customer_vehicle',$insert_array);
      $last_id = $this->db->insert_id();
    }
    $time = (!is_numeric($postData['schedule_date']['time']))?
                  $postData['schedule_date']['time']:
                  date('h:i A',($postData['schedule_date']['time'])/1000);

		$book_data = array('cost'			=> $postData['cost'],
						   'mileage'          => $vehData['milage'],
						   'customer_id'      => $postData['customer_id'],
						   'scheduled_date'   => $postData['schedule_date']['date'],
						   'scheduled_time'   => $time,
						   'issues_selected'  => json_encode($selected_issues),
						   'customer_veh_id'  => $last_id,
						   'custom_issue_data'=> json_encode($postData['optionalData']),
               'car_loc_lat'      => $postData['pickup_data']['pickup_lat'],
               'car_loc_lng'      => $postData['pickup_data']['pickup_lng'],
               'car_location'     => $postData['pickup_data']['pickup_loc'],
               'is_multiple'      => (isset($postData['multiple']))?$postData['multiple']:0,
						   'status'           => '0');

		if($this->db->insert('bookings',$book_data)){
      $insertBookMech = array();
      $book_id = $this->db->insert_id();
      $mechanic_id = explode(',',$postData['mechanic_id']);
      foreach ($mechanic_id AS $mech_id) {
        $mech_amt = explode(':',$mech_id);
        $insertBookMech[] = array('booking_id'=>$book_id,'mechanic_id'=>$mech_amt[0],'amount'=>$mech_amt[1],'status'=>'0');
      }
      if(!empty($insertBookMech)){
        $this->db->insert_batch('mechanic_booking',$insertBookMech);
      }
	  	return 1;
		}
  	return 0;
  }
  //Get Customer Book Details
  function getCustBookDetails($postData = array(), $status = ''){
    $cond = array();
    $where_cond = array();
    if(empty($postData) || !isset($postData['customer_id']) || empty($postData['customer_id'])){
    	return 0;
    }
  	$cond  = "BK.customer_id='".$postData['customer_id']."' ";
    $cond .= (!empty($status))?"AND BK.status IN (".$status.") ":'';
  	$sql = "SELECT BK.booking_id,BK.customer_id,BK.customer_veh_id,BK.scheduled_date,
  				         BK.scheduled_time,BK.cost,BK.is_multiple,BK.status,VEH.car_name,VEH.car_maker,
                   VEH.car_model,VEH.car_model_year,BK.status
    		    FROM bookings AS BK
    		    INNER JOIN customer_vehicle AS VEH ON (VEH.customer_veh_id = BK.customer_veh_id)
    		    WHERE $cond 
    		    GROUP BY BK.booking_id
            ORDER BY BK.booking_id DESC";
    $bookData = $this->db->query($sql);
    if(empty($bookData)){
    	return 0;
    }
    $bookDetails = array();
    $bookData = $bookData->result();
    foreach($bookData AS $book) {
      if(empty($book->scheduled_date) || empty($book->scheduled_time)){
        continue;
      }
      $bookMechData=$this->db->query("SELECT * FROM mechanic_booking 
                                      WHERE booking_id='$book->booking_id' AND status!='2'");
      if(!empty($bookMechData)){
        $bookMechData = $bookMechData->result();
        foreach ($bookMechData AS $mech_value) {
          $mechanic_data = $this->db->query("
                            SELECT ROUND(AVG(MR.rate),2) AS rating,MCH.mechanic_id,MCH.first_name,
                                   MCH.last_name,MCH.phone,CQ.custom_service_quote,MCH.location,
                                   MCH.email_id,CQ.custom_amount,BK.status,BK.amount as mechanic_amount
                            FROM mechanic_booking AS BK 
                            INNER JOIN mechanic MCH ON BK.mechanic_id=MCH.mechanic_id
                            INNER JOIN admin_users AU ON AU.id=MCH.mechanic_id
                            LEFT JOIN custom_quote CQ ON 
                                      CQ.mechanic_id=BK.mechanic_id AND 
                                      CQ.booking_id=BK.booking_id AND CQ.status='1' 
                            LEFT JOIN mechanic_rating MR ON 
                                      MR.mechanic_id=BK.mechanic_id AND MR.status='1' 
                            WHERE AU.status='1' AND BK.mechanic_id='$mech_value->mechanic_id' AND 
                                  BK.booking_id='$book->booking_id'");
          if(!empty($mechanic_data)){
            $mechData = $mechanic_data->row();
            $mechData->custom_service_quote = json_decode($mechData->custom_service_quote);
            $book->mechanic_data[] = $mechData;
            $sTime = strtotime($book->scheduled_date.' '.$book->scheduled_time);
            $cTime = strtotime('+1 hour');
            if($cTime >= $sTime){ 
              $book->status = '4';
            }
          }
        }
      }
      $bookDetails[] = $book;
    }
    return $bookDetails;
  }
  //Change  Booking status
  function changeBookStatus($customer_id = '', $booking_id = '', $status = ''){
  	if(empty($customer_id) || empty($booking_id) || $status == ''){
  		return 0;
  	}
  	$status = $this->db->update('bookings',
  									array('status'=>$status),
								    array('customer_id'=>$customer_id,'booking_id'=>$booking_id));
    $this->db->select('customer_vehicle.car_name,bookings.scheduled_date,bookings.scheduled_time,customers.email');
    $this->db->from('bookings');
    $this->db->join('customer_vehicle','customer_vehicle.customer_veh_id = bookings.customer_veh_id');
    $this->db->join('customers','customers.customer_id = bookings.customer_id');
    $this->db->where('bookings.booking_id',$booking_id);
    $bookData = $this->db->get()->row();
    $subject    = "DcarFixxers, Cancel Booking";
    $email_id   = $bookData->email;
    $message    = "<html>
            <body>
              Hi,\n\r Welcome to DcarFixxers. \r\n Your booking for the vehicle ".$bookData->car_name." on date ".$bookData->scheduled_date." at ".$bookData->scheduled_time." is Cancelled.
            </body>
             </html>";
    $template = getNotifTemplate();
    if(isset($template['cancel_booking']) && !empty($template['cancel_booking'])){
      $message = str_replace(array('{:car_name}','{:book_date}'),array($bookData->car_name,$bookData->scheduled_date),$template['cancel_booking']);
    }
    send_mail($subject,$email_id,$message);
  	return $status;
  }
  //Get Mechanic Bookings
  function getMechBookings($mechanic_id = '', $booking_id = '', $status = '1'){
  	if($this->session->userdata('user_type') != 1 && empty($mechanic_id)){
  		return 0;
  	}
    $cond  = " BK.status IN (".$status.") ";
  	$cond .= (!empty($booking_id))?" AND BK.booking_id='".$booking_id."' ":"";
  	$cond .= (!empty($mechanic_id))?" AND MBK.mechanic_id='".$mechanic_id."' ":"";
    $sql = "SELECT GROUP_CONCAT(DISTINCT(MBK.mechanic_id)) AS mechanic_ids,MBK.amount as cost,BK.booking_id,BK.customer_id,BK.customer_veh_id,BK.scheduled_date,BK.scheduled_time,BK.status,BK.mileage,BK.issues_selected,VEH.car_name,BK.custom_issue_data,VEH.car_model,VEH.car_maker,
      VEH.car_model_year,VEH.car_vin,VEH.vehicle_data,BK.car_location,BK.car_loc_lat,BK.car_loc_lng,
      CUST.first_name AS custFirstName,CUST.last_name AS custLastName,CUST.phone,CUST.email,CUST.address
      ,CUST.profile_image,CUST.date_of_birth,CUSQTE.custom_id,MBK.status AS mech_status
	    FROM bookings AS BK
      INNER JOIN mechanic_booking AS MBK ON (MBK.booking_id=BK.booking_id)
	    INNER JOIN customers AS CUST ON (CUST.customer_id=BK.customer_id)
	    INNER JOIN admin_users AS ADM ON (ADM.id=MBK.mechanic_id)
	    INNER JOIN customer_vehicle AS VEH ON (VEH.customer_veh_id=BK.customer_veh_id)
      LEFT JOIN custom_quote AS CUSQTE on (CUSQTE.booking_id = BK.booking_id 
                                            AND CUSQTE.mechanic_id=MBK.mechanic_id)
	    WHERE $cond AND ADM.status='1' AND CUST.status='1' 
	    GROUP BY BK.booking_id";
    $bookData = $this->db->query($sql);
    if(!empty($bookData)){
      if(empty($booking_id)){
        return $bookData->result();
      }
      $bookedMechanics = array();
    	$bookData = $bookData->row();
      if(!empty($bookData->mechanic_ids)){
        $mechanics = explode(',',$bookData->mechanic_ids);
        foreach ($mechanics AS $mech_id) {
          $mechanic_data = $this->db->query("
                            SELECT ROUND(AVG(MR.rate),2) AS rating,MCH.mechanic_id,MCH.first_name,
                                   MCH.last_name,MCH.phone,CQ.custom_service_quote,MCH.location,
                                   MCH.email_id,CQ.custom_amount,
                                   CASE
                                   WHEN BK.status = '0' THEN 'Pending'
                                   WHEN BK.status = '1' THEN 'Accept'
                                   ELSE 'Reject' END as status 
                            FROM mechanic_booking AS BK 
                            INNER JOIN mechanic MCH ON BK.mechanic_id=MCH.mechanic_id
                            INNER JOIN admin_users AU ON AU.id=MCH.mechanic_id
                            LEFT JOIN custom_quote CQ ON 
                                      CQ.mechanic_id=BK.mechanic_id AND 
                                      CQ.booking_id=BK.booking_id AND CQ.status='1' 
                            LEFT JOIN mechanic_rating MR ON 
                                      MR.mechanic_id=BK.mechanic_id AND MR.status='1' 
                            WHERE AU.status='1' AND BK.mechanic_id='$mech_id' AND BK.booking_id='$booking_id'");
          if(!empty($mechanic_data)){
            $mechData = $mechanic_data->row();
            $mechData->custom_service_quote = json_decode($mechData->custom_service_quote);
            $bookedMechanics[] = $mechData;
          }
        }
        $bookData->mechanic_data = $bookedMechanics;
      }
  	  return $bookData;
    }
    return 0;
  }
  //Change Status
  function changeStatus($booking_id = '', $status = '0'){
		if(empty($booking_id)){
			return 0;
		}
    if($this->session->userdata('user_type')==1){
      if($status == '1'){
        $status=$this->db->update('bookings',array('status'=>'0'),array('booking_id'=>$booking_id));
      }
      else if($status == '4'){
       $status=$this->db->update('bookings',array('status'=>'4'),array('booking_id'=>$booking_id));
      }
      else if($status == '2'){
        $this->db->update('bookings',array('status'=>'2'),array('booking_id'=>$booking_id));
      }
    }else{
      $id = $this->session->userdata('id');
      if($status == '4'){
        $this->db->update('mechanic_booking',
                          array('status'=>'2'),
                          array('booking_id'=>$booking_id,'mechanic_id'=> $id));
      }
      else if($status == '1'){
        $this->db->update('mechanic_booking',
                          array('status'=>'1'),
                          array('booking_id'=>$booking_id,'mechanic_id'=> $id));
      }
      else if($status == '2'){
        $this->db->update('mechanic_booking',
                          array('status'=>'2'),
                          array('booking_id'=>$booking_id,'mechanic_id'=> $id));
      }
    }
		return $status;
  }
  //Insert Custom Quote
  function insertCustomQuote($data){
  	$custData = array();$total=0;
  	$book_id = decode_param($data['booking_id']);
    $mechanic_id = ($this->session->userdata('user_type')==2)?$this->session->userdata('id'):'';
  	unset($data['booking_id']);
  	for($i=0 ; $i < count($data['description']);$i++){
  		$custData[$i]['issue_id']=$data['issue_id'][$i];
      $custData[$i]['sub_issue_id']=$data['sub_issue_id'][$i];
  		$custData[$i]['issue_category']=$data['issue_category'][$i];
  		$custData[$i]['description']=$data['description'][$i];
  		$custData[$i]['amount']=$data['amount'][$i];
  		$total += $data['amount'][$i];
  	}
  	$book_data = $this->db->get_where('custom_quote',array('booking_id'=>$book_id));
  	if(!empty($book_data) && $book_data->num_rows() > 0){
  		$this->db->update('custom_quote',array('custom_service_quote'=>json_encode($custData),'mechanic_id'=>$mechanic_id,'custom_amount'=>$total),array('booking_id'=>$book_id));
  		$res = array('status'=>'success');
  	}else{
  		if($this->db->insert('custom_quote',array('booking_id'=>$book_id,'mechanic_id'=>$mechanic_id,'custom_service_quote'=>json_encode($custData),'custom_amount'=>$total))){
        $last_id = $this->db->insert_id();
    		$res = array('status'=>'success','data'=>encode_param($last_id));
    	}
  	}
  	return $res;
  }
  //Generate Custom Data
  public function getCustomData($customid){
    $this->db->select('custom_quote.custom_service_quote,custom_quote.custom_amount,bookings.issues_selected');
    $this->db->join('bookings','bookings.booking_id = custom_quote.booking_id');
    $this->db->where('custom_quote.custom_id',$customid);
    $custData = $this->db->get('custom_quote');
    if(!empty($custData) && $custData->num_rows() > 0){
      $custData = $custData->row_array();
      return $custData;
    }
    return 0;
  }
}
?>
