<?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 getFeaturedYachts($option_arr, $locale_id, $type)
	{
		$pjListingModel = pjListingModel::factory()
			->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$locale_id."'", 'left')
			->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$locale_id."'", 'left');
		
		$pjListingModel->where('t1.is_featured', 'T');
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
		$pjListingModel->where("(t2.content IS NOT NULL)");
		
		if($type == 'sale' || $type == 'rent')
		{
			$pjListingModel->where('`for`', $type);
		}
		
		$sorting = 't1.created DESC';
		$cnt = $pjListingModel->findCount()->getData();
		if($cnt > $option_arr['o_featured_yachts'])
		{
			$sorting = 'RAND()';
		}
		$pjListingModel->limit(3, 0);
		
		$gallery_table = pjGalleryModel::factory()->getTable();
		$price_table = pjPriceModel::factory()->getTable();
		
		$monday = date('Y-m-d',strtotime('monday this week'));
		$arr = $pjListingModel
			->select(sprintf("t1.*, t2.content AS title, t1.expire, t1.status, t3.content as description,
					(SELECT MIN(price) FROM `".$price_table."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."') AS `min_price`,
					(SELECT MAX(price) FROM `".$price_table."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."') AS `max_price`,
					(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`,
					(SELECT `large_path` FROM `%s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `large_image`", $gallery_table, $gallery_table, $gallery_table))
			->orderBy("$sorting")
			->findAll()
			->getData();
		
		return $arr;
	}
	
	public function pjActionIndex()
	{
		pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionYachts");
	}
	
	public function pjActionFeatured()
	{
		$this->set('arr', $this->getFeaturedYachts($this->option_arr, $this->getLocaleId()), 'both');
	}
	
	
	public function pjActionYachts()
	{
		$pjListingModel = pjListingModel::factory()
			->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left');
		
		$pjListingModel->where("(t1.status = 'T' OR (t1.status = 'E' AND t1.expire >= CURDATE()))");
		$pjListingModel->where("(t2.content IS NOT NULL)");
		
		$monday = date('Y-m-d',strtotime('monday this week'));
		if(isset($_GET['listing_search']))
		{
			if (isset($_GET['keyword']) && !empty($_GET['keyword']))
			{
				$keyword = pjObject::escapeString($_GET['keyword']);
				$pjListingModel->where('t1.listing_refid LIKE', "%$keyword%");
				$pjListingModel->orWhere('t2.content LIKE', "%$keyword%");
				$pjListingModel->orWhere('t3.content LIKE', "%$keyword%");
			}
			if (isset($_GET['for']) && !empty($_GET['for']))
			{
				$pjListingModel->where('t1.for', pjObject::escapeString($_GET['for']));
			}
			if (isset($_GET['manufacturer_id']) && (int) $_GET['manufacturer_id'])
			{
				$pjListingModel->where('t1.manufacturer_id', $_GET['manufacturer_id']);
			}
			if (isset($_GET['feature_fuel_id']) && (int) $_GET['feature_fuel_id'])
			{
				$pjListingModel->where('t1.feature_fuel_id', $_GET['feature_fuel_id']);
			}
			if (isset($_GET['feature_engine_id']) && (int) $_GET['feature_engine_id'])
			{
				$pjListingModel->where('t1.feature_engine_id', $_GET['feature_engine_id']);
			}
			if (isset($_GET['feature_hull_id']) && (int) $_GET['feature_hull_id'])
			{
				$pjListingModel->where('t1.feature_hull_id', $_GET['feature_hull_id']);
			}
			if (isset($_GET['feature_yacht_id']) && (int) $_GET['feature_yacht_id'])
			{
				$pjListingModel->where('t1.feature_yacht_id', $_GET['feature_yacht_id']);
			}
			if (isset($_GET['listing_model']) && !empty($_GET['listing_model']))
			{
				$model = pjObject::escapeString($_GET['listing_model']);
				$pjListingModel->where('t1.listing_model LIKE', "%$model%");
			}
			if (isset($_GET['listing_refid']) && !empty($_GET['listing_refid']))
			{
				$refid = pjObject::escapeString($_GET['listing_refid']);
				$pjListingModel->where('t1.listing_refid LIKE', "%$refid%");
			}
			$year_both = false;
			if (isset($_GET['min_year']))
			{
				if($_GET['min_year'] != '' && (int) $_GET['min_year'] > 0)
				{
					$min_year = pjObject::escapeString($_GET['min_year']);
					if (isset($_GET['max_year']))
					{
						if($_GET['max_year'] != '' && (int) $_GET['max_year'] > 0)
						{
							$max_year = pjObject::escapeString($_GET['max_year']);
							$pjListingModel->where("(t1.listing_year >= ".$min_year." AND t1.listing_year <= ".$max_year.")");
							$year_both = true;
						}else{
							$pjListingModel->where("(t1.listing_year >= ".$min_year.")");
						}
					}else{
						$pjListingModel->where("(t1.listing_year >= ".$min_year.")");
					}
				}
			}
			if($year_both == false)
			{
				if (isset($_GET['max_year']))
				{
					if($_GET['max_year'] != '' && (int) $_GET['max_year'] > 0)
					{
						$max_year = pjObject::escapeString($_GET['max_year']);
						$pjListingModel->where("(t1.listing_year <= ".$max_year.")");
					}
				}
			}
			$length_both = false;
			if (isset($_GET['min_length']))
			{
				if($_GET['min_length'] != '' && (int) $_GET['min_length'] > 0)
				{
					if (isset($_GET['max_length'])){
						if($_GET['max_length'] != '' && (int) $_GET['max_length'] > 0)
						{
							$pjListingModel->where("(t1.listing_length >= ".$_GET['min_length']." AND t1.listing_length <= ".$_GET['max_length'].")");
							$length_both = true;
						}else{
							$pjListingModel->where("(t1.listing_length >= ".$_GET['min_length'].")");
						}
					}else{
						$pjListingModel->where("(t1.listing_length >= ".$_GET['min_length'].")");
					}
				}
			}
			if($length_both == false)
			{
				if (isset($_GET['max_length']))
				{
					if($_GET['max_length'] != '' && (int) $_GET['max_length'] > 0)
					{
						$pjListingModel->where("(t1.listing_length <= ".$_GET['max_length'].")");
					}
				}
			}
			$horse_power_both = false;
			if (isset($_GET['min_horse_power']))
			{
				if($_GET['min_horse_power'] != '' && (int) $_GET['min_horse_power'] > 0)
				{
					if (isset($_GET['max_horse_power'])){
						if($_GET['max_horse_power'] != '' && (int) $_GET['max_horse_power'] > 0)
						{
							$pjListingModel->where("t1.listing_power >=", pjObject::escapeString($_GET['min_horse_power']));
							$pjListingModel->where("t1.listing_power <=", pjObject::escapeString($_GET['max_horse_power']));
							$horse_power_both = true;
						}else{
							$pjListingModel->where("t1.listing_power >=", pjObject::escapeString($_GET['min_horse_power']));
						}
					}else{
						$pjListingModel->where("t1.listing_power >=", pjObject::escapeString($_GET['min_horse_power']));
					}
				}
			}
			if($horse_power_both == false)
			{
				if (isset($_GET['max_horse_power']))
				{
					if($_GET['max_horse_power'] != '' && (int) $_GET['max_horse_power'] > 0)
					{
						$pjListingModel->where("t1.listing_power <=", pjObject::escapeString($_GET['max_horse_power']));
					}
				}
			}
			
			$loa_both = false;
			if (isset($_GET['min_loa']))
			{
				if($_GET['min_loa'] != '' && (int) $_GET['min_loa'] > 0)
				{
					if (isset($_GET['max_loa'])){
						if($_GET['max_loa'] != '' && (int) $_GET['max_loa'] > 0)
						{
							$pjListingModel->where("(t1.listing_loa >= ".$_GET['min_loa']." AND t1.listing_loa <= ".$_GET['max_loa'].")");
							$loa_both = true;
						}else{
							$pjListingModel->where("(t1.listing_loa >= ".$_GET['min_loa'].")");
						}
					}else{
						$pjListingModel->where("(t1.listing_loa >= ".$_GET['min_loa'].")");
					}
				}
			}
			if($loa_both == false)
			{
				if (isset($_GET['max_loa']))
				{
					if($_GET['max_loa'] != '' && (int) $_GET['max_loa'] > 0)
					{
						$pjListingModel->where("(t1.listing_loa <= ".$_GET['max_loa'].")");
					}
				}
			}
			
			$beam_both = false;
			if (isset($_GET['min_beam']))
			{
				if($_GET['min_beam'] != '' && (int) $_GET['min_beam'] > 0)
				{
					if (isset($_GET['max_beam'])){
						if($_GET['max_beam'] != '' && (int) $_GET['max_beam'] > 0)
						{
							$pjListingModel->where("(t1.listing_beam >= ".$_GET['min_beam']." AND t1.listing_beam <= ".$_GET['max_beam'].")");
							$beam_both = true;
						}else{
							$pjListingModel->where("(t1.listing_beam >= ".$_GET['min_beam'].")");
						}
					}else{
						$pjListingModel->where("(t1.listing_beam >= ".$_GET['min_beam'].")");
					}
				}
			}
			if($beam_both == false)
			{
				if (isset($_GET['max_beam']))
				{
					if($_GET['max_beam'] != '' && (int) $_GET['max_beam'] > 0)
					{
						$pjListingModel->where("(t1.listing_beam <= ".$_GET['max_beam'].")");
					}
				}
			}
			
			if(isset($_GET['min_price']) && isset($_GET['max_price']) && (int) $_GET['min_price'] >= 0 && (int) $_GET['max_price'] >= 0)
			{
				$price_table = pjPriceModel::factory()->getTable();
				$min_price_str = "(SELECT MIN(price) FROM `".$price_table."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."')";
				$max_price_str = "(SELECT MAX(price) FROM `".$price_table."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."')";
				$pjListingModel->where("( 
											(`for` = 'sale' AND (`listing_price` BETWEEN ".$_GET['min_price']." AND ".$_GET['max_price']." ) ) 
											OR (`for` = 'rent' AND ( ($min_price_str BETWEEN ".$_GET['min_price']." AND ".$_GET['max_price'].") 
																  OR ($max_price_str BETWEEN ".$_GET['min_price']." AND ".$_GET['max_price'].") 
																  OR (".$_GET['min_price']." BETWEEN $min_price_str AND $max_price_str) 
																  OR (".$_GET['max_price']." BETWEEN $min_price_str AND $max_price_str)) 
											) 
										)");
			}
			
		}
		
		$orderby = 't1.is_featured DESC, t1.created DESC';
		
		$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;
		}
		
		$gallery_table = pjGalleryModel::factory()->getTable();
		$price_table = pjPriceModel::factory()->getTable();
		
		
		$arr = $pjListingModel
			->select(sprintf("t1.*, t2.content AS title, t1.expire, t1.status, t3.content as description,
					(SELECT MIN(price) FROM `".$price_table."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."') AS `min_price`,
					(SELECT MAX(price) FROM `".$price_table."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."') AS `max_price`,
					(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`,
					(SELECT `large_path` FROM `%s` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `large_image`", $gallery_table, $gallery_table, $gallery_table))
			->orderBy("$orderby")
			->limit($rowCount, $offset)
			->findAll()
			->getData();
		
		$paginator = array('pages' => $pages, 'total' => $total);
		
		$this->set('arr', $arr);
		$this->set('paginator', $paginator);
		
		$this->set('meta_arr', array(
				'title' => __('ws_yachts_meta_title', true),
				'keywords' => __('ws_yachts_meta_keywords', true),
				'description' => __('ws_yachts_meta_description', true),
		));
	}
	
	public function pjActionView()
	{
		$pjListingModel = pjListingModel::factory();
		$id = $_GET['id'];
		$monday = date('Y-m-d',strtotime('monday this week'));
		$arr = $pjListingModel
			->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('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.address_country AND t5.field='name' AND t5.locale='".$this->getLocaleId()."'", '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('pjUser', 't9.id=t1.owner_id', 'left')
			->join('pjMultiLang', "t10.model='pjFeature' AND t10.foreign_id=t1.feature_fuel_id AND t10.field='name' AND t10.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t11.model='pjFeature' AND t11.foreign_id=t1.feature_engine_id AND t11.field='name' AND t11.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t12.model='pjFeature' AND t12.foreign_id=t1.feature_hull_id AND t12.field='name' AND t12.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t13.model='pjFeature' AND t13.foreign_id=t1.feature_yacht_id AND t13.field='name' AND t13.locale='".$this->getLocaleId()."'", 'left')
			->select("t1.*, t2.content as manufacturer, t3.content as title, t4.content as description, t5.content as country_title,
						 t6.content AS meta_title, t7.content AS meta_keywords, t8.content AS meta_description, t9.name, t9.email, t9.phone, t9.fax,
						 t10.content as feature_fuel, t11.content as feature_engine, t12.content as feature_hull, t13.content as feature_yacht,
					(SELECT MIN(price) FROM `".pjPriceModel::factory()->getTable()."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."') AS `min_price`,
					(SELECT MAX(price) FROM `".pjPriceModel::factory()->getTable()."` AS TP1 WHERE TP1.listing_id=t1.id AND TP1.start_date>='".$monday."') AS `max_price`")
			 ->find($id)
			 ->getData();
			
		if(!empty($arr) && !empty($arr['title']))
		{
			$status = '200';
			if($arr['status'] == 'F')
			{
				$status = '101';
			}
			if($arr['status'] == 'E')
			{
				if($arr['expire'] < date('Y-m-d'))
				{
					$status = '102';
				}
			}
			if($status == '200')
			{
				$gallery_arr = pjGalleryModel::factory()->where('t1.foreign_id', $id)->orderBy('t1.sort ASC')->findAll()->getData();
					
				$listing_extra_arr = pjListingExtraModel::factory()
					->select('t1.*, t2.content AS name')
					->join('pjMultiLang', "t2.model='pjExtra' AND t2.foreign_id=t1.extra_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->where('t1.listing_id', $_GET['id'])
					->findAll()
					->getDataPair('extra_id', 'name');
								
				$pjListingModel->reset()->where('id', $id)->modifyAll(array('views' => $arr['views'] + 1));

				if($arr['for'] == 'rent')
				{
					$month = date('Y-m');
					if($this->_is('week'))
					{
						$month = date('Y-m', $this->_get('week'));
					}
					$this->set('price_arr', pjPriceModel::factory()->getPricesByMonth($arr['id'], $month));
					$booking_arr = pjBookingModel::factory()
						->where('listing_id', $arr['id'])
						->where('status', 'confirmed')
						->where("DATE_FORMAT(t1.week_start,'%Y-%m')", $month)
						->orderBy("week_start ASC")
						->findAll()
						->getDataPair("id", "week_start");
					$this->set('booking_arr', $booking_arr);
				}
				
				$this->set('meta_arr', array(
						'title' => !empty($arr['meta_title']) ? $arr['meta_title'] : __('ws_details_meta_title', true),
						'keywords' => !empty($arr['meta_keywords']) ? $arr['meta_keywords'] : __('ws_details_meta_keywords', true),
						'description' => !empty($arr['meta_description']) ? $arr['meta_description'] : __('ws_details_meta_description', true)
				));
				
				$this->set('arr', $arr);
				$this->set('gallery_arr', $gallery_arr);
				$this->set('listing_extra_arr', $listing_extra_arr);
			}
		}else{
			$status = '103';
		}
		$this->set('status', $status);
	}
	
	public function pjActionSearch()
	{
		$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')
			->where("t1.id IN (SELECT TL.manufacturer_id FROM `".pjListingModel::factory()->getTable()."` AS TL)")
			->orderBy('name ASC')
			->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('manufacturer_arr', pjSanitize::clean($manufacturer_arr));
		$this->set('feature_arr', $feature_arr);
	}
	
	public function pjActionAccount()
	{
		if ($this->option_arr['o_allow_add_listing'] == 'Yes')
		{
			$this->set('meta_arr', array(
					'title' => __('ws_account_meta_title', true),
					'keywords' => __('ws_account_meta_keywords', true),
					'description' => __('ws_account_meta_description', true),
			));
			if(isset($_POST['register']))
			{
				if (!isset($_POST['name']))
				{
					$err = 101;
				}
				if (!isset($_POST['email']))
				{
					$err = 102;
				}
				if (!isset($_POST['password']))
				{
					$err = 103;
				}
				if (!isset($_POST['reenter_password']))
				{
					$err = 104;
				}
				if (!isset($_POST['captcha']))
				{
					$err = 111;
				}
				if (isset($_POST['name']) && !pjValidation::pjActionNotEmpty($_POST['name']))
				{
					$err = 105;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
				{
					$err = 106;
				}
				if (isset($_POST['password']) && !pjValidation::pjActionNotEmpty($_POST['password']))
				{
					$err = 107;
				}
				if (isset($_POST['reenter_password']) && !pjValidation::pjActionNotEmpty($_POST['reenter_password']))
				{
					$err = 108;
				}
				if (isset($_POST['captcha']) && !pjValidation::pjActionNotEmpty($_POST['captcha']))
				{
					$err = 112;
				}
				if (isset($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
				{
					$err = 109;
				}
				if (isset($_POST['password']) && isset($_POST['reenter_password']) && !pjValidation::pjActionEqualTo($_POST['reenter_password'], $_POST['password']))
				{
					$err = 110;
				}
				if ($_SESSION[$this->defaultCaptcha] == "" || $_POST['captcha'] == "" || strtoupper($_POST['captcha']) != $_SESSION[$this->defaultCaptcha])
				{
					$err = 113;
				}
				if (!isset($err))
				{
					$data = array();
					$data['role_id'] = 3;
					$data['is_active'] = 'T';
					$data['status'] = $this->option_arr['o_owner_is_active'] == 'Yes' ? 'T' : 'F';
					$data['ip'] = pjUtil::getClientIp();
	
					$id = pjUserModel::factory()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
					if ($id !== false && (int) $id > 0)
					{
						$pjOptionModel = pjOptionModel::factory();
						$pjOptionModel->init($id);
						$pjOptionModel->initMultiLang($id, 3);
						pjListings::pjActionRegistrationEmail($id);
						
						$url = sprintf("%s?controller=%s&action=pjActionAccount&status=", $_SERVER['PHP_SELF'], $_GET['controller']);
						if (PJ_IS_WEBSITE && $this->option_arr['o_website_seo'] == 'Yes')
						{
							$url = $_SERVER['REDIRECT_URL'] . '?status=';
						}
						if ($this->option_arr['o_owner_is_active'] == 'Yes')
						{
							pjUtil::redirect($url . 200);
						}else{
							pjUtil::redirect($url . 201);
						}
					}
				}else{
					$this->set('err', $err);
				}
			}
		}else{
			pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionIndex");
		}
	}
	
	public function pjActionForgot()
	{
		if(isset($_POST['forgot']))
		{
			if (!isset($_POST['email']))
			{
				$err = 101;
			}
			if (isset($_POST['email']) && !pjValidation::pjActionNotEmpty($_POST['email']))
			{
				$err = 102;
			}
			if (isset($_POST['email']) && !pjValidation::pjActionEmail($_POST['email']))
			{
				$err = 103;
			}
			if (!isset($err))
			{
				$arr = pjUserModel::factory()
					->where('t1.email', $_POST['email'])
					->limit(1)
					->findAll()
					->getData();
				if(empty($arr))
				{
					$err = 104;
				}
				if (!isset($err))
				{
					pjListings::pjActionForgotEmail($arr[0]['id']);
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionForgot&status=200");
				}else{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionForgot&err=$err");
				}
			}else{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=".$_GET['controller']."&action=pjActionForgot&err=$err");
			}
		}
	}
	
	public function pjActionReserve()
	{
		$pjListingModel = pjListingModel::factory();
		
		if(isset($_POST['reserve']))
		{
			if ((int) $this->option_arr['o_bf_include_captcha'] === 3 && (!isset($_POST['captcha']) ||
					!pjCaptcha::validate($_POST['captcha'], $_SESSION[$this->defaultCaptcha]) ))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 110, 'text' => __('system_110', true)));
			}
			
			$code = 200;
			
			if((int) $this->option_arr['o_bf_include_title'] === 3 && !isset($_POST['c_title']))
			{
				$code = 101;
			}
			if((int) $this->option_arr['o_bf_include_title'] === 3 && isset($_POST['c_title']) && !pjValidation::pjActionNotEmpty($_POST['c_title']))
			{
				$code = 102;
			}
			if((int) $this->option_arr['o_bf_include_name'] === 3 && !isset($_POST['c_name']))
			{
				$code = 103;
			}
			if((int) $this->option_arr['o_bf_include_name'] === 3 && isset($_POST['c_name']) && !pjValidation::pjActionNotEmpty($_POST['c_name']))
			{
				$code = 104;
			}
			if((int) $this->option_arr['o_bf_include_email'] === 3 && !isset($_POST['c_email']))
			{
				$code = 105;
			}
			if((int) $this->option_arr['o_bf_include_email'] === 3 && isset($_POST['c_email']) && !pjValidation::pjActionNotEmpty($_POST['c_email']))
			{
				$code = 106;
			}
			if(isset($_POST['c_email']) && !pjValidation::pjActionEmail($_POST['c_email']))
			{
				$code = 107;
			}
			if((int) $this->option_arr['o_bf_include_phone'] === 3 && !isset($_POST['c_phone']))
			{
				$code = 108;
			}
			if((int) $this->option_arr['o_bf_include_phone'] === 3 && isset($_POST['c_phone']) && !pjValidation::pjActionNotEmpty($_POST['c_phone']))
			{
				$code = 109;
			}
			if((int) $this->option_arr['o_bf_include_company'] === 3 && !isset($_POST['c_company']))
			{
				$code = 110;
			}
			if((int) $this->option_arr['o_bf_include_company'] === 3 && isset($_POST['c_company']) && !pjValidation::pjActionNotEmpty($_POST['c_company']))
			{
				$code = 111;
			}
			if((int) $this->option_arr['o_bf_include_address'] === 3 && !isset($_POST['c_address']))
			{
				$code = 112;
			}
			if((int) $this->option_arr['o_bf_include_address'] === 3 && isset($_POST['c_address']) && !pjValidation::pjActionNotEmpty($_POST['c_address']))
			{
				$code = 113;
			}
			if((int) $this->option_arr['o_bf_include_country'] === 3 && !isset($_POST['c_country']))
			{
				$code = 114;
			}
			if((int) $this->option_arr['o_bf_include_country'] === 3 && isset($_POST['c_country']) && !pjValidation::pjActionNotEmpty($_POST['c_country']))
			{
				$code = 115;
			}
			if((int) $this->option_arr['o_bf_include_state'] === 3 && !isset($_POST['c_state']))
			{
				$code = 116;
			}
			if((int) $this->option_arr['o_bf_include_state'] === 3 && isset($_POST['c_state']) && !pjValidation::pjActionNotEmpty($_POST['c_state']))
			{
				$code = 117;
			}
			if((int) $this->option_arr['o_bf_include_city'] === 3 && !isset($_POST['c_city']))
			{
				$code = 118;
			}
			if((int) $this->option_arr['o_bf_include_city'] === 3 && isset($_POST['c_city']) && !pjValidation::pjActionNotEmpty($_POST['c_city']))
			{
				$code = 119;
			}
			if((int) $this->option_arr['o_bf_include_zip'] === 3 && !isset($_POST['c_zip']))
			{
				$code = 120;
			}
			if((int) $this->option_arr['o_bf_include_zip'] === 3 && isset($_POST['c_zip']) && !pjValidation::pjActionNotEmpty($_POST['c_zip']))
			{
				$code = 121;
			}
			if((int) $this->option_arr['o_bf_include_notes'] === 3 && !isset($_POST['c_notes']))
			{
				$code = 122;
			}
			if((int) $this->option_arr['o_bf_include_notes'] === 3 && isset($_POST['c_notes']) && !pjValidation::pjActionNotEmpty($_POST['c_notes']))
			{
				$code = 123;
			}
			if($code != 200)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => $code, 'text' => $code));
			}else{
				$pjBookingModel = pjBookingModel::factory();
				
				$price_arr = pjPriceModel::factory()
					->where('t1.listing_id', $_POST['listing_id'])
					->where('t1.start_date', $_POST['week_start'])
					->findAll()
					->getData();
				if(count($price_arr) == 0)
				{
					pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 124, 'text' => __('system_124', true)));
				}else{
					$b_arr = $pjBookingModel
						->where('t1.listing_id', $_POST['listing_id'])
						->where('t1.week_start', $_POST['week_start'])
						->where('t1.status', 'confirmed')
						->findAll()
						->getData();
					if(count($b_arr) > 0)
					{
						pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 124, 'text' => __('system_124', true)));
					}
				}
				
				$data = array();
					
				$uuid = pjUtil::uuid();
				$data['uuid'] = $uuid;
				$data['status'] = $this->option_arr['o_booking_status'];
				$data['ip'] = pjUtil::getClientIp();
				
				$payment = 'none';
				if(isset($_POST['payment_method']))
				{
					if (isset($_POST['payment_method'])){
						$payment = $_POST['payment_method'];
					}
				}
									
				$id = $pjBookingModel->reset()->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$pdata = array();
					$pdata['booking_id'] = $id;
					$pdata['payment_method'] = $payment;
					$pdata['payment_type'] = 'online';
					$pdata['amount'] = $_POST['deposit'];
					$pdata['status'] = 'notpaid';
					pjBookingPaymentModel::factory()->setAttributes($pdata)->insert();
					
					$arr = $pjBookingModel
						->reset()
						->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
						->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
						->select('t1.*, t2.content as title, t3.content as country_title')
						->find($id)
						->getData();
					
					pjListings::pjActionConfirmSend($this->option_arr, $arr, PJ_SALT, 'confirm');
					unset($_SESSION[$this->defaultStore]);
					$json = array('code' => 200, 'text' => '', 'booking_id' => $id, 'listing_id' => $_POST['listing_id'], 'payment' => $payment);
					pjAppController::jsonResponse($json);
				}else{
					pjAppController::jsonResponse(array('code' => 'ERR', 'code' => 100, 'text' => __('system_100', true)));
				}
			}
		}else{
			$id = $_GET['id'];
			$arr = $pjListingModel
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->select('t1.*, t2.content as title, 
						(SELECT `small_path` FROM `'.pjGalleryModel::factory()->getTable().'` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `image`,
						(SELECT `medium_path` FROM `'.pjGalleryModel::factory()->getTable().'` WHERE foreign_id = t1.id ORDER BY `sort` ASC LIMIT 1) AS `medium`')
				->find($id)
				->getData();
				
			if(!empty($arr) && !empty($arr['title']))
			{
				$status = '200';
				if($arr['status'] == 'F')
				{
					$status = '101';
				}
				if($arr['status'] == 'E')
				{
					if($arr['expire'] < date('Y-m-d'))
					{
						$status = '102';
					}
				}
				if($status == '200')
				{
					$this->_set('week', $_GET['week']);
					
					$price_arr = pjAppController::calPrices($id, $_GET['week'], $this->option_arr);
					$this->set('price_arr', $price_arr);
					
					$this->set('country_arr', pjCountryModel::factory()
							->select('t1.*, t2.content AS name')
							->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
							->where('t1.status', 'T')
							->orderBy('`name` ASC')
							->findAll()
							->getData()
					);
				}
				
				$this->set('arr', $arr);
			}else{
				$status = '103';
			}
			$this->set('status', $status);
		}
	}
	
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjBookingModel::factory()
			    ->join('pjListing', 't2.id=t1.listing_id', 'left outer')
				->join('pjMultiLang', "t3.model='pjListing' AND t3.foreign_id=t1.listing_id AND t3.field='title' AND t3.locale='".$this->getLocaleId()."'", 'left')
				->select('t1.*, t2.owner_id, t3.content as title')
				->find($_GET['booking_id'])
				->getData();
			$foreign_id = (int)$arr['owner_id'] > 0 ? (int)$arr['owner_id'] : $this->getForeignId();
			if (!empty($arr))
			{
				switch ($arr['payment_method'])
				{
					case 'paypal':
						$this->set('params', array(
							'name' => 'ylPaypal',
							'id' => 'ylPaypal',
							'business' => $this->option_arr['o_owner_paypal_address'],
							'client_id' => $this->option_arr['o_owner_paypal_client_id'],
							'client_secret' => $this->option_arr['o_owner_paypal_client_secret'],
							'item_name' => pjSanitize::html($arr['title']),
							'custom' => $arr['id'],
							'amount' => $arr['deposit'],
							'currency_code' => $this->option_arr['o_currency'],
							'foreign_id' => $foreign_id,
							'payto' => 'owner',
							'return' => $this->option_arr['o_thank_you_page'],
							'failure_url' => $this->option_arr['o_owner_paypal_cancel_url'],
							'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjListings&action=pjActionConfirmPaypal&payto=owner&id='.$arr['listing_id'],						
							'target' => '_self',
							'charset' => 'utf-8'
						));
						break;
					case 'authorize':
						$this->set('params', array(
							'name' => 'ylAuthorize',
							'id' => 'ylAuthorize',
							'target' => '_self',							
							'timezone' => $this->option_arr['o_authorize_timezone'],
							'transkey' => $this->option_arr['o_authorize_transkey'],
							'private_key' => $this->option_arr['o_authorize_md5_hash'],
							'x_login' => $this->option_arr['o_authorize_merchant_id'],							
							'x_description' => pjSanitize::html($arr['title']),
							'x_amount' => $arr['deposit'],
							'x_invoice_num' => $arr['id'].'-'.$arr['listing_id'],
							'x_receipt_link_url' => $this->option_arr['o_thank_you_page'],
							'x_relay_url' => PJ_INSTALL_URL . 'index.php?controller=pjListings&action=pjActionConfirmAuthorize'
						));
						break;
				}
			}
			$this->set('arr', $arr);
			$this->set('get', $_GET);
		}
	}
	
	public function pjActionCancel()
	{
		$this->setLayout('pjActionCancel');
	
		$pjBookingModel = pjBookingModel::factory();
	
		if (isset($_POST['booking_cancel']))
		{
			$booking_arr = pjBookingModel::factory()
				->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
				->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
				->select('t1.*, t2.content as title, t3.content as country_title')
				->find($_POST['id'])
				->getData();
			if (count($booking_arr) > 0)
			{
				$sql = "UPDATE `".$pjBookingModel->getTable()."` SET status = 'cancelled' WHERE SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
	
				$pjBookingModel->reset()->execute($sql);
	
				pjListings::pjActionConfirmSend($this->option_arr, $booking_arr, PJ_SALT, 'cancel');
	
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjListings&action=pjActionCancel&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = pjBookingModel::factory()
					->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
					->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
					->select("t1.*,
							AES_DECRYPT(t1.cc_type, '".PJ_SALT."') AS `cc_type`,
							AES_DECRYPT(t1.cc_num, '".PJ_SALT."') AS `cc_num`,
							AES_DECRYPT(t1.cc_exp_month, '".PJ_SALT."') AS `cc_exp_month`,
							AES_DECRYPT(t1.cc_exp_year, '".PJ_SALT."') AS `cc_exp_year`,
							AES_DECRYPT(t1.cc_code, '".PJ_SALT."') AS `cc_code`, 
							t2.content as title, t3.content as country_title")
					->find($_GET['id'])
					->getData();
				
				if (count($arr) == 0)
				{
					$this->set('status', 2);
				}else{
					if ($arr['status'] == 'cancelled')
					{
						$this->set('status', 4);
					}else{
						$hash = sha1($arr['id'] . $arr['created'] . PJ_SALT);
						if ($_GET['hash'] != $hash)
						{
							$this->set('status', 3);
						}else{
	
							$this->set('arr', $arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
	
	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'],
		    'foreign_id' => 1,
		    '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')
			{
				$current = strtotime($listing_arr['expire']);
			}
			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 pjActionConfirmAuthorize()
	{
		$this->setAjax(true);
	   if (pjObject::getPlugin('pjAuthorize') === NULL)
		{
			$this->log('Authorize.NET plugin not installed');
			exit;
		}
	
		list($booking_id, $listing_id) = explode('-', $_REQUEST['x_invoice_num']);
		$pjBookingModel = pjBookingModel::factory();
		$arr = $pjBookingModel
			->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->select('t1.*, t2.content as title, t3.content as country_title')
			->find($booking_id)
			->getData();
	
		if (!empty($arr))
		{
			if (count($arr) == 0)
			{
				$this->log('No such booking');
				pjUtil::redirect($this->option_arr['o_thank_you_page']);
			}

			if (count($arr) > 0)
			{
				$params = array(
				    'x_login' => $this->option_arr['o_authorize_merchant_id'],
				    'transkey' => $this->option_arr['o_authorize_transkey'],
				    'private_key' => $this->option_arr['o_authorize_md5_hash'],
				    'key' => md5($this->option_arr['private_key'] . PJ_SALT)
				);
				
				$response = $this->requestAction(array('controller' => 'pjAuthorize', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
				if ($response !== FALSE && $response['status'] === 'OK')
				{
					$pjBookingModel
					->reset()->set('id', $booking_id)
					->modify(array('status' => $this->option_arr['o_payment_status'], 'processed_on' => ':NOW()'));

					pjBookingPaymentModel::factory()->where('booking_id', $booking_id)->where('payment_type', 'online')->limit(1)->modifyAll(array('status' => 'paid'));
					
					pjListings::pjActionConfirmSend($this->option_arr, $arr, PJ_SALT, 'payment');

				} elseif (!$response) {
					$this->log('Authorization failed');
				} else {
					$this->log('Booking not confirmed. ' . $response['response_reason_text']);
				}
				$url = $this->option_arr['o_thank_you_page'];
				echo '<html><head><title></title><script type="text/javascript">window.location.href="'.$url.'";</script></head><body></body></html>';
				exit;
			}
			
		}else{
			$this->log('No such booking');
		}
	}
	
	public function pjActionConfirmPaypal()
	{
		$this->setAjax(true);
	
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Paypal plugin not installed'));
		}
		$request = $_REQUEST;
		$input = file_get_contents('php://input');
		$post = json_decode($input, true);
		if ($post) {
		    $request = array_merge($request, $post);
		}
		
		$pjBookingModel = pjBookingModel::factory();
		$arr = $pjBookingModel
			->join('pjMultiLang', "t2.model='pjListing' AND t2.foreign_id=t1.listing_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left')
			->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", 'left')
			->join('pjListing', 't4.id=t1.listing_id', 'left outer')
			->select('t1.*, t2.content as title, t3.content as country_title, t4.owner_id')
			->find($request['custom'])
			->getData();
		if (!empty($arr))
		{
			if (count($arr) == 0)
			{
				$this->log('No such booking');
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'No such booking'));
			}
			$foreign_id = (int)$arr['owner_id'] > 0 ? (int)$arr['owner_id'] : $this->getForeignId();
			$params = array(
			    'request'		=> $request,
			    'cancel_hash'	=> sha1($arr['uuid'].strtotime($arr['created']).PJ_SALT),
			    'txn_id' => @$arr['txn_id'],
			    'paypal_address' => $this->option_arr['o_owner_paypal_address'],
			    'deposit' => @$arr['deposit'],
			    'currency' => $this->option_arr['o_currency'],
			    'foreign_id' => $foreign_id,
			    'key' => md5($this->option_arr['private_key'] . PJ_SALT)
			);
			if (isset($request['payto'])) {
			    $params['payto'] = $request['payto'];
			}
			$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));		
			if ($response !== FALSE && $response['status'] === 'OK')
			{
				$this->log('Booking confirmed');
				
				$pjBookingModel
					->reset()
					->where('id', $arr['id'])
					->limit(1)
					->modifyAll(array(
						'status' => $this->option_arr['o_payment_status'],
						'txn_id' => $response['transaction_id'],
						'processed_on' => ':NOW()'
					));
				
				pjBookingPaymentModel::factory()->where('booking_id', $arr['id'])->where('payment_type', 'online')->limit(1)->modifyAll(array('status' => 'paid'));
						
				pjListings::pjActionConfirmSend($this->option_arr, $arr, PJ_SALT, 'payment');
				pjAppController::jsonResponse(array('status' => 'OK', 'text' => 'Booking confirmed'));
			} elseif (!$response) {
				$this->log('Authorization failed');
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Authorization failed'));
			} else {
				$this->log('Booking not confirmed');
				pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'Booking not confirmed'));
			}
		}else{
			$this->log('No such booking');
			pjAppController::jsonResponse(array('status' => 'ERR', 'text' => 'No such booking'));
		}
	}
	
	public function pjActionGetMonth()
	{
		$this->setAjax(true);
		
		if(isset($_GET['id']) && (int) $_GET['id'])
		{
			$this->set('price_arr', pjPriceModel::factory()->getPricesByMonth($_GET['id'], date('Y-m', $_GET['month'])));
			$booking_arr = pjBookingModel::factory()
				->where('listing_id', $_GET['id'])
				->where('status', 'confirmed')
				->where("DATE_FORMAT(t1.week_start,'%Y-%m')", date('Y-m', $_GET['month']))
				->orderBy("week_start ASC")
				->findAll()
				->getDataPair("id", "week_start");
			$this->set('booking_arr', $booking_arr);
		}else{
			echo '100';
			exit;
		}
	}
	
	public function pjActionRegistrationEmail($id)
	{
		$arr = pjUserModel::factory()->find($id)->getData();
		if(!empty($arr))
		{
			$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();
			$search = array("{Name}", "{Email}", "{Password}", "{Phone}");
			$replace = array($arr['name'], $arr['email'], $arr['password'], $arr['phone']);
				
			$pjMultiLangModel = pjMultiLangModel::factory();
			if ($this->option_arr['o_email_registration'] == 1 && $arr['email'] != '')
			{
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_registration_subject')
					->limit(0, 1)
					->findAll()->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_registration_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($arr['email'])
						->setFrom($from)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($message));
				}
			}
			if ($this->option_arr['o_admin_email_registration'] == 1)
			{
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_email_registration_subject')
					->limit(0, 1)
					->findAll()->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_admin_email_registration_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($arr['phone']) && $this->option_arr['o_sms_registration'] == 1)
			{
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_sms_registration_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'] = $arr['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_registration'] == 1)
			{
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_sms_registration_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 pjActionForgotEmail($id)
	{
		$arr = pjUserModel::factory()->find($id)->getData();
		if(!empty($arr))
		{
			$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();
			$search = array("{Name}", "{Password}");
			$replace = array($arr['name'], $arr['password']);
	
			if ($arr['email'] != '')
			{
				$pjMultiLangModel = pjMultiLangModel::factory();
				$lang_subject = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_forgot_subject')
					->limit(0, 1)
					->findAll()->getData();
				$lang_message = $pjMultiLangModel
					->reset()
					->select('t1.*')
					->where('foreign_id', 1)
					->where('t1.model','pjOption')
					->where('t1.locale', $this->getLocaleId())
					->where('t1.field', 'o_email_forgot_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($arr['email'])
						->setFrom($from)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($message));
				}
			}
		}
	}
	
	public function pjActionConfirmSend($option_arr, $booking_arr, $salt, $opt)
	{
		$Email = new pjEmail();
		if ($option_arr['o_send_email'] == 'smtp')
		{
			$Email
				->setTransport('smtp')
				->setSmtpHost($option_arr['o_smtp_host'])
				->setSmtpPort($option_arr['o_smtp_port'])
				->setSmtpUser($option_arr['o_smtp_user'])
				->setSmtpPass($option_arr['o_smtp_pass'])
				->setSender($option_arr['o_smtp_user'])
			;
		}
		$Email->setContentType('text/html');
	
		$admin_email = $this->getAdminEmail();
		$from_email = $admin_email;
		$owner_email = null;
		$owner_phone = null;
		$foreign_id = 1;
		
		$listing_arr = pjListingModel::factory()->find($booking_arr['listing_id'])->getData();
		if(!empty($listing_arr['owner_id']))
		{
			$owner = pjUserModel::factory()->find($listing_arr['owner_id'])->getData();
			$foreign_id = $listing_arr['owner_id'];
			if(!empty($owner['email']))
			{
				$owner_email = $owner['email'];
			}
			if(!empty($owner['phone']))
			{
				$owner_phone = $owner['phone'];
			}
		}
		
		$tokens = pjAppController::getData($option_arr, $booking_arr, PJ_SALT, $this->getLocaleId());
	
		$pjMultiLangModel = pjMultiLangModel::factory();
	
		$locale_id = isset($booking_arr['locale_id']) && (int) $booking_arr['locale_id'] > 0 ? (int) $booking_arr['locale_id'] : $this->getLocaleId();
	
		if ($option_arr['o_email_payment'] == 1 && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_payment_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']) && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($booking_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
			}
		}
		if ($option_arr['o_owner_email_payment'] == 1 && $opt == 'payment' && $owner_email != null)
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_email_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_email_payment_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']) && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($owner_email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
			}
		}
		if(!empty($owner_phone) && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_sms_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1 && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				if($message != '')
				{
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $owner_phone;
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
	
		if ($option_arr['o_email_confirmation'] == 1 && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_confirmation_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']) && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
					
				$Email
					->setTo($booking_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
			}
		}
		if ($option_arr['o_owner_email_confirmation'] == 1 && $opt == 'confirm' && $owner_email != null)
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_email_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_email_confirmation_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']) && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				$Email
					->setTo($owner_email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
			}
		}
		if(!empty($booking_arr['c_phone']) && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_sms_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1 && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				if($message != '')
				{
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $booking_arr['c_phone'];
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
		if(!empty($owner_phone) && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_sms_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1 && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				if($message != '')
				{
					$params = array(
							'text' => $message,
							'type' => 'unicode',
							'key' => md5($option_arr['private_key'] . PJ_SALT)
					);
					$params['number'] = $owner_phone;
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
	
		if ($option_arr['o_email_cancel'] == 1 && $opt == 'cancel')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_cancel_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_email_cancel_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']) && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($booking_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
			}
		}
		if ($option_arr['o_owner_email_cancel'] == 1 && $opt == 'cancel' && $owner_email != null)
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_email_cancel_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('foreign_id', $foreign_id)
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_owner_email_cancel_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']) && !empty($lang_message[0]['content']))
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($owner_email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
			}
		}
	}
}
?>