<?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 pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || ($this->isOwner() && $this->option_arr['o_allow_add_listing'] == 'Yes'))
		{
			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['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)
				{
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjListing');
					}
					if ($this->isOwner())
					{
						
						$this->pjActionSendNotification($id);
					}
					
					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());
			}
			
			$manufacturer_arr = pjManufacturerModel::factory()->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.model='pjManufacturer' 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('manufacturer_arr', pjSanitize::clean($manufacturer_arr));
	
			$user_arr = pjUserModel::factory()->where('role_id', 3)->findAll()->getData();
			$this->set('user_arr', pjSanitize::clean($user_arr));
			
			$this->set('listing_refid', pjListingModel::factory()->getLastID());
			
			$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();
				
				pjListingExtraModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				pjPaymentModel::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();
				}
				$pjBookingModel = pjBookingModel::factory();
				$booking_id_arr = $pjBookingModel->where('listing_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
				if(!empty($booking_id_arr))
				{
					pjBookingPaymentModel::factory()->whereIn('booking_id', $booking_id_arr)->eraseAll();
					$pjBookingModel->reset()->where('listing_id', $_GET['id'])->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();
				
				pjListingExtraModel::factory()->where('listing_id', $_GET['id'])->eraseAll();
				pjPaymentModel::factory()->whereIn('listing_id', $_POST['record'])->eraseAll();
				pjPriceModel::factory()->whereIn('listing_id', $_POST['record'])->eraseAll();
				
				$pjBookingModel = pjBookingModel::factory();
				$booking_id_arr = $pjBookingModel->whereIn('listing_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
				if(!empty($booking_id_arr))
				{
					pjBookingPaymentModel::factory()->whereIn('booking_id', $booking_id_arr)->eraseAll();
					$pjBookingModel->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('manufacturer_arr', pjManufacturerModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjManufacturer' 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('pjMultiLang', "t3.model='pjManufacturer' AND t3.foreign_id=t1.manufacturer_id AND t3.field='name' AND t3.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 ($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['for']) && $_GET['for'] != '')
			{
				$pjListingModel->where('t1.for', $_GET['for']);
			}
			if (isset($_GET['manufacturer_id']) && (int) $_GET['manufacturer_id'] > 0)
			{
				$pjListingModel->where('t1.manufacturer_id', $_GET['manufacturer_id']);
			}
			if (isset($_GET['address_country']) && (int) $_GET['address_country'] > 0)
			{
				$pjListingModel->where('t1.address_country', $_GET['address_country']);
			}
			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('image', 'listing_refid', 'type', 'owner_name', 'price', 'status');
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array($_GET['column'], $allowed_columns) && 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.for, t1.added_by, t3.content AS manufacturer_title, t1.owner_id, t1.listing_price, t2.name AS owner_name,
					(SELECT MIN(price) FROM `".pjPriceModel::factory()->getTable()."` AS TP1 WHERE TP1.listing_id=t1.id) AS `min_price`,
					(SELECT MAX(price) FROM `".pjPriceModel::factory()->getTable()."` AS TP1 WHERE TP1.listing_id=t1.id) AS `max_price`,
					(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();
			
			$listing_for = __('listing_for', true);
			
			foreach($arr as $k => $v)
			{
				$v['price'] = '';
				$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']);
				$v['type'] = $listing_for[$v['for']];
				if($v['for'] == 'sale' && !empty($v['listing_price']))
				{
					$v['price'] = pjUtil::formatCurrencySign(number_format($v['listing_price'], 0), $this->option_arr['o_currency']);
				}
				if($v['for'] == 'rent' && !empty($v['min_price']) && !empty($v['max_price']))
				{
					$v['price'] = pjUtil::formatCurrencySign(number_format($v['min_price'], 0), $this->option_arr['o_currency']) . ' - ' . pjUtil::formatCurrencySign(number_format($v['max_price'], 0), $this->option_arr['o_currency']) . '<br/>' . __('lblPerWeek', true);
				}
				$data[$k] = $v;
			}	
				
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || ($this->isOwner() && $this->option_arr['o_allow_add_listing'] == 'Yes'))
		{
			$user_arr = pjUserModel::factory()->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));
			
			$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');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionExtend()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || ($this->isOwner() && $this->option_arr['o_allow_add_listing'] == 'Yes'))
		{
			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() && $this->option_arr['o_allow_add_listing'] == '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())
		{
			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->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_listing'] == 'Yes'))
		{
			$ListingExtraModel = new pjListingExtraModel();
				
			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";
					}
				}
				
				$pjListingModel = pjListingModel::factory();
				$post = array_merge($_POST, $data);
				
				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');
				}
				
				pjListingExtraModel::factory()->where('listing_id', $_POST['id'])->eraseAll();
				if (isset($_POST['extra']) && is_array($_POST['extra']) && count($_POST['extra']) > 0)
				{
					$ListingExtraModel->begin();
					foreach ($_POST['extra'] as $extra_id)
					{
						$ListingExtraModel->setAttributes(array(
							'listing_id' => $_POST['id'],
							'extra_id' => $extra_id
						))->insert();
					}
					$ListingExtraModel->commit();
				}
				
				$pjPriceModel = pjPriceModel::factory();
				if($_POST['for'] == 'rent')
				{
					foreach ($_POST['rental_price'] as $start_date => $price)
					{
						$pjPriceModel->reset()->where('listing_id', $_POST['id'])->where('start_date', $start_date)->eraseAll();
						if(!empty($price))
						{
							$pjPriceModel->reset()->setAttributes(array(
									'listing_id' => $_POST['id'],
									'start_date' => $start_date,
									'price' => $price
							))->insert();
						}
					}
				}else{
					$pjPriceModel->where('listing_id', $_POST['id'])->eraseAll();
				}
				
				$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("t1.*")
					->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);
									
				$manufacturer_arr = pjManufacturerModel::factory()->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjManufacturer' 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('manufacturer_arr', pjSanitize::clean($manufacturer_arr));
				
				$this->set('gallery_arr', pjGalleryModel::factory()->where('foreign_id', $arr['id'])->findAll()->getData());
				
				$pjFeatureModel = pjFeatureModel::factory();
				$feature_arr = array();
				foreach(__('feature_types') as $k => $v)
				{
					$feature_arr[$k] = $pjFeatureModel
						->reset()
						->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')
						->where('type', $k)
						->orderBy('name ASC')
						->findAll()
						->getData();
				}
				$this->set('feature_arr', $feature_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));
				
				$user_arr = pjUserModel::factory()->where('status', 'T')->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));
			
				$pjExtraModel = pjExtraModel::factory();
				$extra_arr = array();
				foreach(__('extra_types') as $k => $v)
				{
					$extra_arr[$k] = $pjExtraModel
						->reset()
						->select('t1.*, t2.content AS name')
						->join('pjMultiLang', "t2.model='pjExtra' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->where('status', 'T')
						->where('type', $k)
						->orderBy('name ASC')
						->findAll()
						->getData();
				}
				$this->set('extra_arr', $extra_arr);
				
				$listing_extra_id_arr = pjListingExtraModel::factory()->where('t1.listing_id', $_GET['id'])->findAll()->getDataPair('extra_id', 'extra_id');
				$this->set('listing_extra_id_arr', $listing_extra_id_arr);
				
				if($arr['for'] == 'rent')
				{
					$this->set('price_arr', pjPriceModel::factory()->getPrices($arr['id'], date('Y')));
				}
				
				# TinyMCE
				$this->appendJs('tinymce.min.js', PJ_THIRD_PARTY_PATH . 'tiny_mce/');
				
				# 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/');
				
				# 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');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionResetContact()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$owner_id = null;
			if($this->isOwner())
			{
				$owner_id = $this->getUserId();
			}else if(isset($_GET['id']) && (int) $_GET['id'] > 0){
				$owner_id = $_GET['id'];
			}
			$arr = array();
			if($owner_id != null)
			{
				$arr = pjUserModel::factory()->find($owner_id)->getData();
			}
			pjAppController::jsonResponse($arr);
		}
		exit;
	}
	

	public function pjActionGetPrices()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$this->set('price_arr', pjPriceModel::factory()->getPrices($_GET['id'], $_GET['year']));
		}
	}
	
	public function pjActionSendNotification($id)
	{
		
		$arr = pjListingModel::factory()
			->join('pjMultiLang', "t2.model='pjManufacturer' AND t2.foreign_id=t1.manufacturer_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->join('pjUser', "t4.id=t1.owner_id", "left")
			->select('t1.*, t2.content as manufacturer, t3.content as title, t4.email, t4.phone')
			->find($id)
			->getData();
		
		if(!empty($arr))
		{
			$type_arr = __('listing_for', true);
			$pjEmail = new pjEmail();
			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']);
			}
			
			$pjEmail->setContentType('text/html');
			$from = $this->getAdminEmail();
			$to_email = !empty($arr['owner_email']) ? $arr['owner_email'] : (!empty($arr['email']) ? $arr['email'] : '');
			$to_phone = !empty($arr['owner_phone']) ? $arr['owner_phone'] : (!empty($arr['phone']) ? $arr['phone'] : '');
			$url = PJ_INSTALL_URL . 'index.php?controller=pjAdminListings&action=pjActionUpdate&id=' . $arr['id'];
			$url = '<a href="'.$url.'">'.$url.'</a>';
			$search = array("{RefID}", "{Title}", "{Type}", "URL");
			$replace = array($arr['listing_refid'], $arr['title'], $type_arr[$arr['for']], $url);

			
			$pjMultiLangModel = pjMultiLangModel::factory();
			if ($this->option_arr['o_email_submission'] == 1 && $to_email != '')
			{
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_submission_subject')
					->limit(0, 1)
					->findAll()->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_submission_message')
					->limit(0, 1)
					->findAll()->getData();
				
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$message = str_replace($search, $replace, $lang_message[0]['content']);
						
					$pjEmail
						->setTo($to_email)
						->setFrom($from)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($message));
				}
			}
			if ($this->option_arr['o_admin_email_submission'] == 1)
			{
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_email_submission_subject')
					->limit(0, 1)
					->findAll()->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_email_submission_message')
					->limit(0, 1)
					->findAll()->getData();
					
				if (count($lang_message) === 1 && count($lang_subject) === 1)
				{
					$message = str_replace($search, $replace, $lang_message[0]['content']);
					$pjEmail
						->setTo($from)
						->setFrom($from)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($message));
				}
			}
			if(!empty($to_phone) && $this->option_arr['o_sms_submission'] == 1)
			{
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_sms_submission_message')
					->limit(0, 1)
					->findAll()->getData();
				if (count($lang_message) === 1)
				{
					$message = str_replace($search, $replace, $lang_message[0]['content']);
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($this->option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $to_phone;
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
			$admin_phone = $this->getAdminPhone();
			if(!empty($admin_phone) && $this->option_arr['o_admin_sms_submission'] == 1)
			{
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_sms_submission_message')
					->limit(0, 1)
					->findAll()->getData();
				if (count($lang_message) === 1)
				{
					$message = str_replace($search, $replace, $lang_message[0]['content']);
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($this->option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $admin_phone;
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
	}
	
	public function pjActionGetPaymentForm()
	{
	    $this->setAjax(true);
	    
	    if ($this->isXHR())
	    {
	        $this->option_arr = pjOptionModel::factory()->getPairs(1);
	        
	        $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',
	            'foreign_id' => 1,
	            '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' => __('payment_period', true) .'(#'.$period_arr['id'].'): '. $period_arr['days'] .' '. __('lblDays', 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);
	    }
	}
	
	public function pjActionGetStripeForm()
	{
	    $this->setAjax(true);
	    
	    if ($this->isXHR())
	    {
	        $this->option_arr = pjOptionModel::factory()->getPairs(1);
	        
	        $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' => 'ylStripe',
	            'id' => 'ylStripe',
	            'public_key' => $this->option_arr['o_stripe_public_key'],
	            'item_name' => __('payment_period', true) .'(#'.$period_arr['id'].'): '. $period_arr['days'] .' '. __('lblDays', true),
	            'custom' => $listing_arr['id'].'-'.$period_arr['id'],
	            'amount' => number_format($period_arr['price'], 2, '.', ''),
	            'currency_code' => $this->option_arr['o_currency'],
	            'notify_url' => PJ_INSTALL_URL . "index.php?controller=pjListings&action=pjActionConfirmStripe",
	            'failure_url' => !empty($this->option_arr['o_stripe_cancel_url']) ? $this->option_arr['o_stripe_cancel_url'] : PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex",
	            'return' => PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex",
	            'target' => '_self',
	            'charset' => 'utf-8'
	        ));
	        $this->set('listing_arr', $listing_arr);
	        $this->set('period_arr', $period_arr);
	    }
	}
}
?>