<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjListings extends pjFront
{
	private $isoDatePattern = '/\d{4}-\d{2}-\d{2}/';
		
	public function pjActionIndex()
	{
		$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')
			->join('pjMultiLang', "t4.model='pjListing' AND t4.foreign_id=t1.id AND t4.field='description' AND t4.locale='".$this->getLocaleId()."'", 'left');
			
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
		
		$category_where = "(t1.id IN(SELECT TLC.listing_id FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id IN(SELECT TC.id FROM `".pjCategoryModel::factory()->getTable()."` AS TC WHERE TC.status = 'T')))";
		if(isset($_GET['listing_search']))
		{
			if (isset($_GET['keyword']) && !empty($_GET['keyword']))
			{
				$keyword = pjObject::escapeString($_GET['keyword']);
				$pjListingModel->where("(t3.content LIKE '%$keyword%' OR t4.content LIKE '%$keyword%')");
			}
		}
		if (isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
		{
			$category_where = "(t1.id IN(SELECT TLC.listing_id FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id IN(SELECT TC.id FROM `".pjCategoryModel::factory()->getTable()."` AS TC WHERE TC.status = 'T' AND TC.id = ".(int) $_GET['category_id'].")))";
		}
		$pjListingModel->where($category_where);
		
		if(!isset($_GET['sortby']))
		{
			$_GET['sortby'] = 'title';
			$column = $_GET['sortby'];
		}else{
			if(in_array($_GET['sortby'], array('title', 'created')))
			{
				if($_GET['sortby'] == 'created'){
					$column = 't1.created';
				}else{
					$column = $_GET['sortby'];
				}
			}else{
				$_GET['sortby'] = 'title';
				$column = $_GET['sortby'];
			}
		}
		$direction = 'asc';
		if(!isset($_GET['direction']))
		{
			$_GET['direction'] = 'asc';
		}else{
			if(in_array(strtolower($_GET['direction']), array('asc', 'desc')))
			{
				$direction = strtoupper($_GET['direction']);
			}else{
				$_GET['direction'] = 'asc';
			}
		}
				
		$total = $pjListingModel->findCount()->getData();
		$items_per_page = (int) $this->option_arr['o_items_per_page'] > 0 ? $this->option_arr['o_items_per_page'] : 10;
		$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : $items_per_page;
		$pages = ceil($total / $rowCount);
		$page = isset($_GET['pjPage']) && (int) $_GET['pjPage'] > 0 ? intval($_GET['pjPage']) : 1;
		$offset = ((int) $page - 1) * $rowCount;
		if ($page > $pages)
		{
			$page = $pages;
		}
		
		$arr = $pjListingModel->select(sprintf("t1.id, t1.listing_refid, t3.content AS title, t1.expire, t1.status, t1.owner_id, t4.content as description, 
				(SELECT `small_path` FROM `%s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `image`, 
				(SELECT `medium_path` FROM `%s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `medium_image`", pjGalleryModel::factory()->getTable(), pjGalleryModel::factory()->getTable()))
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
		
		$category_arr = pjCategoryModel::factory()
			->select("t1.*, t2.content AS name, (SELECT COUNT(*) FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id = t1.id AND TLC.listing_id IN(SELECT TL.id FROM `".pjListingModel::factory()->getTable()."` AS TL WHERE  TL.status = 'T' OR (TL.status = 'E' AND TL.expire >= CURDATE())  )) AS `number_of_listings`")
			->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();
					
		$meta_arr = pjMultiLangModel::factory()->getMultiLang(1, 'pjOption');
					
		$this->set('meta_arr', array(
				'title' => isset($meta_arr[$this->getLocaleId()]['home_meta_title']) ? $meta_arr[$this->getLocaleId()]['home_meta_title'] : null,
				'keywords' => isset($meta_arr[$this->getLocaleId()]['home_meta_keywords']) ? $meta_arr[$this->getLocaleId()]['home_meta_keywords'] : null,
				'description' => isset($meta_arr[$this->getLocaleId()]['home_meta_description']) ? $meta_arr[$this->getLocaleId()]['home_meta_description'] : null
			));			
					
		$this->set('arr', $arr);
		$this->set('category_arr', $category_arr);
		$this->set('paginator', array('pages' => $pages, 'total' => $total));
	}
	
	public function pjActionView()
	{
		if(isset($_GET['id']) && (int) $_GET['id'] > 0)
		{
			$pjListingModel = pjListingModel::factory();
			
			$pjListingModel->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')
				->join('pjMultiLang', "t4.model='pjListing' AND t4.foreign_id=t1.id AND t4.field='description' AND t4.locale='".$this->getLocaleId()."'", 'left')
				->join('pjUser', "t5.id=t1.owner_id AND t5.status='T'", 'left')
				->join('pjMultiLang', "t6.model='pjListing' AND t6.foreign_id=t1.id AND t6.field='meta_title' AND t6.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t7.model='pjListing' AND t7.foreign_id=t1.id AND t7.field='meta_keywords' AND t7.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t8.model='pjListing' AND t8.foreign_id=t1.id AND t8.field='meta_description' AND t8.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t9.model='pjCountry' AND t9.foreign_id=t1.country_id AND t9.locale='".$this->getLocaleId()."'", 'left');
			
			$arr = $pjListingModel->select("t1.*, 	t6.content as model, t8.content as make, 
													t9.content as country_title,
													t3.content AS listing_title, t4.content as listing_description,
													t6.content AS meta_title, t7.content AS meta_keywords, t8.content AS meta_description")
					->find($_GET['id'])
					->getData();
					
			$pjListingModel->reset()->setAttributes(array('id' => $arr['id']))->modify(array('views' => $arr['views'] + 1));
			
			$gallery_arr = pjGalleryModel::factory()->where('t1.foreign_id', $_GET['id'])->orderBy('t1.sort ASC')->findAll()->getData();
			
			$this->set('gallery_arr', $gallery_arr);
			
			$og_image = '';
			if(!empty($gallery_arr))
			{
				$og_image = PJ_INSTALL_URL . $gallery_arr[0]['large_path'];
			
			}
			
			$this->set('meta_arr', array(
					'title' => !empty($arr['meta_title']) ? $arr['meta_title'] : pjSanitize::html(stripslashes($arr['listing_title'])),
					'keywords' => $arr['meta_keywords'],
					'description' => $arr['meta_description'],
					'url' => pjUtil::getPageURL(),
					'og_title' => pjSanitize::html(stripslashes($arr['listing_title'])),
					'og_image' => $og_image,
					'body' => pjUtil::truncateDescription(pjUtil::html2txt($arr['listing_description']), 160, ' ')
				));
				
			$this->set('arr', $arr);
			
			$dm = new pjDependencyManager(PJ_INSTALL_PATH, PJ_THIRD_PARTY_PATH);
			$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
			
			$this->appendCss('pjQuery.fancybox.css', PJ_INSTALL_URL . $dm->getPath('pj_fancybox'), true);
		}
	}
	
	public function pjActionMap()
	{
		$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')
			->join('pjMultiLang', "t4.model='pjListing' AND t4.foreign_id=t1.id AND t4.field='description' AND t4.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t5.model='pjCountry' AND t5.foreign_id=t1.country_id AND t5.locale='".$this->getLocaleId()."'", 'left');
			
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
		$pjListingModel->where('t1.address_map', '1');
				
		$category_where = "(t1.id IN(SELECT TLC.listing_id FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id IN(SELECT TC.id FROM `".pjCategoryModel::factory()->getTable()."` AS TC WHERE TC.status = 'T')))";
		
		if(isset($_GET['listing_map']))
		{
			if (isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
			{
				$category_where = "(t1.id IN(SELECT TLC.listing_id FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id IN(SELECT TC.id FROM `".pjCategoryModel::factory()->getTable()."` AS TC WHERE TC.status = 'T' AND TC.id = ".(int) $_GET['category_id'].")))";
			}
			if (isset($_GET['keyword']) && !empty($_GET['keyword']))
			{
				$keyword = pjObject::escapeString($_GET['keyword']);
				$pjListingModel->where("(t3.content LIKE '%$keyword%' OR t4.content LIKE '%$keyword%')");
			}
		}else{
			$pjListingModel->limit(100, 0);
		}
		$pjListingModel->where($category_where);
		
		if(!isset($_GET['sortby']))
		{
			$_GET['sortby'] = 'title';
			$column = $_GET['sortby'];
		}else{
			if($_GET['sortby'] == 'created'){
				$column = 't1.created';
			}else{
				$column = $_GET['sortby'];
			}
		}
		if(!isset($_GET['direction']))
		{
			$_GET['direction'] = 'asc';
		}
		
		$direction = strtoupper($_GET['direction']);
		
		$arr = $pjListingModel->select(sprintf("t1.*, t2.email as owner_email, t3.content AS title, t4.content as description, t5.content as country_title"))
				->orderBy("$column $direction")->findAll()->getData();
		
		$category_arr = pjCategoryModel::factory()
			->select("t1.*, t2.content AS name, (SELECT COUNT(*) FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id = t1.id AND TLC.listing_id IN(SELECT TL.id FROM `".pjListingModel::factory()->getTable()."` AS TL WHERE  TL.status = 'T' OR (TL.status = 'E' AND TL.expire >= CURDATE())  )) AS `number_of_listings`")
			->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();

		$meta_arr = pjMultiLangModel::factory()->getMultiLang(1, 'pjOption');
					
		$this->set('meta_arr', array(
				'title' => isset($meta_arr[$this->getLocaleId()]['map_meta_title']) ? $meta_arr[$this->getLocaleId()]['map_meta_title'] : null,
				'keywords' => isset($meta_arr[$this->getLocaleId()]['map_meta_keywords']) ? $meta_arr[$this->getLocaleId()]['map_meta_keywords'] : null,
				'description' => isset($meta_arr[$this->getLocaleId()]['map_meta_description']) ? $meta_arr[$this->getLocaleId()]['map_meta_description'] : null
			));
					
		$this->set('arr', $arr);
		$this->set('category_arr', $category_arr);
	}
	
	public function pjActionCategory()
	{
		$arr = pjCategoryModel::factory()
			->select("t1.*, t2.content AS name,
						(SELECT COUNT(*) FROM `".pjListingCategoryModel::factory()->getTable()."` as TLC WHERE TLC.category_id = t1.id AND TLC.listing_id IN(SELECT TL.id FROM `".pjListingModel::factory()->getTable()."` AS TL WHERE  TL.status = 'T' OR (TL.status = 'E' AND TL.expire >= CURDATE())  )) AS `number_of_listings`")
			->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();

		$meta_arr = pjMultiLangModel::factory()->getMultiLang(1, 'pjOption');
					
		$this->set('meta_arr', array(
				'title' => isset($meta_arr[$this->getLocaleId()]['category_meta_title']) ? $meta_arr[$this->getLocaleId()]['category_meta_title'] : null,
				'keywords' => isset($meta_arr[$this->getLocaleId()]['category_meta_keywords']) ? $meta_arr[$this->getLocaleId()]['category_meta_keywords'] : null,
				'description' => isset($meta_arr[$this->getLocaleId()]['category_meta_description']) ? $meta_arr[$this->getLocaleId()]['category_meta_description'] : null
			));			
					
		$this->set('arr', $arr);
	}
	
	public function pjActionAccount()
	{
		if ($this->option_arr['o_allow_add_listing'] == 'Yes')
		{
			if (isset($_POST['register']))
			{
				set_time_limit(0);
				
				if (!isset($_POST['email']))
				{
					$err = 9901;
				}
				if (!isset($_POST['password']))
				{
					$err = 9902;
				}
				if (!isset($_POST['name']))
				{
					$err = 9903;
				}
				if (!isset($_POST['captcha']))
				{
					$err = 9904;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
				{
					$err = 9905;
				}
				if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']))
				{
					$err = 9906;
				}
				if (isset($_POST['name']) && !pjValidation::pjActionNotEmpty($_POST['name']))
				{
					$err = 9907;
				}
				if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
				{
					$err = 9908;
				}
				if (isset($_POST['captcha']) && isset($_SESSION[$this->defaultCaptcha]) && strtoupper($_POST['captcha']) != $_SESSION[$this->defaultCaptcha])
				{
					$err = 9909;
				}
				
				if (isset($err))
				{
					if (isset($_SESSION[$this->defaultCaptcha]))
					{
						$_SESSION[$this->defaultCaptcha] = NULL;
						unset($_SESSION[$this->defaultCaptcha]);
					}
					if ($this->option_arr['o_seo_url'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionAccount&err=$err");
					}else{
						pjUtil::redirect($_SERVER['HTTP_REFERER'] . "?err=$err");
					}
				}
				
				if (isset($_SESSION[$this->defaultCaptcha]))
				{
					$_SESSION[$this->defaultCaptcha] = NULL;
					unset($_SESSION[$this->defaultCaptcha]);
				}
				
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->where('t1.email', $_POST['email'])->findAll()->getData();
				
				if (!empty($arr) && count($arr) > 0)
				{
					if ($this->option_arr['o_seo_url'] == 'No')
					{
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionAccount&err=9910");
					}else{
						pjUtil::redirect($_SERVER['HTTP_REFERER'] . "?err=9910");
					}
				}else{
					$data = array();
					$data['email'] = $_POST['email'];
					$data['password'] = $_POST['password'];
					$data['name'] = $_POST['name'];
					$data['role_id'] = 3;
					$data['status'] = $this->option_arr['o_owner_is_active'] == 'Yes' ? 'T' : 'F';
					$data['ip'] = $_SERVER['REMOTE_ADDR'];
					
					$id = $pjUserModel->reset()->setAttributes($data)->insert()->getInsertId();
					if ($id !== false && (int) $id > 0)
					{
						$this->sendNotification(1, $_POST['email'], $_POST['name']);
						if ($this->option_arr['o_owner_is_active'] == 'Yes')
						{
							if ($this->option_arr['o_seo_url'] == 'No')
							{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionAccount&err=9999");
							}else{
								pjUtil::redirect($_SERVER['HTTP_REFERER'] . "?err=9999");
							}
						} else {
							if ($this->option_arr['o_seo_url'] == 'No')
							{
								pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionAccount&err=9998");
							}else{
								pjUtil::redirect($_SERVER['HTTP_REFERER'] . "?err=9998");
							}
						}
						exit;
					}
				}
			}
			
			$meta_arr = pjMultiLangModel::factory()->getMultiLang(1, 'pjOption');
					
			$this->set('meta_arr', array(
					'title' => isset($meta_arr[$this->getLocaleId()]['account_meta_title']) ? $meta_arr[$this->getLocaleId()]['account_meta_title'] : null,
					'keywords' => isset($meta_arr[$this->getLocaleId()]['account_meta_keywords']) ? $meta_arr[$this->getLocaleId()]['account_meta_keywords'] : null,
					'description' => isset($meta_arr[$this->getLocaleId()]['account_meta_description']) ? $meta_arr[$this->getLocaleId()]['account_meta_description'] : null
				));
			
		}else{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionIndex");
		}
	}
	
	public function pjActionForgot()
	{
		if ($this->option_arr['o_allow_add_listing'] == 'Yes')
		{
			if (isset($_GET['forgot_password']))
			{
				set_time_limit(0);
					
				if (!isset($_GET['email']))
				{
					$err = 9901;
				}
				if (isset($_GET['email']) && !pjValidation::pjActionNotEmpty($_GET['email']))
				{
					$err = 9902;
				}
				if (isset($err))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionForgot&err=$err");
				}
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->where('t1.email', $_GET['email'])->findAll()->getData();
				
				if (empty($arr) || count($arr) == 0)
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionForgot&err=9903");
				}else{
					$this->sendForgotEmail(1, $arr[0]);
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionForgot&err=9999");
				}
			}
		}else{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjListings&action=pjActionIndex");
		}
	}
	
	public function pjActionConfirmPayment()
	{
		$this->setAjax(true);
		
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Paypal plugin not installed'));
		}
		
		$input = file_get_contents('php://input');
		$post = json_decode($input, true);
		if ($post) {
		    $_REQUEST = array_merge($_REQUEST, $post);
		}
		
		$pjPaymentModel = pjPaymentModel::factory();
		$pjListingModel = pjListingModel::factory();
		
		list($listing_id, $period_id) = explode('-', $_REQUEST['custom']);
		$listing_arr = $pjListingModel->find($listing_id)->getData();
		$payment_arr = $pjPaymentModel->where('t1.listing_id', $listing_id)->orderBy('t1.date_to DESC')->limit(1)->findAll()->getData();
		$period_arr = pjPeriodModel::factory()->find($period_id)->getData();
		$date_from = date("Y-m-d");
		if (count($payment_arr) === 1)
		{
			$date_from = $payment_arr[0]['date_to'];
		}
		
		$period = $price = NULL;
		if ($period_arr)
		{
		    $period = (int) $period_arr['days'];
		    $price = (float) $period_arr['price'];
		}
		list($year, $month, $day) = explode("-", $date_from);
		$date_to = date("Y-m-d", mktime(0, 0, 0, $month, $day + $period, $year));
		
		$params = array(
		    'request'		=> $_REQUEST,
		    'txn_id' => @$payment_arr[0]['txn_id'],
		    'paypal_address' => $this->option_arr['o_paypal_address'],
		    'deposit' => $price,
		    'currency' => $this->option_arr['o_currency'],
		    'key' => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		if (count($payment_arr) === 1) {
		    $params['cancel_hash'] = sha1($payment_arr[0]['id'].strtotime($payment_arr[0]['processed_on']).PJ_SALT);
		}
		$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
		if ($response !== FALSE && isset($response['status']) && $response['status'] === 'OK')
		{
			$this->log('pjPaypal > pjActionConfirm > status == OK');
			$pjPaymentModel
				->reset()
				->setAttributes(array(
					'listing_id' => $listing_arr['id'],
					'date_from' => $date_from,
					'date_to' => $date_to,
					'txn_id' => $response['transaction_id'],
					'price' => $price
				))
				->insert();
			$current = time();
			if (!empty($listing_arr['expire']) && $listing_arr['expire'] != '0000-00-00')
			{
				$expire_ts = strtotime($listing_arr['expire']);
				if($current <= $expire_ts)
				{
					$current = $expire_ts;
				}
			}
			pjListingModel::factory()
				->set('id', $listing_arr['id'])
				->modify(array(
					'last_extend' => 'paid',
					'status' => 'E',
					'expire' => date("Y-m-d", $current + $period * 86400)
				));
			$this->log('Payment confirmed');
			pjAppController::jsonResponse(array('status' => 'OK', 'text' => 'Payment confirmed'));
		} elseif (!$response) {
			$this->log('Authorization failed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Authorization failed'));
		} else {
			$this->log('Payment not confirmed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Payment not confirmed'));
		}
	}
	
	public function pjActionConfirmStripe()
	{
		$this->setAjax(true);
		
		if (pjObject::getPlugin('pjStripe') === NULL)
		{
			$this->log('Stripe plugin not installed');
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex");
		}
		
		if (!isset($_GET['custom']) || !isset($_GET['session_id']))
		{
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex");
		}
		
		$pjPaymentModel = pjPaymentModel::factory();
		$pjListingModel = pjListingModel::factory();
		
		list($listing_id, $period_id) = explode('-', $_GET['custom']);
		$listing_arr = $pjListingModel->find($listing_id)->getData();
		$payment_arr = $pjPaymentModel->where('t1.listing_id', $listing_id)->orderBy('t1.date_to DESC')->limit(1)->findAll()->getData();
		$period_arr = pjPeriodModel::factory()->find($period_id)->getData();
		$date_from = date("Y-m-d");
		if (count($payment_arr) === 1)
		{
			$date_from = $payment_arr[0]['date_to'];
		}
		
		$period = $price = NULL;
		if ($period_arr)
		{
			$period = (int) $period_arr['days'];
			$price = (float) $period_arr['price'];
		}
		list($year, $month, $day) = explode("-", $date_from);
		$date_to = date("Y-m-d", mktime(0, 0, 0, $month, $day + $period, $year));
		
		$params = array(
			'request'    => $_GET,
			'deposit'    => $price,
			'currency'   => $this->option_arr['o_currency'],
			'foreign_id' => $listing_arr['id'],
			'key'        => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		if (count($payment_arr) === 1) {
			$params['cancel_hash'] = sha1($payment_arr[0]['id'].strtotime($payment_arr[0]['processed_on']).PJ_SALT);
		}
		$response = $this->requestAction(array('controller' => 'pjStripe', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
		if ($response !== FALSE && isset($response['status']) && $response['status'] === 'OK')
		{
			$this->log('pjStripe > pjActionConfirm > status == OK');
			$pjPaymentModel
				->reset()
				->setAttributes(array(
					'listing_id' => $listing_arr['id'],
					'date_from' => $date_from,
					'date_to' => $date_to,
					'txn_id' => $response['transaction_id'],
					'price' => $price
				))
				->insert();
			$current = time();
			if (!empty($listing_arr['expire']) && $listing_arr['expire'] != '0000-00-00')
			{
				$expire_ts = strtotime($listing_arr['expire']);
				if($current <= $expire_ts)
				{
					$current = $expire_ts;
				}
			}
			pjListingModel::factory()
				->set('id', $listing_arr['id'])
				->modify(array(
					'last_extend' => 'paid',
					'status' => 'E',
					'expire' => date("Y-m-d", $current + $period * 86400)
				));
			$this->log('Payment confirmed');
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex&extend=1");
		} else {
			$this->log('Payment not confirmed');
			pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminListings&action=pjActionIndex");
		}
	}
	
	function pjActionGetLatLng()
	{
		$this->setAjax(true);
		
		$_address = $_GET['address'];
		$_address = preg_replace('/\s+/', '+', $_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;
		}
		
		if (isset($data['lat']) && !is_array($data['lat']))
		{
			$data['code'] = 200;
		}else{
			$data['code'] = 100;
		}
		pjAppController::jsonResponse($data);
	}
	
	function pjActionSendSharing()
	{
		$this->setAjax(true);
		
		$pjEmail = new pjEmail();
		
		$pjEmail->setContentType('text/html');
		
		$from = $_POST['from'];
		$to = $_POST['to'];
		$subject = $_POST['subject'];
		$message = pjUtil::textToHtml($_POST['message']);
		
		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->setFrom($from)
				->setTo($to)
				->setSubject($subject)
				->send($message);
		
		echo 100;
		exit;
	}
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['email']) || empty($_GET['email']))
			{
				echo 101;
				exit;
			}
			$pjUserModel = pjUserModel::factory()->where('t1.email', $_GET['email']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjUserModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjUserModel->findCount()->getData() == 0 ? 100 : 101;
		}
		exit;
	}
	
	public function sendNotification($notify_id, $email, $name)
	{
		$arr = array();
		$arr = pjMultiLangModel::factory()->getMultiLang($notify_id, 'pjNotification');
		
		$subject = $arr[$this->getLocaleId()]['new_account_subject'];
		$message = $arr[$this->getLocaleId()]['new_account_message'];
		
		if(!empty($subject) && !empty($message))
		{
			$message = str_replace(	array('{Email}', '{Name}'), 
									array($email, $name), $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 sendForgotEmail($notify_id, $arr)
	{
		$notify_arr = array();
		$notify_arr = pjMultiLangModel::factory()->getMultiLang($notify_id, 'pjNotification');
		
		$subject = $notify_arr[$this->getLocaleId()]['forgot_subject'];
		$message = $notify_arr[$this->getLocaleId()]['forgot_message'];
		
		if(!empty($subject) && !empty($message))
		{
			$message = str_replace(	array('{Name}', '{Password}'), 
									array($arr['name'], $arr['password']), $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['email'];
			$pjEmail->setFrom($from)
					->setTo($to)
					->setSubject($subject)
					->send($message);
			
		}
	}
}
?>