<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminListings extends pjAdmin
{
	private $imageFiles = array('small_path', 'mini_path', 'medium_path', 'large_path', 'source_path');
	
	public function pjActionCheckRefId()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() && isset($_GET['listing_refid']))
		{
			$pjListingModel = pjListingModel::factory();
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjListingModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjListingModel->where('t1.listing_refid', $_GET['listing_refid'])->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			if (isset($_POST['listing_create']))
			{
				$data = array();
				if (isset($_POST['expire']) && $_POST['status'] == 'E')
				{
					$data['expire'] = pjUtil::formatDate($_POST['expire'], $this->option_arr['o_date_format']);
				}else{
					unset($_POST['expire']);
				}
				$data['last_extend'] = 'free';
				if ($this->isOwner())
				{
					$data['owner_id'] = $this->getUserId();
					$data['status'] = 'F';
					$data['is_featured'] = 'F';
					$data['is_best_deal'] = 0;
					$data['added_by'] = 'owner';
					$data['expire'] = date("Y-m-d", strtotime("-1 day"));
				}
				
				$data = array_merge($_POST, $data);
				
				$pjListingModel = pjListingModel::factory();
				if (!$pjListingModel->validates($data))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=1");
				}
				
				$id = $pjListingModel->setAttributes($data)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AL03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjListing');
					}
				} else {
					$err = 'AL04';
				}
				
				if ($id !== false && (int) $id > 0)
				{
					
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $id . "&tab_id=tabs-1");
					
				} else {
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=1");
				}
			}

			if ($this->isOwner())
			{
				$this->set('period_arr', pjPeriodModel::factory()->orderBy('t1.days ASC')->findAll()->getData());
			}
			
			$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()."'")
				->where('t1.status', 'T')->orderBy('name ASC')->findAll()->getData();
			$this->set('type_arr', pjSanitize::clean($type_arr));
	
			$user_arr = pjUserModel::factory()->where('role_id', 3)->findAll()->getData();
			$this->set('user_arr', pjSanitize::clean($user_arr));
			
			$this->appendJs('chosen.jquery.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				
			$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
			$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdminListings.js');
		} else {
			$this->set('status', 2);
		}
	}
		
	public function pjActionDeletePrice()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array('code' => 100);
			if (isset($_POST['id']))
			{
				$pjPriceModel = pjPriceModel::factory();
				$arr = $pjPriceModel
					->select('t1.*, t2.owner_id')
					->join('pjListing', 't2.id=t1.listing_id', 'inner')
					->where('t1.id', $_POST['id'])
					->limit(1)
					->findAll()
					->getData();
				if (count($arr) === 0)
				{
					$response['code'] = 101;
				} elseif ($this->isOwner() && $arr[0]['owner_id'] != $this->getUserId()) {
					$response['code'] = 102;
				} else {
					$response['code'] = 103;
					if ($pjPriceModel->reset()->setAttributes(array('id' => $arr[0]['id']))->erase()->getAffectedRows() == 1)
					{
						$response['code'] = 200;
					}
				}
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
		
	public function pjActionDeleteListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjListingModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjListing')->where('foreign_id', $_GET['id'])->eraseAll();
				
				
				pjListingFeatureModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				pjListingAvailabilityModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				pjEnquiryModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				pjPriceModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				
				$pjGalleryModel = pjGalleryModel::factory();
				$arr = $pjGalleryModel->where('foreign_id', $_GET['id'])->findAll()->getData();
				if (count($arr) > 0)
				{
					foreach ($arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
					$pjGalleryModel->eraseAll();
				}
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteListingBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjListingModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
				pjMultiLangModel::factory()->where('model', 'pjListing')->whereIn('foreign_id', $_POST['record'])->eraseAll();
				
				pjListingFeatureModel::factory()->whereIn('listing_id', $_POST['record'])->eraseAll();
				pjListingAvailabilityModel::factory()->whereIn('listing_id', $_POST['record'])->eraseAll();
				$arr = pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->findAll()->getData();
				if (count($arr) > 0)
				{
					pjGalleryModel::factory()->whereIn('foreign_id', $_POST['record'])->eraseAll();
					foreach ($arr as $item)
					{
						foreach ($this->imageFiles as $file)
						{
							@clearstatcache();
							if (!empty($item[$file]) && is_file($item[$file]))
							{
								@unlink($item[$file]);
							}
						}
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionGetLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_GET['locale']) && (int) $_GET['locale'] > 0)
			{
				pjAppController::setFields($_GET['locale']);
				
				$this->set('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='".$_GET['locale']."'", 'inner')
					->where('t1.status', 'T')->orderBy('name ASC')->findAll()->getData()
				);
			}
		}
	}
	
	public function pjActionExpireListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjListingModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('expire' => ':DATE_ADD(`expire`, INTERVAL 30 DAY)'));
			} elseif (isset($_GET['id']) && (int) $_GET['id'] > 0) {
				pjListingModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array('expire' => ':DATE_ADD(`expire`, INTERVAL 30 DAY)'));
			}
		}
		exit;
	}
	
	public function pjActionGetListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjListingModel = pjListingModel::factory()
				->join('pjUser', 't2.id=t1.owner_id', 'left outer')
				->join('pjType', 't3.id=t1.type_id', 'left outer')
				->join('pjMultiLang', "t4.model='pjType' AND t4.foreign_id=t3.id AND t4.field='name' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='title' AND t5.locale='".$this->getLocaleId()."'", 'left outer');
			
			if (isset($_GET['status']) && !empty($_GET['status']))
			{
				if($_GET['status'] == 'T')
				{
					$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
				}else{
					$pjListingModel->where("(t1.status = 'F' OR (t1.status = 'E' AND t1.expire < CURDATE()))");
				}
			}
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjListingModel->escapeString($_GET['q']);
				$pjListingModel->where('t1.listing_refid LIKE', "%$q%");
				$pjListingModel->orWhere("t1.id IN (SELECT t8.foreign_id FROM `".pjMultiLangModel::factory()->getTable()."` AS t8 WHERE t8.model='pjListing' AND t8.locale='".$this->getLocaleId()."' AND (t8.`field` = 'title') AND t8.`content` LIKE '%$q%')");
			}
			if (isset($_GET['keyword']))
			{
				if($_GET['keyword'] != '')
				{
					$keyword = $pjListingModel->escapeString($_GET['keyword']);
					$pjListingModel->where("t1.id IN (SELECT t8.foreign_id FROM `".pjMultiLangModel::factory()->getTable()."` AS t8 WHERE t8.model='pjListing' AND t8.locale='".$this->getLocaleId()."' AND (t8.`field` = 'description' OR t8.`field` = 'title') AND t8.`content` LIKE '%$keyword%')");
				}
			}
			if (isset($_GET['is_featured']) && in_array($_GET['is_featured'], array('T', 'F')))
			{
				$pjListingModel->where('t1.is_featured', $_GET['is_featured']);
			}
			if (isset($_GET['is_best_deal']) && in_array($_GET['is_best_deal'], array('1,2')))
			{
				$pjListingModel->where("t1.is_best_deal != '0'");
			}
			if ($this->isOwner())
			{
				$pjListingModel->where('t1.owner_id', $this->getUserId());
			} else {
				if (isset($_GET['owner_id']) && (int) $_GET['owner_id'] > 0)
				{
					$pjListingModel->where('t1.owner_id', $_GET['owner_id']);
				}
			}
			if (isset($_GET['type_id']) && (int) $_GET['type_id'] > 0)
			{
				$pjListingModel->where('t1.type_id', $_GET['type_id']);
			}
			if (isset($_GET['country_id']) && (int) $_GET['country_id'] > 0)
			{
				$pjListingModel->where('t1.country_id', $_GET['country_id']);
			}
			if (isset($_GET['listing_refid']) && !empty($_GET['listing_refid']))
			{
				$q = $pjListingModel->escapeString($_GET['listing_refid']);
				$pjListingModel->where('t1.listing_refid LIKE', "%$q%");
			}
			if (isset($_GET['address_state']))
			{
				if($_GET['address_state'] != '')
				{
					$state = $pjListingModel->escapeString($_GET['address_state']);
					$pjListingModel->where("t1.address_state LIKE '%$state%'");
				}
			}
			if (isset($_GET['address_city']))
			{
				if($_GET['address_city'] != '')
				{
					$city = $pjListingModel->escapeString($_GET['address_city']);
					$pjListingModel->where("t1.address_city LIKE '%$city%'");
				}
			}
			
			$column = 'id';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}
			
			$total = $pjListingModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}
			$data = array();
			$arr = $pjListingModel->select(sprintf('t1.id, t1.listing_refid, t1.expire, t1.status,
				t1.type_id, t1.added_by, t4.content AS `type_title`,
				t1.owner_id, t2.name AS owner_name, t5.content AS `listing_title`,
				(SELECT `small_path` FROM `%s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `image`', pjGalleryModel::factory()->getTable()))
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();

			foreach($arr as $k => $v)
			{
				$v['is_expired'] = 0;
				if($v['expire'] < date('Y-m-d'))
				{
					$v['is_expired'] = 1;
				}
				$v['expire'] = pjUtil::formatDate(date('Y-m-d', strtotime($v['expire'])), 'Y-m-d', $this->option_arr['o_date_format']);
				
				$data[$k] = $v;
			}
				
			$data = pjSanitize::clean($data);
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionGetGeocode()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$geo = pjAdminListings::pjActionGeocode($_POST);
			$response = array('code' => 100);
			if (isset($geo['lat']) && !is_array($geo['lat']))
			{
				$response = $geo;
				$response['code'] = 200;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	private static function pjActionGeocode($post)
	{
		$address = array();
		$address[] = $post['address_postcode'];
		$address[] = $post['address_content'];
		$address[] = $post['address_city'];
		$address[] = $post['address_state'];

		foreach ($address as $key => $value)
		{
			$tmp = preg_replace('/\s+/', '+', $value);
			$address[$key] = $tmp;
		}
		$_address = join(",+", $address);
							
		//http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false
		$gfile = "http://maps.googleapis.com/maps/api/geocode/json?address=$_address&sensor=false";
		$Http = new pjHttp();
		$response = $Http->request($gfile)->getResponse();

		$geoObj = pjAppController::jsonDecode($response);
		
		$data = array();
		$geoArr = (array) $geoObj;
		if ($geoArr['status'] == 'OK')
		{
			$geoArr['results'][0] = (array) $geoArr['results'][0];
			$geoArr['results'][0]['geometry'] = (array) $geoArr['results'][0]['geometry'];
			$geoArr['results'][0]['geometry']['location'] = (array) $geoArr['results'][0]['geometry']['location'];
			
			$data['lat'] = $geoArr['results'][0]['geometry']['location']['lat'];
			$data['lng'] = $geoArr['results'][0]['geometry']['location']['lng'];
		} else {
			$data['lat'] = NULL;
			$data['lng'] = NULL;
		}
		return $data;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$user_arr = pjUserModel::factory()->where('role_id', 3)->findAll()->getData();
			$this->set('user_arr', pjSanitize::clean($user_arr));
			
			$country_arr = pjCountryModel::factory()->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
			$this->set('country_arr', pjSanitize::clean($country_arr));
			
			$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 outer')
				->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
			$this->set('type_arr', pjSanitize::clean($type_arr));
			
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
			
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminListings.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExtend()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			if (isset($_POST['extend']))
			{
				$pjListingModel = pjListingModel::factory();
			
				$arr = $pjListingModel->find($_POST['id'])->getData();
				$period_arr = pjPeriodModel::factory()->find($_POST['period_id'])->getData();

				if (count($arr) > 0 && count($period_arr) > 0)
				{
					$current = time();
					if ($arr['last_extend'] == 'paid' && !empty($arr['expire']) && $arr['expire'] != '0000-00-00')
					{
						$current = strtotime($arr['expire']);
					}
					
					$pjListingModel->set('id', $arr['id'])->modify(array(
						'status' => 'E',
						'last_extend' => 'free',
						'expire' => date("Y-m-d", $current + (int) $period_arr['days'] * 86400)
					));
				}
			}
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL10");
			
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionPayment()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$arr = pjListingModel::factory()
				->select('t1.*, t2.content AS listing_title')
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->find($_GET['id'])->getData();
				
			if (count($arr) === 0)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL08");
			} elseif ($this->isOwner() && $arr['owner_id'] != $this->getUserId()) {
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL09");
			}
			$this->set('arr', $arr);
			$this->set('period_arr', pjPeriodModel::factory()->orderBy('t1.days ASC')->findAll()->getData());
		} else {
			$this->set('status', 2);
		}
	}
	
	
	public function pjActionStatusListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0 && isset($_GET['status']) && in_array($_GET['status'], array('T', 'F', 'E')))
			{
				pjListingModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('status' => $_GET['status']));
			}
		}
		exit;
	}
	
	public function pjActionSaveListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjListingModel = pjListingModel::factory();
			if (!in_array($_POST['column'], $pjListingModel->getI18n()))
			{
				if (in_array($_POST['column'], array('expire')))
				{
					$_POST['value'] = pjUtil::formatDate($_POST['value'], $this->option_arr['o_date_format']);
				}
				$value = $_POST['value'];
				//$value = pjSanitize::clean($_POST['value']);
				$pjListingModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $value));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjListing');
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
			
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$ListingFeatureModel = new pjListingFeatureModel();
			$pjListingAvailabilityModel = new pjListingAvailabilityModel();
				
			if (isset($_POST['listing_update']))
			{
				$arr = pjListingModel::factory()->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL08");
				}

				$err = NULL;
				$data = array();
				
				if ($this->isOwner())
				{
					if ($arr['owner_id'] != $this->getUserId())
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL09");
					}
					unset($_POST['owner_id']);
					$data['owner_id'] = $arr['owner_id'];
					$data['expire'] = $arr['expire'];
					$data['status'] = $arr['status'];
				}
				
				$data['modified'] = date("Y-m-d H:i:s");
				if (!$this->isOwner())
				{
					if($_POST['status'] == 'E')
					{
						$data['expire'] = pjUtil::formatDate($_POST['expire'], $this->option_arr['o_date_format']);
					}else{
						$data['expire'] = ":NULL";
					}
				}
				if($_POST['outbound_departs'] != '')
				{
					list($_outbound_departs_date, $_outbound_departs_time) = explode(" ", $_POST['outbound_departs']);
					$_POST['outbound_departs'] = pjUtil::formatDate($_outbound_departs_date, $this->option_arr['o_date_format']) . ' ' . $_outbound_departs_time;
				}
				if($_POST['outbound_arrives'] != '')
				{
					list($_outbound_arrives_date, $_outbound_arrives_time) = explode(" ", $_POST['outbound_arrives']);
					$_POST['outbound_arrives'] = pjUtil::formatDate($_outbound_arrives_date, $this->option_arr['o_date_format']) . ' ' . $_outbound_arrives_time;
				}
				if($_POST['inbound_departs'] != '')
				{
					list($_inbound_departs_date, $_inbound_departs_time) = explode(" ", $_POST['inbound_departs']);
					$_POST['inbound_departs'] = pjUtil::formatDate($_inbound_departs_date, $this->option_arr['o_date_format']) . ' ' . $_inbound_departs_time;
				}
				if($_POST['inbound_arrives'] != '')
				{
					list($_inbound_arrives_date, $_inbound_arrives_time) = explode(" ", $_POST['inbound_arrives']);
					$_POST['inbound_arrives'] = pjUtil::formatDate($_inbound_arrives_date, $this->option_arr['o_date_format']) . ' ' . $_inbound_arrives_time;
				}
				
				$geo = array();
				if (!isset($_POST['lat']) || empty($_POST['lat']) || !isset($_POST['lng']) || empty($_POST['lng']))
				{
					$geo = pjAdminListings::pjActionGeocode($_POST);
				}
				if (isset($_POST['listing_season']) && is_array($_POST['listing_season']) && count($_POST['listing_season']) > 0)
				{
					$data['listing_season'] = implode('|', $_POST['listing_season']);
					unset($_POST['listing_season']);
				}else{
					$data['listing_season'] = ':NULL';
				}
				if(empty($_POST['listing_nights']))
				{
					unset($_POST['listing_nights']);
				}
								
				$pjListingModel = pjListingModel::factory();
				$post = array_merge($_POST, $data, $geo);
				
				if (!$pjListingModel->validates($post))
				{
					pjUtil::redirect(sprintf("%s?controller=pjAdminListings&action=pjActionUpdate&id=%u&locale=%u&tab_id=%s&err=AL02", $_SERVER['PHP_SELF'], $_POST['id'], $_POST['locale'], $_POST['tab_id']));
				}
				
				$pjListingModel->set('id', $_POST['id'])->modify($post);

				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjListing');
				}
				
				pjListingFeatureModel::factory()->where('listing_id', $_POST['id'])->eraseAll();
				if (isset($_POST['feature']) && is_array($_POST['feature']) && count($_POST['feature']) > 0)
				{
					$ListingFeatureModel->begin();
					foreach ($_POST['feature'] as $feature_id)
					{
						$ListingFeatureModel->setAttributes(array(
							'listing_id' => $_POST['id'],
							'feature_id' => $feature_id
						))->insert();
					}
					$ListingFeatureModel->commit();
				}
				
				$PriceModel = pjPriceModel::factory();
				
				$PriceModel->where('listing_id', $_POST['id'])->eraseAll();
				if (isset($_POST['price']))
				{
					$data = array();
					$data['id'] = NULL;
					$data['listing_id'] = $_POST['id'];
					foreach ($_POST['price'] as $i => $price)
					{
						if (!empty($_POST['price_title'][$i]) && !empty($_POST['date_from'][$i]) && !empty($_POST['date_to'][$i]) && !empty($_POST['price_type'][$i]) &&  (float) $_POST['price'][$i] > 0)
						{
							$data['price_title'] = $_POST['price_title'][$i];
							$data['date_from'] = pjUtil::formatDate($_POST['date_from'][$i], $this->option_arr['o_date_format']);
							$data['date_to'] = pjUtil::formatDate($_POST['date_to'][$i], $this->option_arr['o_date_format']);
							$data['price_type'] = $_POST['price_type'][$i];
							$data['price'] = $_POST['price'][$i];
							$PriceModel->reset()->setAttributes(array_merge($_POST, $data))->insert();
						}
					}
				}
				$err = "AL01";
				pjUtil::redirect(sprintf("%s?controller=pjAdminListings&action=pjActionUpdate&id=%u&locale=%u&tab_id=%s&err=%s", $_SERVER['PHP_SELF'], $_POST['id'], $_POST['locale'], $_POST['tab_id'], $err));
				
			} else {
				$arr = pjListingModel::factory()
					->select(sprintf("t1.*, (SELECT COUNT(*) FROM `%s` WHERE `listing_id` = t1.id LIMIT 1) AS `enquiries`", pjEnquiryModel::factory()->getTable()))
					->find($_GET['id'])->getData();
				
				if (count($arr) === 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL08");
				}
				if ($this->isOwner() && $arr['owner_id'] != $this->getUserId())
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL09");
				}
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjListing');
				$this->set('arr', $arr);
				
				$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 outer')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('type_arr', pjSanitize::clean($type_arr));
				
				$this->set('gallery_arr', pjGalleryModel::factory()->where('foreign_id', $arr['id'])->findAll()->getData());
				
				$feature_arr = pjFeatureModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjFeature' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('feature_arr', pjSanitize::clean($feature_arr));
					
				$this->set('listing_feature_arr', pjListingFeatureModel::factory()->where('t1.listing_id', $arr['id'])->findAll()->getDataPair(NULL, 'feature_id'));
				
				$country_arr = pjCountryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('country_arr', pjSanitize::clean($country_arr));
				
				$this->set('price_arr', pjPriceModel::factory()->where('listing_id', $arr['id'])->orderBy('t1.date_from ASC')->findAll()->getData());
				
				$user_arr = pjUserModel::factory()->where('role_id', 3)->findAll()->getData();
				$this->set('user_arr', pjSanitize::clean($user_arr));
				
				$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file')
					->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
					->where('t2.file IS NOT NULL')
					->orderBy('t1.sort ASC')->findAll()->getData();
				
				$lp_arr = array();
				foreach ($locale_arr as $item)
				{
					$lp_arr[$item['id']."_"] = $item['file']; //Hack for jquery $.extend, to prevent (re)order of numeric keys in object
				}
				$this->set('lp_arr', $locale_arr);
				$this->set('locale_str', pjAppController::jsonEncode($lp_arr));
			
				# jQuery Fancybox
				$this->appendJs('jquery.fancybox.pack.js', PJ_THIRD_PARTY_PATH . 'fancybox/js/');
				$this->appendCss('jquery.fancybox.css', PJ_THIRD_PARTY_PATH . 'fancybox/css/');
				
				# Timepicker
				$this->appendJs('jquery-ui-sliderAccess.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendJs('jquery-ui-timepicker-addon.js', PJ_THIRD_PARTY_PATH . 'timepicker/');
				$this->appendCss('jquery-ui-timepicker-addon.css', PJ_THIRD_PARTY_PATH . 'timepicker/');
				
				# TinyMCE
				$this->appendJs('tiny_mce.js', PJ_THIRD_PARTY_PATH . 'tiny_mce/');
				
				# Gallery plugin
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJs('ajaxupload.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/chosen/');
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('jquery.multilang.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
				$this->appendJs('jquery.tipsy.js', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendCss('jquery.tipsy.css', PJ_THIRD_PARTY_PATH . 'tipsy/');
				$this->appendJs('pjAdminListings.js');
				$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>