<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminListings extends pjAdmin
{
	private $imageFiles = array('small_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 pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
					
			$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('category_arr', $category_arr);		
			$this->set('country_arr', $country_arr);
					
			$owner_arr = pjUserModel::factory()->orderBy('t1.name ASC')->findAll()->getData();
			$this->set('owner_arr', pjSanitize::clean($owner_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');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjListingModel = pjListingModel::factory()
				->join('pjUser', 't2.id=t1.owner_id', 'left outer')
				->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t4.model='pjListing' AND t4.foreign_id=t1.id AND t4.field='description' AND t4.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 ($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['q']) && !empty($_GET['q']))
			{
				$pjListingModel->where(sprintf("(t1.listing_refid LIKE '%%%1\$s%%' OR t3.content LIKE '%%%1\$s%%' OR t4.content LIKE '%%%1\$s%%' OR t2.name LIKE '%%%1\$s%%')", pjObject::escapeString($_GET['q'])));
			}
			
			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['keyword']))
			{
				if($_GET['keyword'] != '')
				{
					$keyword = pjObject::escapeString($_GET['keyword']);
					$pjListingModel->where(sprintf("(t3.content LIKE '%%%1\$s%%')", pjObject::escapeString($keyword)));
				}
			}
			if (isset($_GET['category_id']) && !empty($_GET['category_id']))
			{
				$pjListingModel->where("(t1.id IN(SELECT TLC.listing_id FROM `".pjListingCategoryModel::factory()->getTable()."` AS TLC WHERE TLC.category_id = ".$_GET['category_id']."))");
			}
			if (isset($_GET['country_id']) && !empty($_GET['country_id']))
			{
				$pjListingModel->where('t1.country_id', $_GET['country_id']);
			}
			if (isset($_GET['address_city']) && !empty($_GET['address_city']))
			{
				$q = pjObject::escapeString($_GET['address_city']);
				$pjListingModel->where('t1.address_city LIKE', "%$q%");
			}
			if (isset($_GET['address_state']) && !empty($_GET['address_state']))
			{
				$q = pjObject::escapeString($_GET['address_state']);
				$pjListingModel->where('t1.address_state LIKE', "%$q%");
			}
						
			$column = 'id';
			$direction = 'DESC';
			$allowed_columns = array('t1.id', 'title', 'listing_refid', 'status', 'expire', 'created', 'category_name');
			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 = $pjListingModel->select(sprintf('t1.id, t1.listing_refid, t1.expire, t1.status, 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($data as $k => $v){
				if($v['status'] == 'T')
				{
					$v['expire'] = __('lblNever', true);
					
				}else if($v['status'] == 'F'){
					$v['expire'] = '';
				}else{
					if($v['expire'] < date('Y-m-d'))
					{
						$v['expire'] = '<span style="color:red;">' . pjUtil::formatDate($v['expire'], 'Y-m-d', $this->option_arr['o_date_format']) . '</span>';
					}else{
						$v['expire'] = pjUtil::formatDate($v['expire'], 'Y-m-d', $this->option_arr['o_date_format']);
					}
				}
				$data[$k] = $v;
			}
				
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			if (isset($_POST['listing_create']))
			{
				pjAppController::validateCsrfToken();
				if ($this->isOwner())
				{
					if ($this->option_arr['o_allow_add_listing'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL11");
					}
				}
				
				$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'] = 'E';
					$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=AL09");
				}
				
				if ($pjListingModel->where('t1.listing_refid', $data['listing_refid'])->findCount()->getData() > 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=AL10");
				}
				
				$id = $pjListingModel->reset()->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', 'data');
					}
					if($this->isOwner())
					{
						$listing_arr = $pjListingModel->reset()
							->select("t1.*, t2.name as owner_name, t2.email as owner_email")
							->join('pjUser', 't2.id=t1.owner_id', 'left outer')
							->find($id)
							->getData();
						$this->sendNotification(1, $listing_arr);
					}
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $id . "&err=$err");
				} else {
					$err = 'AL04';
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionCreate&err=$err");
				}
			}
			
			if ($this->isOwner())
			{
				$this->set('period_arr', pjPeriodModel::factory()->orderBy('t1.days ASC')->findAll()->getData());
			}
			if ($this->isAdmin())
			{
				$user_arr = pjUserModel::factory()->where('t1.status', 'T')->orderBy('t1.name ASC')->findAll()->getData();
			}else{
				$user_arr = pjUserModel::factory()->where('role_id', 3)->orderBy('t1.name ASC')->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 pjActionUpdate()
	{
		$this->checkLogin();
			
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			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 ($this->option_arr['o_allow_add_listing'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL11");
					}
					
					if ($arr['owner_id'] != $this->getUserId())
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL11");
					}

					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";
					}
				}
				
				$pjListingModel = pjListingModel::factory();
				$post = array_merge($_POST, $data);

				if (!$pjListingModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $_POST['id'] . "&locale=" . $_POST['locale'] . "&tab_id=" . $_POST['tab_id'] . "&err=AL09");
				}
				
				if ($pjListingModel->where('t1.id !=', $_POST['id'])->where('t1.listing_refid', $post['listing_refid'])->findCount()->getData() > 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $_POST['id'] . "&locale=" . $_POST['locale'] . "&tab_id=" . $_POST['tab_id'] . "&err=AL10");
				}
				
				$pjListingModel->set('id', $_POST['id'])->modify($post);

				if (isset($_POST['i18n']))
				{
				pjAppController::validateCsrfToken();
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjListing', 'data');
				}
				
				pjListingCategoryModel::factory()->where('listing_id', $_POST['id'])->eraseAll();
				
				if (isset($_POST['category']) && is_array($_POST['category']) && count($_POST['category']) > 0)
				{
					$pjListingCategoryModel = pjListingCategoryModel::factory();
					$pjListingCategoryModel->begin();
					foreach ($_POST['category'] as $category_id)
					{
						$pjListingCategoryModel->setAttributes(array(
							'listing_id' => $_POST['id'],
							'category_id' => $category_id
						))->insert();
					}
					$pjListingCategoryModel->commit();
				}
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionUpdate&id=" . $_POST['id'] . "&locale=" . $_POST['locale'] . "&tab_id=" . $_POST['tab_id'] . "&err=AL01");
				
			} else {
				$arr = pjListingModel::factory()->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=AL11");
				}
				
				$arr['i18n'] = pjMultiLangModel::factory()->getMultiLang($arr['id'], 'pjListing');
				
				$category_arr = pjCategoryModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('status', 'T')->orderBy('name ASC')->findAll()->getData();
				
				$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();
								
				if ($this->isAdmin())
				{
					$user_arr = pjUserModel::factory()->where('t1.status', 'T')->orderBy('t1.name ASC')->findAll()->getData();
				}else{
					$user_arr = pjUserModel::factory()->where('role_id', 3)->orderBy('t1.name ASC')->findAll()->getData();
				}
				
				$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']; //Hack for jquery $.extend, to prevent (re)order of numeric keys in object
				}
				
				$this->set('arr', $arr);
				$this->set('gallery_arr', pjGalleryModel::factory()->where('foreign_id', $arr['id'])->findAll()->getData());
				$this->set('category_arr', pjSanitize::clean($category_arr));
				$this->set('listing_category_arr', pjListingCategoryModel::factory()->where('t1.listing_id', $arr['id'])->findAll()->getDataPair(NULL, 'category_id'));
				$this->set('country_arr', pjSanitize::clean($country_arr));
				$this->set('user_arr', pjSanitize::clean($user_arr));
				$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/');
				
				# 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/');
				
				$api_key_str = isset($this->option_arr['o_google_map_api']) && !empty($this->option_arr['o_google_map_api']) ? 'key=' . $this->option_arr['o_google_map_api'] . '&' : '';
				$this->appendJs('', '//maps.google.com/maps/api/js?'.$api_key_str.'libraries=places&region=uk&language=en', true);
				
				$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');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetGeocode()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$geo = $this->pjActionGeocode($_POST);
			$response = array('code' => 100);
			if (isset($geo['lat']) && !is_array($geo['lat']))
			{
				$response = $geo;
				$response['code'] = 200;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	protected 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);
							
		$key = isset($this->option_arr['o_google_map_api']) ? $this->option_arr['o_google_map_api'] : '';
		$gfile = "https://maps.googleapis.com/maps/api/geocode/json?key=$key&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 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', 'data');
			}
		}
		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();
				
				pjListingCategoryModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				pjPaymentModel::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())
		{
			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();
				
				pjListingCategoryModel::factory()->whereIn('listing_id', $_POST['record'])->eraseAll();
				pjPaymentModel::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 pjActionExportListing()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$pjListingModel = pjListingModel::factory();
			if($this->isOwner()){
				$pjListingModel->where('t1.owner_id', $this->getUserId());
			}
			$sub_query = "(	SELECT GROUP_CONCAT(TC.id SEPARATOR '|') FROM " . pjListingCategoryModel::factory()->getTable() . " AS TLC
							LEFT OUTER JOIN " . pjCategoryModel::factory()->getTable() . " AS TC ON TLC.category_id=TC.id AND TC.status='T'
							WHERE TLC.listing_id=t1.id) as categories";
			$arr = $pjListingModel->select("t1.*, t2.content as title, t3.content as description, t4.content as meta_title, t5.content as meta_keywords, t6.content as meta_description, $sub_query")
					->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t4.model='pjListing' AND t4.foreign_id=t1.id AND t4.field='meta_title' AND t4.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t5.model='pjListing' AND t5.foreign_id=t1.id AND t5.field='meta_keywords' AND t5.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t6.model='pjListing' AND t6.foreign_id=t1.id AND t6.field='meta_description' AND t6.locale='".$this->getLocaleId()."'", 'left outer')
					->whereIn('t1.id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Listings-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionImport()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isOwner() || $this->isEditor())
		{
			if (isset($_POST['listing_import']))
			{
				pjAppController::validateCsrfToken();
				if (isset($_FILES['csv']) && !empty($_FILES['csv']['tmp_name']))
				{
					if(pjUtil::getFileExtension($_FILES['csv']['name']) == 'csv')
					{
						$csv_data = $this->loadCSV($_FILES['csv']);
						
						$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();
						
						$pjListingModel = pjListingModel::factory();
						$pjListingCategoryModel = pjListingCategoryModel::factory();
						$pjMultiLangModel = pjMultiLangModel::factory();
						
						foreach ($csv_data as $row)
						{
							$lang_arr = array();
							foreach($locale_arr as $v){
								$lang_arr[$v['id']]['title'] = $row['title'];
								$lang_arr[$v['id']]['description'] = $row['description'];
								$lang_arr[$v['id']]['meta_title'] = $row['meta_title'];
								$lang_arr[$v['id']]['meta_keywords'] = $row['meta_keywords'];
								$lang_arr[$v['id']]['meta_description'] = $row['meta_description'];
							}
							
							$arr = $pjListingModel->reset()->where('t1.listing_refid', $row['listing_refid'])->findAll()->getData();
							unset($row['id']);
							unset($row['modified']);
							
							if(count($arr) > 0)
							{
								$arr = $arr[0];
								
								unset($row['listing_refid']);
								$row['modified'] = date('Y-m-d H:i:s');
								if ($this->isOwner())
								{
									unset($row['owner_id']);
									unset($row['status']);
									unset($row['expire']);
									$row['owner_id'] = $this->getUserId();
								}
								$pjListingModel->reset()->set('id', $arr['id'])->modify($row);
								
								if (!empty($lang_arr))
								{
									$pjMultiLangModel->reset()->updateMultiLang($lang_arr, $arr['id'], 'pjListing', 'data');
								}
								
								$pjListingCategoryModel->reset()->where('listing_id', $arr['id'])->eraseAll();
								$category_id_arr = explode("|", $row['categories']); 
								unset($row['categories']);
								$pjListingCategoryModel->reset()->begin();
								foreach ($category_id_arr as $category_id){
									$data = array();
									$data['listing_id'] = $id;
									$data['category_id'] = $category_id;
									$pjListingCategoryModel->reset()->setAttributes($data)->insert();
								}
								$pjListingCategoryModel->commit();
							}else{
								$row['created'] = date('Y-m-d H:i:s');
								if ($this->isOwner())
								{
									unset($row['owner_id']);
									unset($row['status']);
									unset($row['expire']);
									$row['owner_id'] = $this->getUserId();
									$row['status'] = 'E';
									$row['expire'] = date("Y-m-d", strtotime("-1 day"));
								}
								$id = $pjListingModel->reset()->setAttributes($row)->insert()->getInsertId();
								
								if ($id !== false && (int) $id > 0)
								{
									if (!empty($lang_arr))
									{
										$pjMultiLangModel->reset()->updateMultiLang($lang_arr, $id, 'pjListing', 'data');
									}
									
									$category_id_arr = explode("|", $row['categories']); 
									unset($row['categories']);
									$pjListingCategoryModel->begin();
									foreach ($category_id_arr as $category_id){
										$data = array();
										$data['listing_id'] = $id;
										$data['category_id'] = $category_id;
										$pjListingCategoryModel->reset()->setAttributes($data)->insert();
									}
									$pjListingCategoryModel->commit();
								}
							}
						}
						
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionIndex&err=AL12");
					}else{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionImport&err=AL14");
					}
				}else{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminListings&action=pjActionImport&err=AL13");
				}
			}else{
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('additional-methods.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminListings.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExpireListing()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjListingModel = pjListingModel::factory();
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				$arr = $pjListingModel->whereIn('id', $_POST['record'])->findAll()->getData();
				foreach($arr as $k => $v)
				{
					$current = time();
					$expire_ts = strtotime($v['expire']);
					if($current <= $expire_ts)
					{
						$current = $expire_ts;
					}
					$pjListingModel->reset()->set('id', $v['id'])->modify(array(
							'status' => 'E',
							'last_extend' => 'free',
							'expire' => date("Y-m-d", $current + (30 * 86400))
					));
				}
			} elseif (isset($_GET['id']) && (int) $_GET['id'] > 0) {
				$arr = $pjListingModel->find($_GET['id'])->getData();
				$current = time();
				$expire_ts = strtotime($arr['expire']);
				if($current <= $expire_ts)
				{
					$current = $expire_ts;
				}
				
				$pjListingModel->set('id', $arr['id'])->modify(array(
						'status' => 'E',
						'last_extend' => 'free',
						'expire' => date("Y-m-d", $current + (30 * 86400))
				));
			}
		}
		exit;
	}
	
	public function pjActionExtend()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			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();
					$expire_ts = strtotime($arr['expire']);
					if($current <= $expire_ts)
					{
						$current = $expire_ts;
					}
					
					$pjListingModel->set('id', $arr['id'])->modify(array(
						'status' => 'E',
						'last_extend' => 'paid',
						'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')
				->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 sendNotification($notify_id, $listing_arr)
	{
		$arr = array();
		$arr = pjMultiLangModel::factory()->getMultiLang($notify_id, 'pjNotification');
		
		$subject = $arr[$this->getLocaleId()]['new_listing_subject'];
		$message = $arr[$this->getLocaleId()]['new_listing_message'];
		
		if(!empty($subject) && !empty($message))
		{
			$listingURL = PJ_INSTALL_URL . 'index.php?controller=pjAdminListings&action=pjActionUpdate&id=' . $listing_arr['id'];
			$listingURL = '<a href="'.$listingURL.'">'.$listingURL.'</a>';
			$message = str_replace(	array('{Email}', '{Name}', '{ListingRefID}', '{ListingURL}'), 
									array($listing_arr['owner_email'], $listing_arr['owner_name'], $listing_arr['listing_refid'], $listingURL), $message);
									
			$message = pjUtil::textToHtml($message);						
			$pjEmail = new pjEmail();
			$pjEmail->setContentType('text/html');
			if ($this->option_arr['o_send_email'] == 'smtp')
			{
				$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();
			$to_arr = $this->getAdminEmails();
			foreach($to_arr as $to)
			{
				$pjEmail->setFrom($from)
						->setTo($to)
						->setSubject($subject)
						->send($message);
			}
		}
	}
	
	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' => 'ypPaypal',
	            'id' => 'ypPaypal',
	            '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' => __('lblPeriod', 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);
	    }
	}
}