<?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() && $this->option_arr['o_allow_add_package'] == 'Yes'))
		{
			if (isset($_POST['listing_create']))
			{
				pjAppController::validateCsrfToken();
				$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['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']))
					{
				pjAppController::validateCsrfToken();
						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 . 'chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . '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']))
			{
				pjAppController::validateCsrfToken();
				$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)
					{
						pjMultiLangModel::factory()->where('model', 'pjPrice')->where('foreign_id', $arr[0]['id'])->eraseAll();
						$response['code'] = 200;
					}
				}
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
		
	public function pjActionDeleteListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjAppController::validateCsrfToken();
			$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 = pjPriceModel::factory();
				$price_id_arr = $pjPriceModel->where('listing_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
				if(!empty($price_id_arr))
				{
					pjMultiLangModel::factory()->where('model', 'pjPrice')->whereIn('foreign_id', $price_id_arr)->eraseAll();
				}
				$pjPriceModel->reset()->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())
		{
			pjAppController::validateCsrfToken();
			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();
				
				$pjPriceModel = pjPriceModel::factory();
				$price_id_arr = $pjPriceModel->whereIn('listing_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
				if(!empty($price_id_arr))
				{
					pjMultiLangModel::factory()->where('model', 'pjPrice')->whereIn('foreign_id', $price_id_arr)->eraseAll();
				}
				$pjPriceModel->reset()->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')
				->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');
			
			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 = pjObject::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 = pjObject::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']) && $_GET['is_featured'] != '')
			{
				$pjListingModel->where('t1.is_featured', $_GET['is_featured']);
			}
			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 = pjObject::escapeString($_GET['listing_refid']);
				$pjListingModel->where('t1.listing_refid LIKE', "%$q%");
			}
			if (isset($_GET['address_state']))
			{
				if($_GET['address_state'] != '')
				{
					$state = pjObject::escapeString($_GET['address_state']);
					$pjListingModel->where("t1.address_state LIKE '%$state%'");
				}
			}
			if (isset($_GET['address_city']))
			{
				if($_GET['address_city'] != '')
				{
					$city = pjObject::escapeString($_GET['address_city']);
					$pjListingModel->where("t1.address_city LIKE '%$city%'");
				}
			}
			
			$column = 'id';
			$direction = 'DESC';
			$allowed_columns = array('t1.id', 'id', 'listing_title', 't1.status', 'created', 'price', 'is_featured', 'type_title');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')) && in_array($_GET['column'], $allowed_columns))
			{
				$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,
				(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, $this->option_arr);
			$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, $option_arr)
	{
		$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);

		$api_key_str = isset($option_arr['o_google_map_api']) && !empty($option_arr['o_google_map_api']) ? 'key=' . $option_arr['o_google_map_api'] . '&' : '';
		$gfile = "https://maps.googleapis.com/maps/api/geocode/json?".$api_key_str."address=$_address";
		$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() && $this->option_arr['o_allow_add_package'] == 'Yes'))
		{
			$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')
				->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')
				->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 . 'chosen/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . '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() && $this->option_arr['o_allow_add_package'] == 'Yes'))
		{
			if (isset($_POST['extend']))
			{
				pjAppController::validateCsrfToken();
				$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() && $this->option_arr['o_allow_add_package'] == 'Yes'))
		{
			$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')
				->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());
			
			$this->appendJs('pjAdminListings.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	
	public function pjActionStatusListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjAppController::validateCsrfToken();
			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())
		{
			pjAppController::validateCsrfToken();
			$pjListingModel = pjListingModel::factory();
			if (!in_array($_POST['column'], $pjListingModel->i18n))
			{
				if (in_array($_POST['column'], array('expire')))
				{
					$_POST['value'] = pjUtil::formatDate($_POST['value'], $this->option_arr['o_date_format']);
				}
				$value = $_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() && $this->option_arr['o_allow_add_package'] == 'Yes'))
		{
			$ListingFeatureModel = new pjListingFeatureModel();
			$pjListingAvailabilityModel = new pjListingAvailabilityModel();
				
			if (isset($_POST['listing_update']))
			{
				pjAppController::validateCsrfToken();
				$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, $this->option_arr);
				}
				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';
				}
								
				$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']))
				{
				pjAppController::validateCsrfToken();
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjListing', 'data');
				}
				
				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();
				$pjMultiLangModel = pjMultiLangModel::factory();
				
				$price_id_arr = $PriceModel->where('listing_id', $_POST['id'])->findAll()->getDataPair(null, 'id');
				$PriceModel->reset()->where('listing_id', $_POST['id'])->eraseAll();
				
				if(!empty($price_id_arr))
				{
					$pjMultiLangModel->where('model', 'pjPrice')->whereIn('foreign_id', $price_id_arr)->eraseAll();
				}
				
				if (isset($_POST['price']))
				{
				pjAppController::validateCsrfToken();
					$data = array();
					$data['id'] = NULL;
					$data['listing_id'] = $_POST['id'];
					foreach ($_POST['price'] as $i => $price)
					{
						if (!empty($_POST['date_from'][$i]) && !empty($_POST['date_to'][$i]) && !empty($_POST['price_type'][$i]) &&  (float) $_POST['price'][$i] > 0)
						{
							$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];
							$price_id = $PriceModel->reset()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
							if ($price_id !== false && (int) $price_id > 0)
							{
								foreach ($_POST['i18n'] as $locale => $locale_arr)
								{
									foreach ($locale_arr as $field => $content)
									{
										if(is_array($content))
										{
											$pjMultiLangModel->reset()->setAttributes(array(
													'foreign_id' => $price_id,
													'model' => 'pjPrice',
													'locale' => $locale,
													'field' => $field,
													'content' => $content[$i],
													'source' => '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')
					->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')
					->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')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				$this->set('country_arr', pjSanitize::clean($country_arr));
				
				$price_arr = pjPriceModel::factory()->where('listing_id', $arr['id'])->orderBy('t1.date_from ASC')->findAll()->getData();
				foreach($price_arr as $k => $v)
				{
					$price_arr[$k]['i18n'] = pjMultiLangModel::factory()->getMultiLang($v['id'], 'pjPrice');
				}
				
				$this->set('price_arr', $price_arr);
				
				$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')
					->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']; 
				}
				$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('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tinymce/');
				
				# Gallery plugin
				$this->appendCss('pj-gallery.css', pjObject::getConstant('pjGallery', 'PLUGIN_CSS_PATH'));
				$this->appendJsFromPlugin('ajaxupload.js', 'ajaxupload', 'pjGallery');
				$this->appendJs('jquery.gallery.js', pjObject::getConstant('pjGallery', 'PLUGIN_JS_PATH'));
				
				$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'chosen/');
				$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . '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);
		}
	}
	
	public function pjActionGetPaymentForm()
	{
	    $this->setAjax(true);
	    
	    if ($this->isXHR())
	    {
	        $listing_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')
	        ->find($_GET['listing_id'])->getData();
	        
	        $period_arr = pjPeriodModel::factory()->find($_GET['period_id'])->getData();
	        $this->set('params', array(
	            'name' => 'vpPaypal',
	            'id' => 'vpPaypal',
	            'business' => $this->option_arr['o_paypal_address'],
	            'client_id' => $this->option_arr['o_paypal_client_id'],
	            'client_secret' => $this->option_arr['o_paypal_client_secret'],
	            'item_name' => __('listing_payment_period', true) .'(#'.$period_arr['id'].'): '. $period_arr['days'] .' '. __('o_days', true),
	            'custom' => $listing_arr['id'].'-'.$period_arr['id'],
	            'amount' => number_format($period_arr['price'], 2, '.', ''),
	            'currency_code' => $this->option_arr['o_currency'],
	            'return' => PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex",
	            'failure_url' => $this->option_arr['o_paypal_cancel_url'],
	            'notify_url' => PJ_INSTALL_URL . "index.php?controller=pjListings&action=pjActionConfirmPayment",
	            'target' => '_self',
	            'charset' => 'utf-8'
	        ));
	        $this->set('listing_arr', $listing_arr);
	        $this->set('period_arr', $period_arr);
	    }
	}
}
?>