<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjListings extends pjFront
{
	private $isoDatePattern = '/\d{4}-\d{2}-\d{2}/';
	
	public function pjActionIndex()
	{
		pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionListings");
	}
	
	public function pjActionListings()
	{
		$pjListingModel = pjListingModel::factory()
			->join('pjUser', "t2.id=t1.owner_id", 'left')
			->join('pjType', "t3.id=t1.type_id", 'left')
			->join('pjMultiLang', "t4.model='pjType' AND t4.foreign_id=t3.id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t6.model='pjListing' AND t6.foreign_id=t1.id AND t6.field='description' AND t6.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t7.model='pjCountry' AND t7.foreign_id=t1.country_id AND t7.field='name' AND t7.locale='".$this->getLocaleId()."'", 'left');
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
		$pjListingModel->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')");
	
		if (isset($_GET['listing_search']))
		{
			if (isset($_GET['season']) && $_GET['season'] != '')
			{
				$season_arr = explode(',', $_GET['season']);
				$where_arr = array();
				foreach($season_arr as $v)
				{
					$where_arr[] = "(t1.listing_season LIKE '%".pjObject::escapeString($v)."%')";
				}
				$pjListingModel->where("(" . implode(" OR ", $where_arr) . ")");
			}
	
			if (isset($_GET['type']) && $_GET['type'] != '')
			{
				$_type_arr = explode(",", $_GET['type']);
				$is_valid = true;
				foreach($_type_arr as $type_id)
				{
					if(!((int)$type_id > 0))
					{
						$is_valid = false;
					}
				}
				if($is_valid == true)
				{
					$pjListingModel->where("(t1.type_id IN(".$_GET['type']."))");
				}
			}
	
			if (isset($_GET['location']) && !empty($_GET['location']))
			{
				$pjListingModel->where("(t1.address_city LIKE '%". pjObject::escapeString($_GET['location']) ."%' OR t7.content LIKE '%". pjObject::escapeString($_GET['location']) ."%')");
			}
			if (isset($_GET['rating_from']) && (int) $_GET['rating_from'] > 0 && isset($_GET['rating_to']) && (int) $_GET['rating_to'] > 0)
			{
				$pjListingModel->where("(t1.listing_rating >= " . $_GET['rating_from'] . " AND t1.listing_rating <= ". $_GET['rating_to'] .")");
			}
			if (isset($_GET['price_from']) && is_numeric($_GET['price_from']) && isset($_GET['price_to']) && is_numeric($_GET['price_to']))
			{
				$price_from = $_GET['price_from'];
				$price_to = $_GET['price_to'];
					
				$pjListingModel->where("t1.id IN(SELECT TP.listing_id FROM `".pjPriceModel::factory()->getTable()."` as TP WHERE TP.price BETWEEN $price_from AND $price_to)");
			} else {
				if (isset($_GET['price_from']) && is_numeric($_GET['price_from']))
				{
					$price_from = $_GET['price_from'];
					$pjListingModel->where("t1.id IN(SELECT TP.listing_id FROM `".pjPriceModel::factory()->getTable()."` as TP WHERE TP.price >= $price_from)");
				} elseif (isset($_GET['price_to']) && is_numeric($_GET['price_to'])) {
					$price_to = $_GET['price_to'];
					$pjListingModel->where("t1.id IN(SELECT TP.listing_id FROM `".pjPriceModel::factory()->getTable()."` as TP WHERE TP.price <= $price_to)");
				}
			}
		}
	
		$sorting = 't1.is_featured DESC, t1.created DESC, listing_title ASC';
		$sorting_arr = array();
		if(isset($_GET['column']) && in_array($_GET['column'], array('min', 'listing_rating')) && isset($_GET['direction']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
		{
			$sorting = $_GET['column'] . ' ' . $_GET['direction'];
		}
		
		$total = $pjListingModel->findCount()->getData();
		$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : $this->getDefaultItemPerPage();
		
		$pages = ceil($total / $rowCount);
		$page = isset($_GET['pjPage']) && (int) $_GET['pjPage'] > 0 ? intval($_GET['pjPage']) : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}
	
		$pjListingModel
			->select(sprintf("t1.*, t5.content as listing_title, ,t6.content as listing_description, t7.content as country_title, t4.content AS type_title, t2.name AS owner_name,
				(SELECT `medium_path` FROM `%1\$s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `image`,
				(SELECT `large_path` FROM `%1\$s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `large_image`,
				(SELECT COUNT(*) FROM `%1\$s` AS TG WHERE TG.foreign_id = t1.id LIMIT 1) AS `cnt_photos`,
				(SELECT MIN(`price`) FROM `%2\$s` AS t8 WHERE t8.listing_id = t1.id GROUP BY t8.listing_id LIMIT 1) AS `min`,
				(SELECT MAX(`price`) FROM `%2\$s` AS t9 WHERE t9.listing_id = t1.id GROUP BY t9.listing_id LIMIT 1) AS `max`,
				(SELECT AVG(t11.rating) FROM `%3\$s` AS t11 WHERE t11.listing_id = t1.id AND t11.status = 'Confirmed' AND t11.rating IS NOT NULL LIMIT 1) AS `avg_rating`,
				(SELECT COUNT(*) FROM `%3\$s` AS t12 WHERE t12.listing_id = t1.id AND t12.status = 'Confirmed' AND t12.rating IS NOT NULL LIMIT 1) AS `number_of_comments`",
				pjGalleryModel::factory()->getTable(), pjPriceModel::factory()->getTable(), pjCommentModel::factory()->getTable()
			))
			->orderBy($sorting);
	
		if($this->getDefaultView() != 'map')
		{
			$pjListingModel->limit($rowCount, $offset);
		}
	
		$arr = 	$pjListingModel->findAll()->getData();
	
		$type_arr = pjTypeModel::factory()->select("t1.*, t2.content AS name, (SELECT COUNT(*) FROM `".pjListingModel::factory()->getTable()."` as TL WHERE TL.type_id = t1.id AND (TL.status = 'T' OR (TL.status = 'E' AND TL.expire >= CURDATE()))) AS `number_of_packages`")
			->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
			
		$city_arr = pjListingModel::factory()->select('`address_city`')->groupBy('`address_city`')->orderBy("`address_city` asc")->findAll()->getData();
	
		if(isset($_SESSION['VPL_BACK_URL']))
		{
			unset($_SESSION['VPL_BACK_URL']);
		}
	
		$pjListingModel->reset()
			->join('pjUser', "t2.id=t1.owner_id", 'left')
			->join('pjType', "t3.id=t1.type_id", 'left')
			->join('pjMultiLang', "t4.model='pjCountry' AND t4.foreign_id=t1.country_id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left');
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
		$pjListingModel->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')");
		$country_arr = $pjListingModel->select('t4.content as country_title')->groupBy('`country_title`')->orderBy("`country_title` asc")->findAll()->getData();
	
		$location_arr = array();
		foreach($city_arr as $v)
		{
			if(!empty($v['address_city']))
			{
				$location_arr[] = $v['address_city'];
			}
		}
		foreach($country_arr as $v)
		{
			$location_arr[] = $v['country_title'];
		}
	
		$season_arr = array();
		for($i = 1; $i <= 4; $i++)
		{
			$season_arr[$i] = $pjListingModel
				->reset()
				->join('pjUser', "t2.id=t1.owner_id", 'left')
				->join('pjType', "t3.id=t1.type_id", 'left')
				->where('t1.listing_season LIKE', '%'.$i.'%')
				->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))")
				->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')")
				->findCount()
				->getData();
		}
	
		$this->set('arr', $arr);
		$this->set('paginator', array('pages' => $pages, 'total' => $total));
		$this->set('type_arr', $type_arr);
		$this->set('location_arr', $location_arr);
		$this->set('season_arr', $season_arr);
	}
	
	public function pjActionFeatured()
	{
		$this->set('arr', $this->getFeaturedListings($this->option_arr, $this->getLocaleId()));		
	}
	
	public function pjActionView()
	{
		$pjListingModel = pjListingModel::factory();
		
		if(isset($_POST['booking_form']))
		{
			$listing_id = $_POST['listing_id'];
			$err = '';
			if (!isset($_POST['email']))
			{
				$err = 9901;
			}
			if (!isset($_POST['name']))
			{
				$err = 9904;
			}
			if (!isset($_POST['captcha']))
			{
				$err = 9905;
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 9906;
			}
			if (isset($_POST['name']) && !pjValidation::pjActionNotEmpty($_POST['name']))
			{
				$err= 9909;
			}
			if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
			{
				$err= 9910;
			}
			if ( (isset($_POST['captcha']) && !pjCaptcha::validate(strtoupper($_POST['captcha']), $_SESSION[$this->defaultCaptcha])) || !isset($_SESSION[$this->defaultCaptcha]))
			{
				$err= 9911;
			}
			if (isset($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err= 9912;
			}
			$_SESSION[$this->defaultCaptcha] = NULL;
			unset($_SESSION[$this->defaultCaptcha]);
			if (empty($err))
			{
				$start_date = null;
				$end_date = null;
				if($_POST['date_from'] != '')
				{
					$start_date = $_POST['date_from'];
					$_POST['date_from'] = pjUtil::formatDate($_POST['date_from'], $this->option_arr['o_date_format']);
				}
				if($_POST['date_to'] != '')
				{
					$end_date = $_POST['date_to'];
					$_POST['date_to'] = pjUtil::formatDate($_POST['date_to'], $this->option_arr['o_date_format']);
				}
				
				$id = pjEnquiryModel::factory()->setAttributes($_POST)->insert()->getInsertId();
				
				$arr = $pjListingModel->select("t1.*, t2.content AS subject, t3.content AS message, t4.email AS owner_email, t4.name as owner_name, t5.content AS listing_title")
					->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='confirm_subject' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='confirm_tokens' AND t3.locale='".$this->getLocaleId()."'", 'left')
					->join('pjUser', "t4.id=t1.owner_id AND t4.role_id = '3'", 'left')
					->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left')
					->find($listing_id)
					->getData();
				
				if ($id !== false && (int) $id > 0)
				{
					$email_data = array();				
					$email_default = pjNotificationModel::factory()->where('user_id', 1)->findAll()->getData();				
					if(count($email_default) > 0)
					{
						$email_data = $email_default[0];
					}
					
					$to_arr = array();
					if(!empty($arr['owner_id'])){
						$to_arr[] = $arr['owner_email'];
						$email_owner = pjNotificationModel::factory()->where('user_id', $arr['owner_id'])->findAll()->getData();				
						if(count($email_owner) > 0)
						{
							$email_data = $email_owner[0];
						}
					}else{
						$to_arr = $this->getAdminEmail();
					}							
					if(!empty($email_data))
					{				
						$email_data['i18n'] = pjMultiLangModel::factory()->getMultiLang($email_data['id'], 'pjNotification');
						
						if(!empty($email_data['i18n'][$this->getLocaleId()]['confirm_subject']) && !empty($email_data['i18n'][$this->getLocaleId()]['confirm_message']))
						{
							$subject = $email_data['i18n'][$this->getLocaleId()]['confirm_subject'];
							$message = str_replace(	array('{OwnerName}', '{FullName}', '{Email}', '{Phone}', '{Notes}', '{StartDate}', '{EndDate}', '{ListingID}', '{ListingTitle}', '{EnquiryID}'), 
													array($arr['owner_name'], $_POST['name'], $_POST['email'], $_POST['phone'], $_POST['notes'], $start_date, $end_date, $arr['listing_refid'], $arr['listing_title'], $id), 
													$email_data['i18n'][$this->getLocaleId()]['confirm_message']);
													
							$pjEmail = new pjEmail();
							if ($this->option_arr['o_send_email'] == 'smtp' && 
								$this->option_arr['o_smtp_host'] != '' && 
								$this->option_arr['o_smtp_port'] != '' &&
								$this->option_arr['o_smtp_user'] != '' &&
								$this->option_arr['o_smtp_pass'] != '')
							{
								$pjEmail
									->setTransport('smtp')
									->setSmtpHost($this->option_arr['o_smtp_host'])
									->setSmtpPort($this->option_arr['o_smtp_port'])
									->setSmtpUser($this->option_arr['o_smtp_user'])
									->setSmtpPass($this->option_arr['o_smtp_pass'])
									->setSender($this->option_arr['o_smtp_user'])
								;
							}
							$from = $this->getFromEmail($this->option_arr);
							foreach($to_arr as $to)
							{
								$pjEmail
									->setFrom($from)
									->setTo($to)
									->setSubject($subject)
									->send($message);
							}
						}
					}	
					$err = 'FR02';
				}else{
					$err = 'FR03';
				}
				
				$_SESSION['VPL_ENQUIRY_POST'] = $err;
				
				if ($this->option_arr['o_seo_url'] == 'No')
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller='.$_GET['controller'].'&action=pjActionView&id='.$listing_id . (isset($_POST['iframe']) ? '&iframe' : NULL) . '#pjVpEnquirySection');
				} else {
					$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
					$path = $path == '/' ? '' : $path;
					$url = $path .'/'. $this->friendlyURL($arr['listing_title']) . "-". $arr['id'] . ".html#pjVpEnquirySection";
					pjUtil::redirect($url);
				}
			}
		}
		
		if(isset($_POST['comment_form']))
		{
			$listing_id = $_POST['listing_id'];
			
			$err = '';
			if (!isset($_POST['email']))
			{
				$err = 9901;
			}
			if (!isset($_POST['name']))
			{
				$err = 9904;
			}
			if (!isset($_POST['comment']))
			{
				$err = 9914;
			}
			if (!isset($_POST['captcha']))
			{
				$err = 9905;
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 9906;
			}
			if (isset($_POST['name']) && !pjValidation::pjActionNotEmpty($_POST['name']))
			{
				$err= 9909;
			}
			if (isset($_POST['comment']) && !pjValidation::pjActionNotEmpty($_POST['comment']))
			{
				$err= 9915;
			}
			if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
			{
				$err= 9910;
			}
			if ( (isset($_POST['captcha']) && !pjCaptcha::validate(strtoupper($_POST['captcha']), $_SESSION[$this->defaultCommentCaptcha])) || !isset($_SESSION[$this->defaultCommentCaptcha]))
			{
				$err= 9911;
			}
			if (isset($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err= 9912;
			}
			$_SESSION[$this->defaultCommentCaptcha] = NULL;
			unset($_SESSION[$this->defaultCommentCaptcha]);
			if (empty($err))
			{
				$comment_status = $this->option_arr['o_comment_default_status'];
				$_POST['status'] = $comment_status;
				
				$rating = '';
				if(empty($_POST['rating'])){
					unset($_POST['rating']);
				}else{
					$rating = $_POST['rating'];
				}
				$id = pjCommentModel::factory()->setAttributes($_POST)->insert()->getInsertId();
				
				$arr = $pjListingModel 
					->select("t1.*, t2.content AS subject, t3.content AS message, t4.email AS owner_email, t4.name as owner_name, t5.content AS listing_title")
					->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='comment_notify_subject' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='comment_notify_body' AND t3.locale='".$this->getLocaleId()."'", 'left')
					->join('pjUser', "t4.id=t1.owner_id AND t4.role_id = '3'", 'left')
					->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left')
					->find($listing_id)
					->getData();

				if ($id !== false && (int) $id > 0)
				{
					
					$email_data = array();				
									
					$email_default = pjNotificationModel::factory()->where('user_id', 1)->findAll()->getData();				
					if(count($email_default) > 0){
						$email_data = $email_default[0];
					}
								
					if(!empty($email_data))
					{				
						$email_data['i18n'] = pjMultiLangModel::factory()->getMultiLang($email_data['id'], 'pjNotification');
						if(!empty($email_data['i18n'][$this->getLocaleId()]['notify_subject']) && !empty($email_data['i18n'][$this->getLocaleId()]['notify_message']))
						{				
							$subject = $email_data['i18n'][$this->getLocaleId()]['notify_subject'];
							$message = str_replace(	array('{OwnerName}', '{Name}', '{Email}', '{Rating}', '{Title}', '{Comment}', '{RefID}', '{ListingTitle}'), 
													array($arr['owner_name'], $_POST['name'], $_POST['email'], $rating, $_POST['title'], $_POST['comment'], $arr['listing_refid'], $arr['listing_title']), 
													$email_data['i18n'][$this->getLocaleId()]['notify_message']);
							$pjEmail = new pjEmail();
							if ($this->option_arr['o_send_email'] == 'smtp' && 
								$this->option_arr['o_smtp_host'] != '' && 
								$this->option_arr['o_smtp_port'] != '' &&
								$this->option_arr['o_smtp_user'] != '' &&
								$this->option_arr['o_smtp_pass'] != '')
							{
								$pjEmail
									->setTransport('smtp')
									->setSmtpHost($this->option_arr['o_smtp_host'])
									->setSmtpPort($this->option_arr['o_smtp_port'])
									->setSmtpUser($this->option_arr['o_smtp_user'])
									->setSmtpPass($this->option_arr['o_smtp_pass'])
									->setSender($this->option_arr['o_smtp_user'])
								;
							}
							$from = $this->getFromEmail($this->option_arr);
							if(!empty($arr['owner_email'])){
								$pjEmail
									->setFrom($from)
									->setTo($arr['owner_email'])
									->setSubject($subject)
									->send($message);
							}else{
								$to_arr = $this->getAdminEmail();
								foreach($to_arr as $to)
								{
									$pjEmail
										->setFrom($from)
										->setTo($to)
										->setSubject($subject)
										->send($message);
								}
							}
						}
					}
					if($comment_status == 'New')
					{
						$err = 'FRC02';
					}else{
						$err = 'FRC03';
					}
				}else{
					$err = 'FRC04';
				}
			}
			$_SESSION['VPL_COMMENT_POST'] = $err;
			
			if ($this->option_arr['o_seo_url'] == 'No')
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller='.$_GET['controller'].'&action=pjActionView&id='.$listing_id . (isset($_POST['iframe']) ? '&iframe' : NULL) . '#pjVpCommentSection');
			} else {
				$path = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
				$path = $path == '/' ? '' : $path;
				$url = $path .'/'. $this->friendlyURL($arr['listing_title']) . "-". $arr['id'] . ".html#pjVpCommentSection";
				pjUtil::redirect($url);
			}
		}
		
		$arr = $pjListingModel
			->select(sprintf("t1.*, t2.content AS type_title, t3.content AS country_title, t4.content AS listing_title,
				t5.content AS listing_description, t6.content AS listing_terms, t7.content AS meta_title,
				t8.content AS meta_keywords, t9.content AS meta_description, t10.content AS flight_notes,
				t11.content AS checkin, t12.content AS checkout, t13.content AS pets, t14.content AS policies, t15.content AS fees,
				(SELECT MIN(`price`) FROM `%1\$s` AS TP1 WHERE TP1.listing_id = t1.id GROUP BY `listing_id` LIMIT 1) AS `min`,
				(SELECT MAX(`price`) FROM `%1\$s` AS TP2 WHERE TP2.listing_id = t1.id GROUP BY `listing_id` LIMIT 1) AS `max`,
				(SELECT AVG(t11.rating) FROM `%2\$s` as t11 WHERE t11.listing_id = t1.id AND t11.status = 'Confirmed' AND t11.rating IS NOT NULL) AS `avg_rating`,
				(SELECT COUNT(*) FROM `%2\$s` as t12 WHERE t12.listing_id = t1.id AND t12.status = 'Confirmed' AND t12.rating IS NOT NULL LIMIT 1) AS `number_of_comments`",
				pjPriceModel::factory()->getTable(), pjCommentModel::factory()->getTable()
			))
			->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.type_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.country_id AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t4.model='pjListing' AND t4.foreign_id=t1.id AND t4.field='title' AND t4.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='description' AND t5.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t6.model='pjListing' AND t6.foreign_id=t1.id AND t6.field='terms' AND t6.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t7.model='pjListing' AND t7.foreign_id=t1.id AND t7.field='meta_title' AND t7.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t8.model='pjListing' AND t8.foreign_id=t1.id AND t8.field='meta_keywords' AND t8.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t9.model='pjListing' AND t9.foreign_id=t1.id AND t9.field='meta_description' AND t9.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t10.model='pjListing' AND t10.foreign_id=t1.id AND t10.field='flight_notes' AND t10.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t11.model='pjListing' AND t11.foreign_id=t1.id AND t11.field='checkin' AND t11.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t12.model='pjListing' AND t12.foreign_id=t1.id AND t12.field='checkout' AND t12.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t13.model='pjListing' AND t13.foreign_id=t1.id AND t13.field='pets' AND t13.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t14.model='pjListing' AND t14.foreign_id=t1.id AND t14.field='policies' AND t14.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t15.model='pjListing' AND t15.foreign_id=t1.id AND t15.field='fees' AND t15.locale='".$this->getLocaleId()."'", 'left')
			->where('t1.id', $_GET['id'])
			->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))")
			
			->limit(1)
			->findAll()
			->getData();
		
		if (count($arr) === 1)
		{
			$arr = $arr[0];
			
			$pjListingModel->reset()->setAttributes(array('id' => $arr['id']))->modify(array('views' => $arr['views'] + 1));
			
			$this->set('feature_arr', pjFeatureModel::factory()
				->select('t1.*, t2.content AS feature_title')
				->join('pjMultiLang', "t2.model='pjFeature' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->where('t1.status', 'T')
				->orderBy('feature_title ASC')
				->findAll()
				->getData()
			);
			
			$this->set('gallery_arr', pjGalleryModel::factory()->where('t1.foreign_id', $_GET['id'])->orderBy('t1.sort ASC')->findAll()->getData());
			$feature_ids = pjListingFeatureModel::factory()->where('t1.listing_id', $_GET['id'])->findAll()->getDataPair(NULL, 'feature_id');
			
			$feature_arr = array();
			if(count($feature_ids) > 0)
			{
				$feature_arr = pjFeatureModel::factory()->select('t1.*, t2.content as feature_title')
								->join('pjMultiLang', "t2.model='pjFeature' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->whereIn('t1.id', $feature_ids)->findAll()->getData();
			}
			
			$this->set('price_arr', pjPriceModel::factory()
				->select('t1.*, t2.content as price_title')
				->join('pjMultiLang', "t2.model='pjPrice' AND t2.foreign_id=t1.id AND t2.field='price_title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->where('listing_id', $_GET['id'])
				->orderBy('date_from ASC, date_to ASC')
				->findAll()
				->getData()
			);
			
			$this->set('listing_id', $_GET['id']);
			
			$this->set('arr', $arr);
			$this->set('feature_arr', $feature_arr);
			
			$this->set('comment_arr', pjCommentModel::factory()
				->where('status', 'Confirmed')
				->where('listing_id', $_GET['id'])
				->orderBy('created DESC')
				->findAll()
				->getData()
			);
			
			$this->set('meta_arr', array(
				'title' => $arr['meta_title'],
				'keywords' => $arr['meta_keywords'],
				'description' => $arr['meta_description']
			));
			
			if(!empty($arr['owner_id']))
			{
				$this->set('contact_arr', pjUserModel::factory()->find($arr['owner_id'])->getData());
				
				$this->set('owner_option_arr', $this->getOwnerOptions($arr['owner_id']));
			}
			
			if(isset($_SESSION['VPL_COMMENT_POST']))
			{
				$this->set('comment_message', $_SESSION['VPL_COMMENT_POST']);
				unset($_SESSION['VPL_COMMENT_POST']);
			}
			if(isset($_SESSION['VPL_ENQUIRY_POST']))
			{
				$this->set('enquiry_message', $_SESSION['VPL_ENQUIRY_POST']);
				unset($_SESSION['VPL_ENQUIRY_POST']);
			}
		}
	}
	
	public function pjActionRegister()
	{
		if ($this->option_arr['o_allow_add_package'] == 'Yes')
		{
			if (isset($_POST['register']))
			{
				$redirect_url = pjUtil::buildFrontUrl($_SERVER['PHP_SELF']. '?controller='.$_GET['controller'].'&action=pjActionRegister', $_GET);
				
				set_time_limit(0);
				
				$err = array();
				
				if (!isset($_POST['email']))
				{
					$err[] = 9901;
				}
				if (!isset($_POST['password']))
				{
					$err[] = 9902;
				}
				if (!isset($_POST['retype_password']))
				{
					$err[] = 9903;
				}
				if (!isset($_POST['name']))
				{
					$err[] = 9904;
				}
				if (!isset($_POST['captcha']))
				{
					$err[] = 9905;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
				{
					$err[] = 9906;
				}
				if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']))
				{
					$err[] = 9907;
				}
				if (isset($_POST['retype_password']) && !pjValidation::pjActionNotEmpty($_POST['retype_password']))
				{
					$err[] = 9908;
				}
				if (isset($_POST['name']) && !pjValidation::pjActionNotEmpty($_POST['name']))
				{
					$err[] = 9909;
				}
				if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
				{
					$err[] = 9910;
				}
				if ( (isset($_POST['captcha']) && !pjCaptcha::validate(strtoupper($_POST['captcha']), $_SESSION[$this->defaultCaptcha])) || !isset($_SESSION[$this->defaultCaptcha]))
				{
					$err= 9911;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
				{
					$err[] = 9912;
				}
				if (isset($_POST['password']) && isset($_POST['retype_password']) && $_POST['password'] != $_POST['retype_password'])
				{
					$err[] = 9913;
				}
				
				$_SESSION[$this->defaultCaptcha] = NULL;
				unset($_SESSION[$this->defaultCaptcha]);
				
				if (!empty($err))
				{
					$_SESSION['REGISTER_STATUS']= $err;
					$_SESSION['REGISTER_DATA'] = $_POST;
					pjUtil::redirect($redirect_url . "&err=9900");
				}
				
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->where('t1.email', $_POST['email'])->findAll()->getData();
				
				if (!empty($arr) && count($arr) > 0)
				{
					$_SESSION['REGISTER_STATUS'][]= 9997;
					$_SESSION['REGISTER_DATA'] = $_POST;
					pjUtil::redirect($redirect_url . "&err=9900");
				}else{
					$data['password'] = $_POST['password'];
					$data['email'] = $_POST['email'];
					$data['name'] = $_POST['name'];
					$data['role_id'] = 3;
					$data['is_active'] = 'F';
					$data['status'] = $this->option_arr['o_owner_is_active'] == 'Yes' ? 'T' : 'F';
					$data['ip'] = $_SERVER['REMOTE_ADDR'];
					$id = $pjUserModel->reset()->setAttributes($data)->insert()->getInsertId();
					if ($id !== false && (int) $id > 0)
					{
						pjOptionModel::factory()->saveOwnerOptions($id);
						
						if($this->option_arr['o_owner_is_active'] == 'Yes')
						{
							$err = 9999;
						}else{
							$err = 9998;
						}
						
						$email_data = array();				
								
						$email_default = pjNotificationModel::factory()->where('user_id', 1)->findAll()->getData();				
						if(count($email_default) > 0)
						{
							$email_data = $email_default[0];
						}
						if(!empty($email_data))
						{				
							$email_data['i18n'] = pjMultiLangModel::factory()->getMultiLang($email_data['id'], 'pjNotification');
							if(!empty($email_data['i18n'][$this->getLocaleId()]['new_account_subject']) && !empty($email_data['i18n'][$this->getLocaleId()]['new_account_message']))
							{				
								$subject = $email_data['i18n'][$this->getLocaleId()]['new_account_subject'];
								$message = str_replace(	array('{Email}', '{Name}'), 
														array($_POST['email'], $_POST['name']), 
														$email_data['i18n'][$this->getLocaleId()]['new_account_message']);
								$pjEmail = new pjEmail();
								if ($this->option_arr['o_send_email'] == 'smtp' && 
									$this->option_arr['o_smtp_host'] != '' && 
									$this->option_arr['o_smtp_port'] != '' &&
									$this->option_arr['o_smtp_user'] != '' &&
									$this->option_arr['o_smtp_pass'] != '')
								{
									$pjEmail
										->setTransport('smtp')
										->setSmtpHost($this->option_arr['o_smtp_host'])
										->setSmtpPort($this->option_arr['o_smtp_port'])
										->setSmtpUser($this->option_arr['o_smtp_user'])
										->setSmtpPass($this->option_arr['o_smtp_pass'])
										->setSender($this->option_arr['o_smtp_user'])
									;
								}
								$to_arr = $this->getAdminEmail();
								$from = $this->getFromEmail($this->option_arr);
								foreach($to_arr as $to)
								{	
									$pjEmail
										->setFrom($from)
										->setTo($to)
										->setSubject($subject)
										->send($message);
								}
							}
						}
						
						pjUtil::redirect($redirect_url . "&err=$err");
						exit;
					}
				}
			}else{
				if(!isset($_GET['err']))
				{
					if(isset($_SESSION['REGISTER_STATUS']))
					{
						unset($_SESSION['REGISTER_STATUS']);
					}
					if(isset($_SESSION['REGISTER_DATA'])){
						unset($_SESSION['REGISTER_DATA']);
					}
				}else{
					if($_GET['err'] != 9900)
					{
						if(isset($_SESSION['REGISTER_STATUS']))
						{
							unset($_SESSION['REGISTER_STATUS']);
						}
						if(isset($_SESSION['REGISTER_DATA'])){
							unset($_SESSION['REGISTER_DATA']);
						}
					}
				}
				
				$pjListingModel = pjListingModel::factory();
				
				$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
							
				$city_arr = $pjListingModel->select('`address_city`')->groupBy('`address_city`')->orderBy("`address_city` asc")->findAll()->getData();
				
				$pjListingModel->reset()
					->join('pjUser', "t2.id=t1.owner_id", 'left')
					->join('pjType', "t3.id=t1.type_id", 'left')
					->join('pjMultiLang', "t4.model='pjCountry' AND t4.foreign_id=t1.country_id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left');
				$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
				$pjListingModel->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')");
				$country_arr = $pjListingModel->select('t4.content as country_title')->groupBy('`country_title`')->orderBy("`country_title` asc")->findAll()->getData();
				
				$location_arr = array();
				foreach($city_arr as $v)
				{
					if(!empty($v['address_city']))
					{
						$location_arr[] = $v['address_city'];
					}
				}
				foreach($country_arr as $v)
				{
					$location_arr[] = $v['country_title'];
				}
				
				$this->set('type_arr', $type_arr);				
				$this->set('location_arr', $location_arr);
			}
			
		}else{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionIndex");
		}
	}
	
	public function pjActionLogin()
	{
		if ($this->option_arr['o_allow_add_package'] == 'Yes')
		{
			
			$pjListingModel = pjListingModel::factory();
			
			$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
							->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
							->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
						
			$city_arr = $pjListingModel->select('`address_city`')->groupBy('`address_city`')->orderBy("`address_city` asc")->findAll()->getData();
			
			$pjListingModel->reset()
				->join('pjUser', "t2.id=t1.owner_id", 'left')
				->join('pjType', "t3.id=t1.type_id", 'left')
				->join('pjMultiLang', "t4.model='pjCountry' AND t4.foreign_id=t1.country_id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left');
			$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
			$pjListingModel->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')");
			$country_arr = $pjListingModel->select('t4.content as country_title')->groupBy('`country_title`')->orderBy("`country_title` asc")->findAll()->getData();
			
			$location_arr = array();
			foreach($city_arr as $v)
			{
				if(!empty($v['address_city']))
				{
					$location_arr[] = $v['address_city'];
				}
			}
			foreach($country_arr as $v)
			{
				$location_arr[] = $v['country_title'];
			}
			
			$this->set('type_arr', $type_arr);				
			$this->set('location_arr', $location_arr);
		}else{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionIndex");
		}
	}
	
	public function pjActionForgotPassword()
	{
		if ($this->option_arr['o_allow_add_package'] == 'Yes')
		{
			if (isset($_POST['forgot_password']))
			{
				$redirect_url = pjUtil::buildFrontUrl($_SERVER['PHP_SELF']. '?controller='.$_GET['controller'].'&action=pjActionForgotPassword', $_GET);
				
				set_time_limit(0);
				
				$err = array();
				
				if (!isset($_POST['forgot_email']))
				{
					$err[] = 9901;
				}
				if (isset($_POST['forgot_email']) && !pjValidation::pjActionNotEmpty($_POST['forgot_email']))
				{
					$err[] = 9906;
				}
				if (isset($_POST['forgot_email']) && !pjValidation::pjActionEmail($_POST['forgot_email']))
				{
					$err[] = 9912;
				}
				
				if (!empty($err))
				{
					unset($_SESSION['FORGOT_STATUS']);
					unset($_SESSION['FORGOT_DATA']);
					
					$_SESSION['FORGOT_STATUS']= $err;
					$_SESSION['FORGOT_DATA'] = $_POST;
					pjUtil::redirect($redirect_url."&err=9900");
				}
				
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->where('t1.email', $_POST['forgot_email'])->findAll()->getData();
				
				if (empty($arr) && count($arr) == 0)
				{
					unset($_SESSION['FORGOT_STATUS']);
					unset($_SESSION['FORGOT_DATA']);
					
					$_SESSION['FORGOT_STATUS'][]= 9997;
					$_SESSION['FORGOT_DATA'] = $_POST;
					pjUtil::redirect($redirect_url."&err=9900");
				}else{
					$email_data = array();				
								
					$email_default = pjNotificationModel::factory()->where('user_id', 1)->findAll()->getData();				
					if(count($email_default) > 0)
					{
						$email_data = $email_default[0];
					}
					if(!empty($email_data))
					{				
						$email_data['i18n'] = pjMultiLangModel::factory()->getMultiLang($email_data['id'], 'pjNotification');
						if(!empty($email_data['i18n'][$this->getLocaleId()]['forgot_subject']) && !empty($email_data['i18n'][$this->getLocaleId()]['forgot_message']))
						{				
							$subject = $email_data['i18n'][$this->getLocaleId()]['forgot_subject'];
							$message = str_replace(	array('{Password}'), 
													array($arr[0]['password']), 
													$email_data['i18n'][$this->getLocaleId()]['forgot_message']);
							$pjEmail = new pjEmail();
							if ($this->option_arr['o_send_email'] == 'smtp' && 
								$this->option_arr['o_smtp_host'] != '' && 
								$this->option_arr['o_smtp_port'] != '' &&
								$this->option_arr['o_smtp_user'] != '' &&
								$this->option_arr['o_smtp_pass'] != '')
							{
								$pjEmail
									->setTransport('smtp')
									->setSmtpHost($this->option_arr['o_smtp_host'])
									->setSmtpPort($this->option_arr['o_smtp_port'])
									->setSmtpUser($this->option_arr['o_smtp_user'])
									->setSmtpPass($this->option_arr['o_smtp_pass'])
									->setSender($this->option_arr['o_smtp_user'])
								;
							}
								
							$pjEmail
								->setFrom($this->getFromEmail($this->option_arr))
								->setTo($_POST['forgot_email'])
								->setSubject($subject)
								->send($message);
						}
					}
					
					pjUtil::redirect($redirect_url."&err=9999");
					exit;
				}
			}else{
				
				if(!isset($_GET['err']))
				{
					if(isset($_SESSION['FORGOT_STATUS']))
					{
						unset($_SESSION['FORGOT_STATUS']);
					}
					if(isset($_SESSION['FORGOT_DATA'])){
						unset($_SESSION['FORGOT_DATA']);
					}
				}else{
					if($_GET['err'] != 9900)
					{
						if(isset($_SESSION['FORGOT_STATUS']))
						{
							unset($_SESSION['FORGOT_STATUS']);
						}
						if(isset($_SESSION['FORGOT_DATA'])){
							unset($_SESSION['FORGOT_DATA']);
						}
					}
				}
				
				$pjListingModel = pjListingModel::factory();
				
				$type_arr = pjTypeModel::factory()->select('t1.*, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjType' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
								->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
							
				$city_arr = $pjListingModel->select('`address_city`')->groupBy('`address_city`')->orderBy("`address_city` asc")->findAll()->getData();
				
				$pjListingModel->reset()
					->join('pjUser', "t2.id=t1.owner_id", 'left')
					->join('pjType', "t3.id=t1.type_id", 'left')
					->join('pjMultiLang', "t4.model='pjCountry' AND t4.foreign_id=t1.country_id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left');
				$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
				$pjListingModel->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')");
				$country_arr = $pjListingModel->select('t4.content as country_title')->groupBy('`country_title`')->orderBy("`country_title` asc")->findAll()->getData();
				
				$location_arr = array();
				foreach($city_arr as $v)
				{
					if(!empty($v['address_city']))
					{
						$location_arr[] = $v['address_city'];
					}
				}
				foreach($country_arr as $v)
				{
					$location_arr[] = $v['country_title'];
				}
				
				$this->set('type_arr', $type_arr);				
				$this->set('location_arr', $location_arr);
			}
		}else{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionIndex");
		}
	}
	
	private function pjActionGetCalendar($priceBasedOn=1)
	{
		$months = __('months', true);
		ksort($months);
		$dayNames = __('day_names', true);
		ksort($dayNames);
		
		return pjABCalendar::factory()
			->setStartDay(1)
			->setPriceBasedOn($priceBasedOn)
			->setMonthNames(array_values($months))
			->setDayNames($dayNames);
	}
	
	public function pjActionConfirmPayment()
	{
		$this->setAjax(true);
		
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			exit;
		}
		
		$pjPaymentModel = pjPaymentModel::factory();
		$pjListingModel = pjListingModel::factory();
		$listing_arr = $pjListingModel->find($_POST['custom'])->getData();
		$payment_arr = $pjPaymentModel->where('t1.listing_id', $_POST['custom'])->orderBy('t1.date_to DESC')->limit(1)->findAll()->getData();
		$period_arr = pjPeriodModel::factory()->findAll()->getData();
		$date_from = date("Y-m-d");
		if (count($payment_arr) === 1)
		{
			$date_from = $payment_arr[0]['date_to'];
		}
		
		$period = $price = NULL;
		foreach ($period_arr as $_period)
		{
			if ((float) $_period['price'] == (float) $_POST['mc_gross'])
			{
				$period = (int) $_period['days'];
				$price = (float) $_period['price'];
				break;
			}
		}
		list($year, $month, $day) = explode("-", $date_from);
		$date_to = date("Y-m-d", mktime(0, 0, 0, $month, $day + $period, $year));
		
		$params = array(
			'txn_id' => @$booking_arr['txn_id'],
			'paypal_address' => $this->option_arr['o_paypal_address'],
			'deposit' => $price,
			'currency' => $this->option_arr['o_currency'],
			'key' => md5($this->option_arr['private_key'] . PJ_SALT)
		);

		$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
		if ($response !== FALSE && isset($response['status']) && $response['status'] === 'OK')
		{
			$this->log('pjPaypal > pjActionConfirm > status == OK');
			$pjPaymentModel
				->reset()
				->setAttributes(array(
					'listing_id' => $listing_arr['id'],
					'date_from' => $date_from,
					'date_to' => $date_to,
					'txn_id' => $response['transaction_id'],
					'price' => $price
				))
				->insert();
			$current = time();
			if (!empty($listing_arr['expire']) && $listing_arr['expire'] != '0000-00-00')
			{
				$current = strtotime($listing_arr['expire']);
			}
			pjListingModel::factory()
				->set('id', $listing_arr['id'])
				->modify(array(
					'last_extend' => 'paid',
					'status' => 'E',
					'expire' => date("Y-m-d", $current + $period * 86400)
				));
			$this->log('Payment confirmed');
		} elseif (!$response) {
			$this->log('Authorization failed');
		} else {
			$this->log('Payment not confirmed');
		}
		exit;
	}
	
	public function getFeaturedListings($option_arr, $locale_id)
	{
		$pjListingModel = pjListingModel::factory()
			->join('pjUser', "t2.id=t1.owner_id", 'left')
			->join('pjType', "t3.id=t1.type_id", 'left')
			->join('pjMultiLang', "t4.model='pjType' AND t4.foreign_id=t3.id AND t4.field='name' AND t4.locale='".$locale_id."'", 'left')
			->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='title' AND t5.locale='".$locale_id."'", 'left')
			->join('pjMultiLang', "t6.model='pjListing' AND t6.foreign_id=t1.id AND t6.field='description' AND t6.locale='".$locale_id."'", 'left')
			->join('pjMultiLang', "t7.model='pjCountry' AND t7.foreign_id=t1.country_id AND t7.field='name' AND t7.locale='".$locale_id."'", 'left');
		
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))")->where('t1.is_featured', 'T');
		$pjListingModel->where("((t2.status = 'T' OR t2.status IS NULL) AND t3.status='T')");
		
		$sorting = 't1.created DESC';
		$cnt = $pjListingModel->findCount()->getData();
		
		if($cnt > $option_arr['o_featured_properties'])
		{
			$sorting = 'RAND()';
		}
		$pjListingModel->limit($option_arr['o_featured_properties'], 0);
		
		$arr = $pjListingModel
			->select(sprintf("t1.*, t5.content as listing_title, ,t6.content as listing_description, t7.content as country_title, t4.content AS type_title, t2.name AS owner_name,
				(SELECT `medium_path` FROM `%1\$s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `image`,
				(SELECT MIN(`price`) FROM `%2\$s` AS t8 WHERE t8.listing_id = t1.id GROUP BY `listing_id` LIMIT 1) AS `min`,
				(SELECT MAX(`price`) FROM `%2\$s` AS t9 WHERE t9.listing_id = t1.id GROUP BY `listing_id` LIMIT 1) AS `max`,
				(SELECT AVG(t11.rating) FROM `%3\$s` AS t11 WHERE t11.listing_id = t1.id AND t11.status = 'Confirmed' AND t11.rating IS NOT NULL) AS `avg_rating`,
				(SELECT COUNT(*) FROM `%3\$s` AS t12 WHERE t12.listing_id = t1.id AND t12.status = 'Confirmed' AND t12.rating IS NOT NULL LIMIT 1) AS `number_of_comments`",
				pjGalleryModel::factory()->getTable(), pjPriceModel::factory()->getTable(), pjCommentModel::factory()->getTable()
			))
			->orderBy($sorting)
			->findAll()
			->getData();
		
		return $arr;
	}
	
	private function getOwnerOptions($owner_id)
	{
		$option_arr = pjOptionModel::factory()->getPairs($owner_id);
		return $option_arr;
	}
}
?>