<?php 
class Mechanic_model extends CI_Model {
	
	public function _consruct(){
		parent::_construct();
 	}

 	public function addMechanic($mechanic_data = array()){
 		if(empty($mechanic_data))
 			return 0;
 		$userIdChk = $this->db->query("SELECT * FROM mechanic AS MECH 
 									   INNER JOIN admin_users AS AU ON (AU.id = MECH.mechanic_id)
 									   WHERE AU.status!='2' AND 
								   			 AU.username='".$mechanic_data['username']."'");
 		if(!empty($userIdChk) && $userIdChk->num_rows() > 0) return 4;
 		$emailChk = $this->db->query("SELECT * FROM mechanic AS MECH 
 									   INNER JOIN admin_users AS AU ON (AU.id = MECH.mechanic_id)
 									   WHERE AU.status!='2' AND 
								   			 MECH.email_id='".$mechanic_data['email_id']."'");
 		if(!empty($emailChk) && $emailChk->num_rows() > 0) return 2;
 		$phoneChk = $this->db->query("SELECT * FROM mechanic AS MECH 
 									   INNER JOIN admin_users AS AU ON (AU.id = MECH.mechanic_id)
 									   WHERE AU.status!='2' AND 
								   			 MECH.phone='".$mechanic_data['phone']."'");
 		if(!empty($phoneChk) && $phoneChk->num_rows() > 0) return 3;
 		$status = $this->db->insert('admin_users',
										array('username'=>$mechanic_data['username'],
											  'password'=>$mechanic_data['password'],
											  'display_name'=>$mechanic_data['display_name'],
											  'profile_image'=>$mechanic_data['profile_image'],
											  'user_type'=>'2','status'=>'1'));
 		if(!$status){
 			return 0;
 		}
 		$mechamic_id = $this->db->insert_id();
		$status = $this->db->insert('mechanic', 
										array('mechanic_id'=>$mechamic_id,
											  'city'=>$mechanic_data['city'],
											  'phone'=>$mechanic_data['phone'],
											  'state'=>$mechanic_data['state'],
											  'shop_id'=>$mechanic_data['shop_id'],
											  'address'=>$mechanic_data['address'],
											  'licence'=>$mechanic_data['licence'],
											  'location'=>$mechanic_data['location'],
											  'email_id'=>$mechanic_data['email_id'],
											  'end_time'=>$mechanic_data['end_time'],
											  'last_name'=>$mechanic_data['last_name'],
											  'start_time'=>$mechanic_data['start_time'],
											  'first_name'=>$mechanic_data['first_name'],
											  'location_lat'=>$mechanic_data['location_lat'],
											  'location_lng'=>$mechanic_data['location_lng'],
											  'licence_number'=>$mechanic_data['licence_number'],
											  'licence_exp_date'=>$mechanic_data['licence_exp_date']));
 		return $status;
 	}

 	function getMechanic($mechanic_id = '', $view_all = 0){
 		$cond = (!empty($mechanic_id))?" MECH.mechanic_id = '".$mechanic_id."' ":"";
 		$cond .= (!empty($cond))?" AND ":$cond;
 		$cond .= (!empty($view_all))?" ADMN.status IN (0,1) ":" ADMN.status IN (1) ";
		$sql = "SELECT ADMN.username,ADMN.user_type,TRIM(CONCAT(MECH.first_name,' ' ,IFNULL(MECH.last_name,''))) as display_name,ADMN.profile_image,ADMN.status, 
				       MSH.shop_name, MSH.address AS shop_address, MSH.phone AS shop_phone, 
				       MSH.email_id AS shop_email, MECH.* 
		        FROM mechanic AS MECH 
			    INNER JOIN admin_users AS ADMN ON (ADMN.id = MECH.mechanic_id)
			    LEFT JOIN mechanic_shop AS MSH ON (MSH.shop_id = MECH.shop_id AND MSH.status = '1')
			    WHERE ".$cond;
		$result = $this->db->query($sql);
		if(empty($result)){
			return;
		}
		return (empty($mechanic_id))?$result->result():$result->row();
 	}

 	function updateMechanic($mechanic_id = '', $mechanic_data = array()){
 		if(empty($mechanic_id) || empty($mechanic_data))
 			return 0;
 		$userIdChk = $this->db->query("SELECT * FROM mechanic AS MECH 
 									   INNER JOIN admin_users AS AU ON (AU.id = MECH.mechanic_id)
 									   WHERE AU.status!='2' AND AU.id!='".$mechanic_id."' AND 
								   			 AU.username='".$mechanic_data['username']."'");
 		if(!empty($userIdChk) && $userIdChk->num_rows() > 0) { return 4; }
 		$emailChk = $this->db->query("SELECT * FROM mechanic AS MECH 
 									  INNER JOIN admin_users AS AU ON (AU.id = MECH.mechanic_id)
 									  WHERE AU.status!='2' AND AU.id!='".$mechanic_id."' AND 
								   			MECH.email_id='".$mechanic_data['email_id']."'");
 		if(!empty($emailChk) && $emailChk->num_rows() > 0) { return 2; }
 		$phoneChk = $this->db->query("SELECT * FROM mechanic AS MECH 
 									  INNER JOIN admin_users AS AU ON (AU.id = MECH.mechanic_id)
 									  WHERE AU.status!='2' AND AU.id!='".$mechanic_id."' AND 
								   			MECH.phone='".$mechanic_data['phone']."'");
 		if(!empty($phoneChk) && $phoneChk->num_rows() > 0) { return 3; }
 		$admUpdateArr = array('username'=>$mechanic_data['username'],
							  'display_name'=>$mechanic_data['display_name']);
 		if(isset($mechanic_data['profile_image']) && !empty($mechanic_data['profile_image']))
 			$admUpdateArr['profile_image'] = $mechanic_data['profile_image'];
 		$status = $this->db->update('admin_users',$admUpdateArr,array('id'=>$mechanic_id));
 		if(!$status) { return 0; }
 		$upMecArr = array(
 						'city'=>$mechanic_data['city'],'first_name'=>$mechanic_data['first_name'],
 						'state'=>$mechanic_data['state'],
 						'shop_id'=>(!empty($mechanic_data['shop_id']) ? $mechanic_data['shop_id'] : '0'),
 						'address'=>$mechanic_data['address'],'email_id'=>$mechanic_data['email_id'],
 						'last_name'=>$mechanic_data['last_name'],'phone'=>$mechanic_data['phone'],
 						'location'=>$mechanic_data['location'],
						'end_time'=>$mechanic_data['end_time'],
						'start_time'=>$mechanic_data['start_time'],
 						'location_lat'=>$mechanic_data['location_lat'],
 						'location_lng'=>$mechanic_data['location_lng'],
 						'licence_number'=>$mechanic_data['licence_number'],
 						'licence_exp_date'=>$mechanic_data['licence_exp_date']);
 						
 		if(isset($mechanic_data['licence']) && !empty($mechanic_data['licence']))
 			$upMecArr['licence'] = $mechanic_data['licence'];
 		
		$status = $this->db->update('mechanic',$upMecArr,array('mechanic_id'=>$mechanic_id));
 		return $status;
 	}

 	function changeStatus($mechanic_id = '', $status = '0'){
 		if(empty($mechanic_id)){
 			return 0;
 		}
 		$resp = $this->db->update('admin_users',array('status'=>$status),array('id'=>$mechanic_id));
 		if($status == '1'){
 			$mechData = $this->db->get_where('mechanic',array('	mechanic_id'=>$mechanic_id))->row();
 			
 			$subject    = "Profile Activation";
			$email_id   = $mechData->email_id;
			$message    = "<html>
							<body>
							  Hi,\n\r Welcome to DcarFixxers. \r\n Your account for the Username ".$email_id." is now Activated.
							</body>
						   </html>";

			$template = getNotifTemplate();
	        if(isset($template['mechanic_activation_mail']) && !empty($template['mechanic_activation_mail'])){
	            $message = str_replace(array('{:user_name}'),array($email_id),$template['mechanic_activation_mail']);
	        }
			send_mail($subject,$email_id,$message);
			$res = array('status'=>1,'data'=>'');
 		}
 		return $resp;
 	}

 	function getNearByMechanics($location_data = array(),$sub_issues = array()){
 		if(empty($location_data) || empty($sub_issues)){
 			return 0;
 		}

 		$current_lat = $location_data['pickup_lat'];
        $current_lng = $location_data['pickup_lng'];
 		$issue_cat_id = implode(',',$sub_issues);

        $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'
               -- GROUP BY ME.mechanic_id
                -- HAVING distance<30";

        $mechData = $this->db->query($sql);
        if(empty($mechData) || empty($mechData = $mechData->result_array())){
        	return 0;
        }

        $estimate = 0;
        $mechDataArr = array();
        foreach($mechData AS $index => $data){
        	$data['distance'] = (int)$data['distance'];
        	if(empty($data['start_time']) || empty($data['end_time'])){
        		$scheduleTiming = array(
        								strtotime(date('Y-m-d 09:00'))*1000,
        								strtotime(date('Y-m-d 10:00'))*1000,
        								strtotime(date('Y-m-d 11:00'))*1000,
        								strtotime(date('Y-m-d 12:00'))*1000,
        								strtotime(date('Y-m-d 13:00'))*1000,
        								strtotime(date('Y-m-d 14:00'))*1000,
        								strtotime(date('Y-m-d 15:00'))*1000,
        								strtotime(date('Y-m-d 16:00'))*1000,
        								strtotime(date('Y-m-d 17:00'))*1000,
        								strtotime(date('Y-m-d 18:00'))*1000,
        								strtotime(date('Y-m-d 19:00'))*1000,
        								strtotime(date('Y-m-d 20:00'))*1000,
        								strtotime(date('Y-m-d 21:00'))*1000,
        								);
        	} else {
        		$endTime = strtotime($data['end_time']);
			    $schTime = strtotime($data['start_time']);
			    $scheduleTiming = array();

			    for( ; $schTime <= ($endTime-3600) ; $schTime += 3600){
			    	$scheduleTiming[] = $schTime * 1000;
			    }
        	}

        	$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.*
        			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;
        }
        return $mechData;
 	}
}
?>