<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjCarPark_Captcha';
	
	public $defaultLocale = 'pjCarPark_LocaleId';
	
	public $defaultStore = 'pjCarPark_Store';
	
	public $defaultForm = 'pjCarPark_Form';
	
	public $defaultFieldsIndex = 'fields_index';
	
	public $defaultFields = 'front_fields';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
		self::allowCORS();
		
	}

	public function isXHR()
	{
		// CORS
		return parent::isXHR() || isset($_SERVER['HTTP_ORIGIN']);
	}
	protected static function allowCORS()
	{
	    $install_url = parse_url(PJ_INSTALL_URL);
	    if($install_url['scheme'] == 'https'){
	        header('Set-Cookie: '.session_name().'='.session_id().'; SameSite=None; Secure');
	    }
	    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
	    header('P3P: CP="ALL DSP COR CUR ADM TAI OUR IND COM NAV INT"');
	    header("Access-Control-Allow-Origin: $origin");
	    header("Access-Control-Allow-Credentials: true");
	    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
	    header("Access-Control-Allow-Headers: Origin, X-Requested-With");
	    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
	    {
	        exit;
	    }
	}
	
	private function _get($key)
	{
		if ($this->_is($key))
		{
			return $_SESSION[$this->defaultStore][$key];
		}
		return false;
	}
	
	private function _is($key)
	{
		return isset($_SESSION[$this->defaultStore]) && isset($_SESSION[$this->defaultStore][$key]);
	}
	
	private function _set($key, $value)
	{
		$_SESSION[$this->defaultStore][$key] = $value;
		return $this;
	}
	
	private function _unset($key)
	{
		if ($this->_is($key))
		{
			unset($_SESSION[$this->defaultStore][$key]);
		}
		return $this;
	}
	
	public function afterFilter()
	{		
		if (!$this->_get->check('hide') || ($this->_get->check('hide') && $this->_get->toInt('hide') !== 1) &&
	        in_array($this->_get->toString('action'), array('pjActionSearch', 'pjActionSpaces', 'pjActionExtras', 'pjActionCheckout', 'pjActionPreview', 'pjActionGetPaymentForm')))
	    {
	        $locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file, t2.title')
	        ->join('pjBaseLocaleLanguage', 't2.iso=t1.language_iso', 'left')
	        ->where('t2.file IS NOT NULL')
	        ->orderBy('t1.sort ASC')->findAll()->getData();
	        
	        $this->set('locale_arr', $locale_arr);
	    }
	}
	
	public function beforeFilter()
	{
		$cid = $this->getForeignId();
        $this->models['Option'] = pjBaseOptionModel::factory();
	    $base_option_arr = $this->models['Option']->getPairs($cid);
	    $script_option_arr = pjOptionModel::factory()->getPairs($cid);
	    $this->option_arr = array_merge($base_option_arr, $script_option_arr);
	    $this->set('option_arr', $this->option_arr);

		if (!in_array($this->_get->toString('action'), array('pjActionLoadCss')))
		{
			if($this->_get->toInt('locale') > 0 && $this->_get->toInt('locale') != $this->pjActionGetLocale())
		    {
		        $this->setLocaleId($this->_get->toInt('locale'));
				$this->loadSetFields(true);
		    } else {
		    	if($this->_get->toString('action') == 'pjActionLoad')
				{
					$this->loadSetFields(true);
				}else{
					$this->loadSetFields();
				}	
		    }
		}
		if (!isset($_SESSION[$this->defaultLocale]))
		{
			$locale_arr = pjLocaleModel::factory()->where('is_default', 1)->limit(1)->findAll()->getData();
			if (count($locale_arr) === 1)
			{
				$this->setLocaleId($locale_arr[0]['id']);
				$this->loadSetFields(true);
			}
		}
		$is_ip_blocked = pjBase::isBlockedIp(pjUtil::getClientIp(), $this->option_arr);
		if($is_ip_blocked == true && !(in_array($this->_get->toString('controller'), array('pjFront')) && in_array($this->_get->toString('action'), array('pjActionLoad', 'pjActionLoadCss', 'pjActionIpBlocked'))))
		{
		    self::jsonResponse(array('status' => 'ERR', 'code' => 400, 'text' => ''));
		}
		
		return parent::beforeFilter();
	}
	
	public function beforeRender()
	{
		if ($this->_get->check('iframe'))
		{
			$this->setLayout('pjActionIframe');
		}
	}
	
	public function pjActionLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$get = $this->_get->raw();
			if (isset($get['locale_id']))
			{
				$this->pjActionSetLocale($get['locale_id']);				
				$this->loadSetFields(true);
				
				$day_names = __('day_names', true);
				ksort($day_names, SORT_NUMERIC);
				
				$months = __('months', true);
				ksort($months, SORT_NUMERIC);
				
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Locale have been changed.', 'opts' => array(
					'day_names' => array_values($day_names),
					'month_names' => array_values($months)
				)));
			}
		}
		exit;
	}
	private function pjActionSetLocale($locale)
	{
		if ((int) $locale > 0)
		{
			$_SESSION[$this->defaultLocale] = (int) $locale;
		}
		return $this;
	}
	
	public function pjActionGetLocale()
	{
		return isset($_SESSION[$this->defaultLocale]) && (int) $_SESSION[$this->defaultLocale] > 0 ? (int) $_SESSION[$this->defaultLocale] : FALSE;
	}
	
	public function pjActionCaptcha()
	{
	    $this->setAjax(true);
	    
	    header("Cache-Control: max-age=3600, private");
	    $rand = $this->_get->toInt('rand') ? $this->_get->toInt('rand') : rand(1, 9999);
	    $patterns = 'app/web/img/button.png';
	    if(!empty($this->option_arr['o_captcha_background_front']) && $this->option_arr['o_captcha_background_front'] != 'plain')
	    {
	        $patterns = PJ_INSTALL_PATH . $this->getConstant('pjBase', 'PLUGIN_IMG_PATH') . 'captcha_patterns/' . $this->option_arr['o_captcha_background_front'];
	    }
	    $Captcha = new pjCaptcha(PJ_INSTALL_PATH . $this->getConstant('pjBase', 'PLUGIN_WEB_PATH') . 'obj/arialbd.ttf', $this->defaultCaptcha, (int) $this->option_arr['o_captcha_length_front']);
	    $Captcha->setImage($patterns)->setMode($this->option_arr['o_captcha_mode_front'])->init($rand);
	    exit;
	}
	
	public function pjActionCheckCaptcha()
	{
	    $this->setAjax(true);
	    if (!$this->_get->check('captcha') || !$this->_get->toString('captcha') || !pjCaptcha::validate($this->_get->toString('captcha'), $_SESSION[$this->defaultCaptcha])){
	        echo 'false';
	    }else{
	        echo 'true';
	    }
	    exit;
	}
	
	public function pjActionCheckReCaptcha()
	{
	    $this->setAjax(true);
	    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$this->option_arr['o_captcha_secret_key_front'].'&response='.$this->_get->toString('recaptcha'));
	    $responseData = json_decode($verifyResponse);
	    echo $responseData->success ? 'true': 'false';
	    exit;
	}
	
	public function pjActionLoadCss()
	{
		$this->setLayout('pjActionEmpty');
		$dm = new pjDependencyManager(null, PJ_THIRD_PARTY_PATH);
		$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
		
		$get = $this->_get->raw();
		$theme = isset($get['theme']) ? $get['theme'] : $this->option_arr['o_theme'];
		if((int) $theme > 0)
		{
			$theme = 'theme' . $theme;
		}
		$arr = array(
			array('file' => 'jquery-ui.custom.min.css', 'path' => $dm->getPath('pj_jquery_ui') . 'css/smoothness/'),
			array('file' => 'font-awesome.min.css', 'path' => $dm->getPath('font_awesome') . 'css/'),
		    array('file' => 'bootstrap-datetimepicker.min.css', 'path' => $dm->getPath('pj_bootstrap_datetimepicker')),
			array('file' => 'pjCarParkBooking.css', 'path' => PJ_CSS_PATH),
			array('file' => "$theme.css", 'path' => PJ_CSS_PATH.'themes/')
		);
		header("Content-Type: text/css; charset=utf-8");
		foreach ($arr as $item)
		{
			ob_start();
			@readfile($item['path'] . $item['file']);
			$string = ob_get_contents();
			ob_end_clean();
				
			if ($string !== FALSE)
			{
				echo str_replace(
						array('../img/', '../fonts/glyphicons', '../fonts/fontawesome', 'images/', "pjWrapper"),
						array(
								PJ_INSTALL_URL . PJ_IMG_PATH,
								PJ_INSTALL_URL . PJ_FRAMEWORK_LIBS_PATH . 'pj/fonts/glyphicons',
								PJ_INSTALL_URL . $dm->getPath('font_awesome') . 'fonts/fontawesome',
								PJ_INSTALL_URL . $dm->getPath('pj_jquery_ui') . 'css/smoothness/images/',
								"pjWrapperCarParkBooking_" . $theme
						),
						$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		$this->setAjax(false);
	    $this->setLayout('pjActionFront');
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	
	public function pjActionSetDateTimes()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$post = $this->_post->raw();
			if (isset($post['from']))
			{
			    $from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			    $to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			    $from_ts = $from_arr['ts'];
			    $to_ts = $to_arr['ts'];
			    if($from_ts < time())
			    {
			        pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101));
			    }
			    if($to_ts < time())
			    {
			        pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102));
			    }
			    if($from_ts >= $to_ts)
			    {
			        pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 103));
			    }
			    $this->_set('from', $from_arr['iso_date_time']);
			    $this->_set('to', $to_arr['iso_date_time']);
			    
			    pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200));
			}
		}
		exit;
	}
	
	public function pjActionHandleExtras()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$get = $this->_get->raw();
			if (isset($get['extra_id']) && (int) $get['extra_id'] > 0)
			{
				if (!$this->_is('extras'))
				{
					$this->_set('extras', array());
				}
				if (!isset($_SESSION[$this->defaultStore]['extras'][$get['extra_id']]))
				{
					$_SESSION[$this->defaultStore]['extras'][$get['extra_id']] = 0;
				}
				if((int) $get['cnt'] > 0)
				{
					$_SESSION[$this->defaultStore]['extras'][$get['extra_id']] = (int) $get['cnt'];
				}else{
					unset($_SESSION[$this->defaultStore]['extras'][$get['extra_id']]);
				}
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200));
			}
		}
		exit;
	}
	
	public function pjActionAddPromo()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$get = $this->_get->raw();
			if(isset($get['code']))
			{
				$from = $this->_get("from");
				$to = $this->_get("to");
				
				$from_ts = strtotime($from);
				$to_ts = strtotime($to);
				
				$iso_from = date('Y-m-d', $from_ts);
				$iso_to = date('Y-m-d', $to_ts);
				
				$result = array('status' => 'ERR');
				if (pjObject::getPlugin('pjVouchers') !== NULL)
				{
					$result = pjVoucherModel::factory()->getVoucher($get['code'], $iso_from, date("H:i:s", $from_ts));
				}
				if ($result['status'] == 'OK')
				{
					$extras = null;
					if($this->_is('extras'))
					{
						$extras = $this->_get('extras');
					}
					$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
					$price = pjAppController::getPrice($this->option_arr, $this->_get('space_id'), $from_ts, $to_ts, $rental_days, $this->getLocaleId(), $get['code'], $extras);
					if (isset($price['discount_formatted']))
					{
						$price['discount_text'] = $price['discount_formatted'] . " " . __('front_discount_text', true);
					}
					$this->_set('code', $get['code']);
					$this->set('price',$price);
				} else {
					$this->_unset('code');
				}
			}
		}
	}
	
	public function pjActionRemovePromo()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			if ($this->_is('code'))
			{
				unset($_SESSION[$this->defaultStore]['code']);
			}
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200));
		}
		exit;
	}
	
	public function pjActionIpBlocked()
	{
	    $this->setAjax(true);
	    
	    if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
	    {
	        
	    }
	}
	
	public function pjActionSearch()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
		{
			if (!isset($_SESSION[$this->defaultStore]) || count($_SESSION[$this->defaultStore]) === 0)
			{
				$_SESSION[$this->defaultStore] = array();
			}
		}
	}
	
	public function pjActionSpaces()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
		{
			$get = $this->_get->raw();
			if (isset($_SESSION[$this->defaultStore]) && count($_SESSION[$this->defaultStore]) > 0)
			{
				$sortby = 'price_asc';
				if(isset($get['sortby']) && in_array($get['sortby'], array('price_asc', 'price_desc', 'name_asc', 'name_desc')))
				{
					$sortby = $get['sortby'];
				}
				
				$from = $this->_get("from");
				$to = $this->_get("to");
				
				$from_ts = strtotime($from);
				$to_ts = strtotime($to);
				
				$iso_from = date('Y-m-d', $from_ts);
				$iso_to = date('Y-m-d', $to_ts);
				
				$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
				$space_arr = pjAppController::getSpaces($from_ts, $to_ts, $iso_from, $iso_to, $rental_days, $this->getLocaleId(), $sortby, null);

				$cnt_extras = pjExtraModel::factory()->findCount()->getData();
				
				$this->set('rental_days', $rental_days);
				$this->set('space_arr', $space_arr);
				$this->set('cnt_extras', $cnt_extras);
				$this->set('status', 'OK');
			}else{
				$this->set('status', 'ERR');
			}
		}
	}
	
	public function pjActionExtras()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
		{
			$get = $this->_get->raw();
			if (isset($_SESSION[$this->defaultStore]) && count($_SESSION[$this->defaultStore]) > 0)
			{
				if(isset($get['space_id']) && (int) $get['space_id'] > 0)
				{
					$this->_set('space_id', $get['space_id']);
				}
				if($this->_is('space_id'))
				{
					$space_id = $this->_get('space_id');
					
					$from = $this->_get("from");
					$to = $this->_get("to");
		
					$from_ts = strtotime($from);
					$to_ts = strtotime($to);
		
					$iso_from = date('Y-m-d', $from_ts);
					$iso_to = date('Y-m-d', $to_ts);
		
					$space = pjSpaceModel::factory()
						->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->select('t1.*, t2.content as name')
						->find($space_id)
						->getData();
					
					$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
					$extra_arr = pjAppController::getExtras($iso_from, $iso_to, $this->getLocaleId(), null);
					
					$STORE = @$_SESSION[$this->defaultStore];
					foreach($extra_arr as $k => $extra)
					{
					    $max = $extra['cnt'] - $extra['bookings'];
					    if ($extra['type'] == 'unlimited')
					    {
					        $max = 100;
					    }
					    switch ($extra['is_single'])
					    {
					        case 1:
					            if (isset($STORE['extras']) && array_key_exists($extra['id'], @$STORE['extras']) && (int) @$STORE['extras'][$extra['id']] > 0)
					            {
					                if ($max <= 0)
					                {
					                    unset($_SESSION[$this->defaultStore]['extras'][$extra['id']]);
					                }
					            }
					            break;
					        case 0:
					            if ($max <= 0)
					            {
					                if(isset($STORE['extras']) && count($STORE['extras']) > 0)
					                {
					                    if(array_key_exists($extra['id'], $STORE['extras']))
					                    {
					                        unset($_SESSION[$this->defaultStore]['extras'][$extra['id']]);
					                    }
					                }
					            }
					            break;
					    }
					}
					
					$this->set('space', $space);
					$this->set('rental_days', $rental_days);
					$this->set('extra_arr', $extra_arr);
					$this->set('status', 'OK');
				}else{
					$this->set('status', 'ERR');
				}
			}else{
				$this->set('status', 'ERR');
			}
		}
	}
	
	public function pjActionCheckout()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
		{
			$get = $this->_get->raw();
			if (isset($_SESSION[$this->defaultStore]) && count($_SESSION[$this->defaultStore]) > 0)
			{
				if(isset($get['space_id']) && (int) $get['space_id'] > 0)
				{
					$this->_set('space_id', $get['space_id']);
				}
				if($this->_is('space_id'))
				{
					if ($this->_post->check('cp_checkout'))
					{
						$_SESSION[$this->defaultForm] = $this->_post->raw();
					
						pjAppController::jsonResponse(array('status' => 'OK', 'code' => 211));
					}else{
						$from = $this->_get("from");
						$to = $this->_get("to");
						
						$from_ts = strtotime($from);
						$to_ts = strtotime($to);
						
						$iso_from = date('Y-m-d', $from_ts);
						$iso_to = date('Y-m-d', $to_ts);
						
						$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
						
						$space = pjSpaceModel::factory()
							->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
							->select('t1.*, t2.content as name')
							->find($this->_get('space_id'))
							->getData();
							
						$country_arr = pjBaseCountryModel::factory()
								->select('t1.id, t2.content AS name')
								->join('pjMultiLang', "t2.model='pjBaseCountry' 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();
						
						$extras = null;
						$code = null;
						if($this->_is('extras'))
						{
							$extras = $this->_get('extras');
						}
						if($this->_is('code'))
						{
							$code = $this->_get('code');
						}
						
						$price = pjAppController::getPrice($this->option_arr, $this->_get('space_id'), $from_ts, $to_ts, $rental_days, $this->getLocaleId(), $code, $extras);
						if (isset($price['discount_formatted']))
						{
							$price['discount_text'] = $price['discount_formatted'] . " " . __('front_discount_text', true);
						}
						
						$cnt_extras = pjExtraModel::factory()->findCount()->getData();
						
						$terms_conditions = pjMultiLangModel::factory()->select('t1.*')
							->where('t1.model','pjOption')
							->where('t1.locale', $this->getLocaleId())
							->where('t1.field', 'o_terms')
							->limit(0, 1)
							->findAll()->getData();
						$this->set('terms_conditions', $terms_conditions[0]['content']);
						
						$this->set('extras', $price['extra_compilation']['extra_name']);
						$this->set('extra_arr', $price['extra_compilation']['extra_arr']);
						$this->set('extra_price', $price['extra_compilation']['extra_price']);
						
						if(pjObject::getPlugin('pjPayments') !== NULL)
						{
						    $this->set('payment_option_arr', pjPaymentOptionModel::factory()->getOptions($this->getForeignId()));
						    $this->set('payment_titles', pjPayments::getPaymentTitles($this->getForeignId(), $this->getLocaleId()));
						}else{
						    $this->set('payment_titles', __('payment_methods', true));
						}
						$bank_account = pjMultiLangModel::factory()->select('t1.content')
			                    ->where('t1.model','pjOption')
			                    ->where('t1.locale', $this->getLocaleId())
			                    ->where('t1.field', 'o_bank_account')
			                    ->limit(1)
			                    ->findAll()->getDataIndex(0);
	                    $this->set('bank_account', $bank_account ? $bank_account['content'] : '');
						
						$this->set('space', $space);
						$this->set('rental_days', $rental_days);
						$this->set('cnt_extras', $cnt_extras);
						$this->set('price', $price);
						$this->set('country_arr', $country_arr);
					}
					$this->set('status', 'OK');
				}else{
					$this->set('status', 'ERR');
				}
			}else{
				$this->set('status', 'ERR');
			}
		}
	}
	
	public function pjActionPreview()
	{
		$this->setAjax(true);
		if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
		{
			if (isset($_SESSION[$this->defaultStore]) && count($_SESSION[$this->defaultStore]) > 0)
			{
				if($this->_is('space_id'))
				{
					$from = $this->_get("from");
					$to = $this->_get("to");
						
					$from_ts = strtotime($from);
					$to_ts = strtotime($to);
						
					$iso_from = date('Y-m-d', $from_ts);
					$iso_to = date('Y-m-d', $to_ts);
						
					$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
						
					$space = pjSpaceModel::factory()
						->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->select('t1.*, t2.content as name')
						->find($this->_get('space_id'))
						->getData();
					
					if(isset($_SESSION[$this->defaultForm]['c_country']) && (int) $_SESSION[$this->defaultForm]['c_country'] > 0)
					{	
						$this->set('country_arr', pjBaseCountryModel::factory()
							->select('t1.*, t2.content AS name')
							->join('pjBaseMultiLang', "t2.model='pjBaseCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
							->find($_SESSION[$this->defaultForm]['c_country'])
							->getData()
						);
					}
						
					$extras = null;
					$code = null;
					if($this->_is('extras'))
					{
						$extras = $this->_get('extras');
					}
					if($this->_is('code'))
					{
						$code = $this->_get('code');
					}
						
					$price = pjAppController::getPrice($this->option_arr, $this->_get('space_id'), $from_ts, $to_ts, $rental_days, $this->getLocaleId(), $code, $extras);
					if (isset($price['discount_formatted']))
					{
						$price['discount_text'] = $price['discount_formatted'] . " " . __('front_discount_text', true);
					}
					
					$this->set('extras', $price['extra_compilation']['extra_name']);
					$this->set('extra_arr', $price['extra_compilation']['extra_arr']);
					$this->set('extra_price', $price['extra_compilation']['extra_price']);
					
					$this->set('space', $space);
					$this->set('rental_days', $rental_days);
					$this->set('price', $price);
					
					if(pjObject::getPlugin('pjPayments') !== NULL)
					{
					    $this->set('payment_titles', pjPayments::getPaymentTitles($this->getForeignId(), $this->getLocaleId()));
					}else{
					    $this->set('payment_titles', __('payment_methods', true));
					}
					$bank_account = pjMultiLangModel::factory()->select('t1.content')
		                    ->where('t1.model','pjOption')
		                    ->where('t1.locale', $this->getLocaleId())
		                    ->where('t1.field', 'o_bank_account')
		                    ->limit(1)
		                    ->findAll()->getDataIndex(0);
                    $this->set('bank_account', $bank_account ? $bank_account['content'] : '');
					
					$this->set('status', 'OK');
				}else{
					$this->set('status', 'ERR');
				}
			}else{
				$this->set('status', 'ERR');
			}
		}
	}
	
	public function pjActionGetPrices()
	{
		$this->setAjax(true);
		if ($this->isXHR() || $this->_get->check('_escaped_fragment_'))
		{
			$from = $this->_get("from");
			$to = $this->_get("to");

			$from_ts = strtotime($from);
			$to_ts = strtotime($to);

			$iso_from = date('Y-m-d', $from_ts);
			$iso_to = date('Y-m-d', $to_ts);

			$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));

			$extras = null;
			$code = null;
			if($this->_is('extras'))
			{
				$extras = $this->_get('extras');
			}
			if($this->_is('code'))
			{
				$code = $this->_get('code');
			}

			$price = pjAppController::getPrice($this->option_arr, $this->_get('space_id'), $from_ts, $to_ts, $rental_days, $this->getLocaleId(), $code, $extras);
			if (isset($price['discount_formatted']))
			{
				$price['discount_text'] = $price['discount_formatted'] . " " . __('front_discount_text', true);
			}
			
			$this->set('extras', $price['extra_compilation']['extra_name']);
			$this->set('extra_arr', $price['extra_compilation']['extra_arr']);
			$this->set('extra_price', $price['extra_compilation']['extra_price']);
			$this->set('rental_days', $rental_days);
			$this->set('price', $price);
		}
	}
	
	public function pjActionSaveBooking()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
		    $front_err = __('front_err', true);
			if (!$this->_post->check('cp_preview') || !isset($_SESSION[$this->defaultForm]) || empty($_SESSION[$this->defaultForm]) || !isset($_SESSION[$this->defaultStore]) || empty($_SESSION[$this->defaultStore]))
			{
			    pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 109, 'text' => $front_err[109]));
			}
			$FORM = @$_SESSION[$this->defaultForm];
	        if ((int) $this->option_arr['o_bf_include_captcha'] === 3 && $this->option_arr['o_captcha_type_front'] == 'system' && (!isset($FORM['captcha']) || !pjCaptcha::validate(strtoupper($FORM['captcha']), $_SESSION[$this->defaultCaptcha])))
	        {
	            pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 110, 'text' => $front_err[110]));
	        }
	        $_SESSION[$this->defaultCaptcha] = NULL;
	        unset($_SESSION[$this->defaultCaptcha]);
	        			
			$from = $this->_get("from");
			$to = $this->_get("to");
			
			$from_ts = strtotime($from);
			$to_ts = strtotime($to);
			
			$iso_from = date('Y-m-d', $from_ts);
			$iso_to = date('Y-m-d', $to_ts);
			
			/* Validate form */
			$map = array(
			    'o_bf_include_title' => 'c_title',
			    'o_bf_include_name' => 'c_name',
			    'o_bf_include_email' => 'c_email',
			    'o_bf_include_phone' => 'c_phone',
			    'o_bf_include_company' => 'c_company',
			    'o_bf_include_address' => 'c_address',
			    'o_bf_include_country' => 'c_country',
			    'o_bf_include_state' => 'c_state',
			    'o_bf_include_city' => 'c_city',
			    'o_bf_include_zip' => 'c_zip',
			    'o_bf_include_notes' => 'c_notes',
			    'o_bf_include_regno' => 'c_regno',
			    'o_bf_include_make' => 'c_make',
			    'o_bf_include_model' => 'c_model',
			);
			$map_label = array(
			    'c_title' => __('front_title', true),
			    'c_name' => __('front_name', true),
			    'c_email' => __('front_email', true),
			    'c_phone' => __('front_phone', true),
			    'c_company' => __('front_company', true),
			    'c_address' => __('front_address', true),
			    'c_country' => __('front_country', true),
			    'c_state' => __('front_state', true),
			    'c_city' => __('front_city', true),
			    'c_zip' => __('front_zip', true),
			    'c_notes' => __('front_notes', true),
			    'c_regno' => __('front_regno', true),
			    'c_make' => __('front_make', true),
			    'c_model' => __('front_model', true),
			);
			foreach ($map as $key => $idx)
			{
			    $check = true;
			    
			    if ($this->option_arr[$key] == 2)
			    {
			        $check = array_key_exists($idx, $FORM);
			        
			    } elseif ($this->option_arr[$key] == 3) {
			        
			        $check = array_key_exists($idx, $FORM) && !empty($FORM[$idx]);
			    }
			    
			    if ($idx == 'c_email' && array_key_exists($idx, $FORM) && !empty($FORM[$idx]))
			    {
			        if (!pjValidation::pjActionEmail($FORM[$idx]))
			        {
			            $check = false;
			        }
			    }
			    
			    if (!$check)
			    {
			        if($idx == 'c_email')
			        {
			            self::jsonResponse(array('status' => 'ERR', 'code' => 113, 'text' => sprintf($front_err[113], $map_label[$idx]), 'idx' => $idx));
			        }else{
			            self::jsonResponse(array('status' => 'ERR', 'code' => 112, 'text' => sprintf($front_err[112], $map_label[$idx]), 'idx' => $idx));
			        }
			    }
			}
			$data = array();
			
			$rental_days = pjAppController::getRentalDays($this->option_arr, $iso_from, $iso_to, date('H', $from_ts), date('H', $to_ts), date('i', $from_ts), date('i', $to_ts));
			$extras = null;
			$code = null;
			if($this->_is('extras'))
			{
			    $extras = $this->_get('extras');
			}
			if($this->_is('code'))
			{
			    $code = $this->_get('code');
			}
			$price = pjAppController::getPrice($this->option_arr, $this->_get('space_id'), $from_ts, $to_ts, $rental_days, $this->getLocaleId(), $code, $extras);
			
			$STORE = @$_SESSION[$this->defaultStore];
			$data['rental_price'] = $price['rental_price'];
			$data['extra_price'] = isset($price['extra_compilation']) ? (!empty($price['extra_compilation']) ? $price['extra_compilation']['extra_price'] : 0) : 0;
			$data['sub_total'] = !(isset($STORE['code']) && !empty($STORE['code'])) ? $price['price'] : $price['price_after_discount'];
			$data['tax'] = $price['tax'];
			$data['total'] = $price['total'];
			$data['deposit'] = $price['deposit'];
			$data['discount'] = @$price['price_before_discount'] - @$price['price_after_discount'];
			if($this->option_arr['o_payment_disable'] == 'Yes')
			{
			    $data['discount'] = 0;
			}
			$discount_code = $this->_get('code');
			
			$uuid = pjUtil::uuid();
			$data['uuid'] = $uuid;
			$data['locale_id'] = $this->getLocaleId();
			$data['space_id'] = $this->_get('space_id');
			$data['discount_code'] = !empty($discount_code) ? $discount_code : ':NULL';
			$data['from'] = $iso_from . ' ' . date("H:i:s", $from_ts);
			$data['to'] = $iso_to . ' ' . date("H:i:s", $to_ts);
			$data['status'] = $this->option_arr['o_booking_status'];
			$data['ip'] = pjUtil::getClientIp();
				
			$payment = 'none';
			if(isset($FORM['payment_method']))
			{
				if (isset($FORM['payment_method'])){
					$payment = $FORM['payment_method'];
				}
			}
				
			$pjBookingModel = pjBookingModel::factory();
			
			$id = $pjBookingModel->setAttributes(array_merge($FORM, $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				if(isset($price['extra_compilation']['extra_arr']) && !empty($price['extra_compilation']['extra_arr']))
				{
					$pjBookingExtraModel = pjBookingExtraModel::factory();
					$pjBookingExtraModel->begin();
					foreach($price['extra_compilation']['extra_arr'] as $k => $v)
					{
						$pjBookingExtraModel
							->reset()
							->set('booking_id', $id)
							->set('extra_id', $v['id'])
							->set('price', $v['price'])
							->set('cnt', $v['qty'])
							->insert();
					}
					$pjBookingExtraModel->commit();
				}

				$arr = $pjBookingModel
					->reset()
					->find($id)
					->getData();
				
				$pdata = array();
				$pdata['booking_id'] = $id;
				$pdata['payment_method'] = $payment;
				$pdata['payment_type'] = 'online';
				$pdata['amount'] = $arr['deposit'];
				$pdata['status'] = 'notpaid';
				pjBookingPaymentModel::factory()->setAttributes($pdata)->insert();

				pjFront::pjActionConfirmSend($this->option_arr, $arr, 'confirmation');

				unset($_SESSION[$this->defaultStore]);
				unset($_SESSION[$this->defaultForm]);

				$json = array('code' => 200, 'text' => '', 'booking_id' => $id, 'payment' => $payment);
				pjAppController::jsonResponse($json);
			}else {
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 119, 'text' => $front_err[119]));
			}
		}
	}
	
	public function pjActionCancel()
	{
		$this->setLayout('pjActionCancel');
	
		$pjBookingModel = pjBookingModel::factory();
	
		if ($this->_post->check('booking_cancel'))
		{
			$booking_id = $this->_post->toInt('id');
			$booking_arr = $pjBookingModel->find($booking_id)->getData();
			if (count($booking_arr) > 0)
			{
				$pjBookingModel->reset()->where("SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $this->_post->toString('hash') . "'")->limit(1)->modifyAll(array('status' => 'cancelled'));
				$arr = $pjBookingModel
					->reset()
					->find($booking_id)
					->getData();
				pjFront::pjActionConfirmSend($this->option_arr, $arr, 'cancel');
	
				pjUtil::redirect($this->option_arr['o_cancel_page']);
			}
		}else{
			$get = $this->_get->raw();
			if (isset($get['hash']) && isset($get['id']))
			{
				$arr = $pjBookingModel
					->reset()
					->select('t1.*, t2.content as space_name, t3.content as country_title')
					->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.space_id AND t2.field='name' AND t2.locale=t1.locale_id", 'left outer')
					->join('pjMultiLang', "t3.model='pjBaseCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale=t1.locale_id", 'left outer')
					->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{
						    if((int) $arr['locale_id'] > 0)
						    {
						        $locale = pjLocaleModel::factory()->find($arr['locale_id'])->getData();
						        if(!empty($locale))
						        {
						            $this->setLocaleId($locale['id']);
						            $this->loadSetFields(true);
						        }
						    }
							$this->set('arr', $arr);
						}
					}
				}
			}else if (!isset($get['err'])) {
				$this->set('status', 1);
			}
		}
	}
	
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$arr = pjBookingModel::factory()
				->select('t1.*, t2.content as space_name')
				->join('pjMultiLang', "t2.model='pjSpace' AND t2.foreign_id=t1.space_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->find($this->_get->toInt('booking_id'))
				->getData();
			
			if (!empty($arr))
			{
				if(pjObject::getPlugin('pjPayments') !== NULL)
	            {
	                $pjPlugin = pjPayments::getPluginName($arr['payment_method']);
	                if(pjObject::getPlugin($pjPlugin) !== NULL)
	                {
	                    $amount = pjUtil::stripPrice(pjCurrency::formatPriceOnly($arr['deposit']));
	                    $params = $pjPlugin::getFormParams(array('payment_method' => $arr['payment_method']), array(
	                        'locale_id'	 => $this->getLocaleId(),
	                        'return_url'	=> $this->option_arr['o_thank_you_page'],
	                        'id'			=> $arr['id'],
	                        'foreign_id'	=> $this->getForeignId(),
	                        'uuid'		  => $arr['uuid'],
	                        'name'		  => @$arr['c_name'],
	                        'email'		 => @$arr['c_email'],
	                        'phone'		 => @$arr['c_phone'],
	                        'amount'		=> $amount,
	                        'cancel_hash'   => sha1($arr['uuid'].strtotime($arr['created']).PJ_SALT),
	                        'currency_code' => $this->option_arr['o_currency'],
	                    ));
	                    $params['option_foreign_id'] = $this->getForeignId(); 
	                    $this->set('params', $params);
	                }
	                
	                if ($arr['payment_method'] == 'bank')
	                {
	                    $bank_account = pjMultiLangModel::factory()->select('t1.content')
	                    ->where('t1.model','pjOption')
	                    ->where('t1.locale', $this->getLocaleId())
	                    ->where('t1.field', 'o_bank_account')
	                    ->limit(1)
	                    ->findAll()->getDataIndex(0);
	                    $this->set('bank_account', $bank_account['content']);
	                }
	            }
			}
			$this->set('arr', $arr);
			$this->set('get', $this->_get->raw());
		}
	}
	
	public function pjActionConfirm()
	{
	    $this->setAjax(true);
	    
	    if (pjObject::getPlugin('pjPayments') === NULL)
	    {
	        $this->log('pjPayments plugin not installed');
	        exit;
	    }
	    
	    $pjPayments = new pjPayments();
	    $post = $this->_post->raw();
	    $get = $this->_get->raw();
	    $request = array();
	    if(isset($get['payment_method']))
	    {
	        $request = $get;
	    }
	    if(isset($post['payment_method']))
	    {
	        $request = $post;
	    }
	    
	    if($pjPlugin = $pjPayments->getPaymentPlugin($request))
	    {
	        if($uuid = $this->requestAction(array('controller' => $pjPlugin, 'action' => 'pjActionGetCustom', 'params' => $request), array('return')))
	        {
	            $pjBookingModel= pjBookingModel::factory();
	            $booking_arr = $pjBookingModel
	            ->select("t1.*, t2.content AS country")
				->join('pjMultiLang', "t2.model='pjBaseCountry' AND t2.foreign_id=t1.c_country AND t2.locale='".$this->getLocaleId()."' AND t2.field='name'", 'left outer')
				->where('uuid', $uuid)
				->limit(1)
				->findAll()->getDataIndex(0);
				
				if (!empty($booking_arr))
				{
				    $params = array(
				        'request'		=> $request,
				        'payment_method' => $request['payment_method'],
				        'foreign_id'	 => $this->getForeignId(),
				        'amount'		 => $booking_arr['deposit'],
				        'txn_id'		 => $booking_arr['txn_id'],
				        'order_id'	   => $booking_arr['id'],
				    	'uuid'	   => $booking_arr['uuid'],
				        'cancel_hash'	=> sha1($booking_arr['uuid'].strtotime($booking_arr['created']).PJ_SALT),
				        'key'			=> md5($this->option_arr['private_key'] . PJ_SALT)
				    );
				    $response = $this->requestAction(array('controller' => $pjPlugin, 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
				    if($response['status'] == 'OK')
				    {
				        $this->log("Payments | {$pjPlugin} plugin<br>Order was confirmed. UUID: {$uuid}");
				        
				        $pjBookingModel->reset()->setAttributes(array('id' => $booking_arr['id']))->modify(array(
							'status' => $this->option_arr['o_payment_status'],
							'processed_on' => ':NOW()'
						));
						pjBookingPaymentModel::factory()->setAttributes(array('booking_id' => $booking_arr['id'], 'payment_type' => 'online'))
														->limit(1)->modifyAll(array('status' => 'paid'));
						
						pjFront::pjActionConfirmSend($this->option_arr, $booking_arr, 'payment');
				        echo $this->option_arr['o_thank_you_page'];
				        exit;
				    }elseif($response['status'] == 'CANCEL'){
				        $this->log("Payments | {$pjPlugin} plugin<br>Payment was cancelled. UUID: {$uuid}");
				        
				        $pjBookingModel->reset()->set('id', $booking_arr['id'])->modify(array('status' => 'cancelled', 'processed_on' => ':NOW()'));
				       	pjFront::pjActionConfirmSend($this->option_arr, $booking_arr, 'cancel');
				        if(isset($response['return_url']) && !empty($response['return_url']))
				        {
				            echo $response['return_url'];
				        }else{
				            echo $this->option_arr['o_cancel_page'];
				        }
				        exit;
				    }else{
				        $this->log("Payments | {$pjPlugin} plugin<br>Order confirmation was failed. UUID: {$uuid}");
				    }
				    
				    if(isset($response['redirect']) && $response['redirect'] == true)
				    {
				        echo $this->option_arr['o_thank_you_page'];
				        exit;
				    }
				}else{
				    $this->log("Payments | {$pjPlugin} plugin<br>Booking with UUID {$uuid} not found.");
				}
				echo $this->option_arr['o_thank_you_page'];
				exit;
	        }
	    }
	    echo $this->option_arr['o_thank_you_page'];
	    exit;
	}
	
	public function pjActionConfirmSend($option_arr, $booking_arr, $opt)
	{
		$Email = self::getMailer($option_arr);
	    
	    $pjMultiLangModel = pjMultiLangModel::factory();
	    $pjNotificationModel = pjNotificationModel::factory();
	    
	    $locale_id = (int)$booking_arr['locale_id'] > 0 ? (int)$booking_arr['locale_id'] : $this->getLocaleId();
	    $admin_email = pjAppController::getAdminEmail();
	    $admin_phone = pjAppController::getAdminPhone();
	    $booking_arr['calendar_id'] = $this->getForeignId();
	    $tokens = pjAppController::getTokens($booking_arr, $option_arr, PJ_SALT, $locale_id);
	   
	    $notification = $pjNotificationModel->reset()->where('recipient', 'client')->where('transport', 'email')->where('variant', $opt)->findAll()->getDataIndex(0);
	    if((int) $notification['id'] > 0 && $notification['is_active'] == 1)
	    {
	        $resp = pjFront::pjActionGetSubjectMessage($notification, $locale_id, $booking_arr['calendar_id']);
	        $lang_message = $resp['lang_message'];
	        $lang_subject = $resp['lang_subject'];
	        if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']))
	        {
	            $subject = str_replace($tokens['search'], $tokens['replace'], $lang_subject[0]['content']);
	            $message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	            $Email
	            ->setTo($booking_arr['c_email'])
	            ->setSubject(stripslashes($subject))
	            ->send(stripslashes($message));
	        }
	    }
	    
	    $notification = $pjNotificationModel->reset()->where('recipient', 'admin')->where('transport', 'email')->where('variant', $opt)->findAll()->getDataIndex(0);
	    if((int) $notification['id'] > 0 && $notification['is_active'] == 1)
	    {
	        $resp = pjFront::pjActionGetSubjectMessage($notification, $locale_id, $booking_arr['calendar_id']);
	        $lang_message = $resp['lang_message'];
	        $lang_subject = $resp['lang_subject'];
	        if (count($lang_message) === 1 && count($lang_subject) === 1 && !empty($lang_subject[0]['content']))
	        {
	            $subject = str_replace($tokens['search'], $tokens['replace'], $lang_subject[0]['content']);
	            $message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	            
	            $Email
	            ->setTo($admin_email)
	            ->setSubject(stripslashes($subject))
	            ->send(stripslashes($message));
	        }
	    }
	    
	    /*SMS sent to client*/
	    if(!empty($booking_arr['c_phone']))
	    {
	        $notification = $pjNotificationModel->reset()->where('recipient', 'client')->where('transport', 'sms')->where('variant', $opt)->findAll()->getDataIndex(0);
	        if((int) $notification['id'] > 0 && $notification['is_active'] == 1)
	        {
	            $lang_message = $pjMultiLangModel
	            ->reset()
	            ->select('t1.*')
	            ->where('t1.foreign_id', $booking_arr['calendar_id'])
	            ->where('t1.model','pjOption')
	            ->where('t1.locale', $locale_id)
	            ->where('t1.field', 'confirm_sms_tokens_client')
	            ->limit(0, 1)
	            ->findAll()
	            ->getData();
	            if (count($lang_message) === 1)
	            {
	                $message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	                $params = array(
	                    'text' => stripslashes($message),
	                    'type' => 'unicode',
	                    'key' => md5($option_arr['private_key'] . PJ_SALT)
	                );
	                $params['number'] = $booking_arr['c_phone'];
	                pjBaseSms::init($params)->pjActionSend();
	            }
	        }
	    }
	    
		/*SMS sent to admin*/
	    if(!empty($admin_phone))
	    {
	        $notification = $pjNotificationModel->reset()->where('recipient', 'admin')->where('transport', 'sms')->where('variant', $opt)->findAll()->getDataIndex(0);
	        if((int) $notification['id'] > 0 && $notification['is_active'] == 1)
	        {
	        	if ($opt == 'payment') {
		            $lang_message = $pjMultiLangModel
		            ->reset()
		            ->select('t1.*')
		            ->where('t1.foreign_id', $booking_arr['calendar_id'])
		            ->where('t1.model','pjOption')
		            ->where('t1.locale', $locale_id)
		            ->where('t1.field', 'payment_sms_tokens_admin')
		            ->limit(0, 1)
		            ->findAll()
		            ->getData();
	        	} else {
	        		$lang_message = $pjMultiLangModel
		            ->reset()
		            ->select('t1.*')
		            ->where('t1.foreign_id', $booking_arr['calendar_id'])
		            ->where('t1.model','pjOption')
		            ->where('t1.locale', $locale_id)
		            ->where('t1.field', 'confirm_sms_tokens_admin')
		            ->limit(0, 1)
		            ->findAll()
		            ->getData();
	        	}
	            if (count($lang_message) === 1)
	            {
	                $message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	                $params = array(
	                    'text' => stripslashes($message),
	                    'type' => 'unicode',
	                    'key' => md5($option_arr['private_key'] . PJ_SALT)
	                );
	                $params['number'] = $admin_phone;
	                pjBaseSms::init($params)->pjActionSend();
	            }
	        }
	    }
	}
	
	public static function pjActionGetSubjectMessage($notification, $locale_id, $calendar_id)
	{
	    $field = $notification['variant'] . '_tokens_' . $notification['recipient'];
	    $field = str_replace('confirmation', 'confirm', $field);
	    $pjMultiLangModel = pjMultiLangModel::factory();
	    $lang_message = $pjMultiLangModel
		    ->reset()
		    ->select('t1.*')
		    ->where('t1.foreign_id', $calendar_id)
		    ->where('t1.model','pjOption')
		    ->where('t1.locale', $locale_id)
		    ->where('t1.field', $field)
		    ->limit(0, 1)
		    ->findAll()
		    ->getData();
	    $field = $notification['variant'] . '_subject_' . $notification['recipient'];
	    $field = str_replace('confirmation', 'confirm', $field);
	    $lang_subject = $pjMultiLangModel
		    ->reset()
		    ->select('t1.*')
		    ->where('t1.foreign_id',  $calendar_id)
		    ->where('t1.model','pjOption')
		    ->where('t1.locale', $locale_id)
		    ->where('t1.field', $field)
		    ->limit(0, 1)
		    ->findAll()
		    ->getData();
	    return compact('lang_message', 'lang_subject');
	}
	
	public function pjActionCheckTime()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
		    $post = $this->_post->raw();
		    $field = $this->_get->toString('field');
			if ($field == 'from' && !empty($post['from'])) {
		    	$from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
		    	$from_ts = $from_arr['ts'];
		    	if ($from_ts < time()) {
		    		pjAppController::jsonResponse(array('code' => '101'));
		    	}
		    }
			if ($field == 'to' && !empty($post['to'])) {
		    	$to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
		    	$to_ts = $to_arr['ts'];
		    	if ($to_ts < time()) {
		    		pjAppController::jsonResponse(array('code' => '102'));
		    	}
		    }
		    
		    if (!empty($post['from']) && !empty($post['to'])) {
		    	$from_arr = pjUtil::convertDateTime($post['from'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
				$to_arr = pjUtil::convertDateTime($post['to'], $this->option_arr['o_date_format'], $this->option_arr['o_time_format']);
			    $from_ts = $from_arr['ts'];
				$to_ts = $to_arr['ts'];
				if ($from_ts > $to_ts) {
					pjAppController::jsonResponse(array('code' => '103'));
				} else {
					pjAppController::jsonResponse(array('code' => '200'));
				}
		    }
		    pjAppController::jsonResponse(array('code' => '200'));
		}
		exit;
	}
}
?>