<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjNCBS_Captcha';
	
	public $defaultLocale = 'pjNCBS_LocaleId';
	
	public $defaultFrontUser = 'pjNCBS_User';
	
	public $defaultLangMenu = 'pjNCBS_LangMenu';
	
	public $defaultStore = 'pjNCBS_Store';
	
	public $defaultForm = 'pjNCBS_Form';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
		
		self::allowCORS();
	}
	
	public function _get($key)
	{
		if ($this->_is($key))
		{
			return $_SESSION[$this->defaultStore][$key];
		}
		return false;
	}
	
	public function _is($key)
	{
		return isset($_SESSION[$this->defaultStore]) && isset($_SESSION[$this->defaultStore][$key]);
	}
	
	public function _set($key, $value)
	{
		$_SESSION[$this->defaultStore][$key] = $value;
		return $this;
	}
	
	public function _unset($key)
	{
		if ($this->_is($key))
		{
			unset($_SESSION[$this->defaultStore][$key]);
		}
	}
	
	public function afterFilter()
	{		
		if (!isset($_GET['hide']) || (isset($_GET['hide']) && (int) $_GET['hide'] !== 1) &&
			in_array($_GET['action'], array('pjActionMain', 'pjActionTypes', 'pjActionLogin', 'pjActionVouchers', 'pjActionCheckout', 'pjActionPreview')))
		{
			$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file, t2.title')
				->join('pjLocaleLanguage', '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()
	{
		$OptionModel = pjOptionModel::factory();
		$this->option_arr = $OptionModel->getPairs($this->getForeignId());
		$this->set('option_arr', $this->option_arr);
		$this->setTime();

		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']);
			}
		}
		
		$cnt_extras = pjExtraModel::factory()
			->where('t1.status', 'T')
			->findCount()
			->getData();
		
		$this->set('cnt_extras', $cnt_extras);
		
		$this->loadSetFields();
	}
	
	public function beforeRender()
	{
		if (isset($_GET['iframe']))
		{
			$this->setLayout('pjActionIframe');
		}
	}
	
	public function pjActionLocale()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			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");
		$Captcha = new pjCaptcha(PJ_WEB_PATH.'obj/Anorexia.ttf', $this->defaultCaptcha, 6);
		$Captcha->setImage(PJ_IMG_PATH.'button.png')->init(isset($_GET['rand']) ? $_GET['rand'] : null);
		exit;
	}

	public function pjActionCheckCaptcha()
	{
		$this->setAjax(true);
		if (!isset($_GET['captcha']) || empty($_GET['captcha']) || strtoupper($_GET['captcha']) != $_SESSION[$this->defaultCaptcha]){
			echo 'false';
		}else{
			echo 'true';
		}
		exit;
	}
	
	public function pjActionLoadCss()
	{
		$dm = new pjDependencyManager(PJ_INSTALL_PATH, PJ_THIRD_PARTY_PATH);
		$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
	
		$theme = $this->option_arr['o_layout'];
		$fonts = $this->option_arr['o_layout'];
		if(isset($_GET['layout']) && in_array($_GET['layout'], array('theme1', 'theme2', 'theme3', 'theme4', 'theme5', 'theme6', 'theme7', 'theme8', 'theme9', 'theme10')))
		{
			$theme = $_GET['layout'];
			$fonts = $_GET['layout'];
		}
		$arr = array(
				array('file' => "$fonts.css", 'path' => PJ_CSS_PATH . "fonts/"),
				array('file' => 'bootstrap-datetimepicker.min.css', 'path' => $dm->getPath('pj_bootstrap_datetimepicker')),
				array('file' => 'style.css', 'path' => PJ_CSS_PATH),
				array('file' => "$theme.css", 'path' => PJ_CSS_PATH . "themes/",
				array('file' => 'transitions.css', 'path' => PJ_CSS_PATH))
		);
		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('../fonts/glyphicons', "pjWrapper"),
						array(
								PJ_INSTALL_URL . PJ_FRAMEWORK_LIBS_PATH . 'pj/fonts/glyphicons',
								"pjWrapperNightClub_" . $theme
						),
						$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionSearch()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			$date = date($this->option_arr['o_date_format'], time());
			$date_iso = date('Y-m-d');
			if(isset($_GET['date']) && !empty($_GET['date']))
			{
				$date = $_GET['date'];
				$date_iso = pjUtil::formatDate($date, $this->option_arr['o_date_format']);
			}else{
				if($this->_is('date_iso'))
				{
					$date_iso = $this->_get('date_iso');
					$date = date($this->option_arr['o_date_format'], strtotime($date_iso));
				}
			}
						
			$this->_set("date_iso", $date_iso);
			
			$pjDateModel = pjDateModel::factory()->where("('$date_iso' BETWEEN `start_date` AND `end_date`)");
			if($pjDateModel->findCount()->getData() == 0)
			{
				$booth_arr = pjBoothModel::factory()
					->select("t1.*, t2.content AS type, 
							(SELECT SUM(`TR`.cnt) FROM `".pjReservationModel::factory()->getTable()."` AS `TR` WHERE `TR`.`date`='".$date_iso."' AND `TR`.status <> 'cancelled' AND `TR`.booth_id=t1.id) AS cnt_booked,
							(SELECT `TP`.price FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.`date`='".$date_iso."' AND `TP`.booth_id=t1.id LIMIT 1) AS custom_price")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjBooth' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'type'", 'left')
					->where('t1.status', 'T')
					->orderBy("type ASC")
					->findAll()
					->getData();
				
				$this->set('booth_arr', $booth_arr);
			}
			
			if($this->_is('id'))
			{
				$this->_unset('id');
			}
			
			$this->set('date', $date);
		}
	}
	public function pjActionSetBooth()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$this->_set('id', (int) $_GET['id']);
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
			exit;
		}
	}
	public function pjActionBooth()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_SESSION[$this->defaultStore]) && 
					count($_SESSION[$this->defaultStore]) > 0 &&
					isset($_SESSION[$this->defaultStore]['date_iso']) && 
					isset($_SESSION[$this->defaultStore]['id']))
			{
				
				$id = $this->_get('id');
				$date_iso = $this->_get('date_iso');
				
				$arr = pjBoothModel::factory()
					->select("t1.*, t2.content AS type, t3.content AS description,
							(SELECT SUM(`TR`.cnt) FROM `".pjReservationModel::factory()->getTable()."` AS `TR` WHERE `TR`.`date`='".$date_iso."' AND `TR`.status <> 'cancelled' AND `TR`.booth_id=t1.id) AS cnt_booked,
							(SELECT `TP`.price FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.`date`='".$date_iso."' AND `TP`.booth_id=t1.id LIMIT 1) AS custom_price")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjBooth' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'type'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjBooth' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
					->find($id)
					->getData();

				$cnt = (int) $arr['count'] - (int) $arr['cnt_booked'];
				if($cnt > 0 && !$this->_is('cnt'))
				{
					$this->_set('cnt', 1);
				}
				
				$this->set('arr', $arr);
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				exit;
			}
		}
	}
	public function pjActionSetCount()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_GET['cnt']) && (int) $_GET['cnt'] > 0)
			{
				$this->_set('cnt', (int) $_GET['cnt']);
				$text = pjUtil::formatCurrencySign(number_format($_GET['cnt'] * $_GET['price'], 2), $this->option_arr['o_currency']);
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => $text));
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
			exit;
		}
	}
	public function pjActionExtras()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_SESSION[$this->defaultStore]) &&
					count($_SESSION[$this->defaultStore]) > 0 &&
					isset($_SESSION[$this->defaultStore]['date_iso']) &&
					isset($_SESSION[$this->defaultStore]['id']) &&
					isset($_SESSION[$this->defaultStore]['cnt']))
			{
				$category_arr = pjCategoryModel::factory()
					->select('t1.*, t2.content as name')
					->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->where('status', 'T')
					->where("(SELECT COUNT(`TCE`.extra_id) FROM `".pjCategoryExtraModel::factory()->getTable()."` AS `TCE` WHERE `TCE`.category_id=t1.id) > 0")
					->orderBy("name ASC")
					->findAll()
					->getData();
				
				if(count($category_arr) > 0)
				{
					$category_id = $category_arr[0]['id'];
					
					$extra_arr = pjExtraModel::factory()
						->select("t1.*, t2.content AS title, t3.content AS description")
						->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
						->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjExtra' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
						->where("t1.id IN (SELECT TCE.extra_id FROM `".pjCategoryExtraModel::factory()->getTable()."` AS TCE WHERE TCE.category_id=".$category_id.")")
						->where('t1.status', 'T')
						->orderBy("title ASC")
						->findAll()
						->getData();

					if(!empty($extra_arr))
					{
						$this->set('extra_arr', $extra_arr);
						$this->set('category_id', $category_id);
						$this->set('category_arr', $category_arr);
					}else{
						pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 200, 'text' => ''));
						exit;
					}
				}else{
					pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 200, 'text' => ''));
					exit;
				}
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				exit;
			}
		}
	}
	public function pjActionGetExtras()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if(isset($_GET['category_id']) && (int) $_GET['category_id'] > 0)
			{
				$extra_arr = pjExtraModel::factory()
					->select("t1.*, t2.content AS title, t3.content AS description")
					->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
					->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjExtra' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
					->where("t1.id IN (SELECT TCE.extra_id FROM `".pjCategoryExtraModel::factory()->getTable()."` AS TCE WHERE TCE.category_id=".$_GET['category_id'].")")
					->orderBy("title ASC")
					->findAll()
					->getData();

				$this->set('extra_arr', $extra_arr);
				$this->set('category_id', $_GET['category_id']);
			}
		}
	}
	public function pjActionSetExtras()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_GET['category_id']) && (int) $_GET['category_id'] > 0 && 
					isset($_GET['extra_id']) && (int) $_GET['extra_id'] > 0 &&
					isset($_GET['cnt']) && (int) $_GET['cnt'] >= 0)
			{
				$STORE = $_SESSION[$this->defaultStore];
				
				$extra_arr = pjExtraModel::factory()->find($_GET['extra_id'])->getData();
				
				if(isset($STORE['extras']))
				{
					$extras = $STORE['extras'];
					$extras[$_GET['category_id']][$_GET['extra_id']] = array('cnt' => $_GET['cnt'], 'price' => $extra_arr['price']);
				}else{
					$extras = array();
					$extras[$_GET['category_id']][$_GET['extra_id']] = array('cnt' => $_GET['cnt'], 'price' => $extra_arr['price']);
				}
				$_SESSION[$this->defaultStore]['extras'] = $extras;
				
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => ''));
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
			}
			exit;
		}
	}
	public function pjActionCheckout()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_SESSION[$this->defaultStore]) &&
					count($_SESSION[$this->defaultStore]) > 0 &&
					isset($_SESSION[$this->defaultStore]['date_iso']) &&
					isset($_SESSION[$this->defaultStore]['id']) &&
					isset($_SESSION[$this->defaultStore]['cnt']))
			{
				if(isset($_POST['ncb_checkout']))
				{
					$_SESSION[$this->defaultForm] = $_POST;
				
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200));
				}else{
					$reservation_details = $this->pjActionReservationDetails(); 
					
					$country_arr = pjCountryModel::factory()
						->select('t1.id, t2.content AS country_title')
						->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->orderBy('`country_title` ASC')
						->findAll()
						->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();
					$terms_conditions = '';
					if(!empty($_terms_conditions))
					{
						$terms_conditions = $_terms_conditions[0]['content'];
					}
					$this->set('terms_conditions', $terms_conditions);
					$this->set('country_arr', $country_arr);
					$this->set('arr', $reservation_details['arr']);
					$this->set('prices', $reservation_details['prices']);
					$this->set('category_arr', $reservation_details['category_arr']);
					$this->set('extra_arr', $reservation_details['extra_arr']);
				}
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				exit;
			}
		}
	}
	public function pjActionPreview()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_SESSION[$this->defaultStore]) &&
					count($_SESSION[$this->defaultStore]) > 0 &&
					isset($_SESSION[$this->defaultStore]['date_iso']) &&
					isset($_SESSION[$this->defaultStore]['id']) &&
					isset($_SESSION[$this->defaultStore]['cnt']))
			{
				$reservation_details = $this->pjActionReservationDetails(); 
					
				if(isset($_SESSION[$this->defaultForm]['c_country']) && (int) $_SESSION[$this->defaultForm]['c_country'] > 0)
				{	
					$country_arr = pjCountryModel::factory()
						->select('t1.id, t2.content AS country_title')
						->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->find($_SESSION[$this->defaultForm]['c_country'])
						->getData();
					$this->set('country_arr', $country_arr);
				}	
				
				$this->set('arr', $reservation_details['arr']);
				$this->set('prices', $reservation_details['prices']);
				$this->set('category_arr', $reservation_details['category_arr']);
				$this->set('extra_arr', $reservation_details['extra_arr']);
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				exit;
			}
		}
	}
	
	public function pjActionSaveReservation()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_POST['ncb_preview']) || !isset($_SESSION[$this->defaultForm]) || empty($_SESSION[$this->defaultForm]) || !isset($_SESSION[$this->defaultStore]) || empty($_SESSION[$this->defaultStore]))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 109));
			}
			if ((int) $this->option_arr['o_bf_include_captcha'] === 3 && (!isset($_SESSION[$this->defaultForm]['captcha']) ||
					!pjCaptcha::validate($_SESSION[$this->defaultForm]['captcha'], $_SESSION[$this->defaultCaptcha]) ))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 110));
			}
			
			$STORE = @$_SESSION[$this->defaultStore];
			$FORM = @$_SESSION[$this->defaultForm];
			
			$data = array();
			
			$data['uuid'] = time();
			$data['date'] = $STORE['date_iso'];
			$data['booth_id'] = $STORE['id'];
			$data['cnt'] = $STORE['cnt'];
			$data['ip'] = pjUtil::getClientIp();
			$data['status'] = $this->option_arr['o_booking_status'];
			$data['created'] = date('Y-m-d H:i:s');
			$payment = ':NULL';
			if(isset($FORM['payment_method']))
			{
				if (isset($FORM['payment_method'])){
					$payment = $FORM['payment_method'];
				}
			}
			$pjReservationModel = pjReservationModel::factory();
			$id = $pjReservationModel->setAttributes(array_merge($FORM, $data))->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				if(isset($STORE['extras']) && count($STORE['extras']) >0)
				{
					$pjExtraModel = pjExtraModel::factory();
					$pjReservationExtraModel = pjReservationExtraModel::factory();
					foreach($STORE['extras'] as $cid => $extra_arr)
					{
						foreach($extra_arr as $eid => $pair)
						{
							if((int)$pair['cnt'] > 0)
							{
								$pjReservationExtraModel
									->reset()
									->setAttributes(array(
										'reservation_id' => $id,
										'extra_id' => $eid,
										'category_id' => $cid,
										'price' => $pair['price'],
										'cnt' => $pair['cnt']
								))->insert();
							}
						}
					}
				}
				$arr = $pjReservationModel
					->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';
				pjReservationPaymentModel::factory()->setAttributes($pdata)->insert();
				
				pjFront::pjActionConfirmSend($this->option_arr, $arr, PJ_SALT, 'confirm');
				
				unset($_SESSION[$this->defaultStore]);
				unset($_SESSION[$this->defaultForm]);
				
				$json = array('code' => 200, 'text' => '', 'reservation_id' => $id, 'payment' => $payment);
				pjAppController::jsonResponse($json);
			}else {
				pjAppController::jsonResponse(array('code' => 'ERR', 'code' => 119));
			}
		}
	}

	public function pjActionCancel()
	{
		$this->setLayout('pjActionCancel');
	
		$pjReservationModel = pjReservationModel::factory();
	
		if (isset($_POST['reservation_cancel']))
		{
			$booking_arr = $pjReservationModel->find($_POST['id'])->getData();
			if (count($booking_arr) > 0)
			{
				$sql = "UPDATE `".$pjReservationModel->getTable()."` SET status = 'cancelled' WHERE SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
	
				$pjReservationModel->reset()->execute($sql);
	
				$arr = $pjReservationModel
					->reset()
					->find($_POST['id'])
					->getData();
				pjFront::pjActionConfirmSend($this->option_arr, $arr, PJ_SALT, 'cancel');
	
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjFront&action=pjActionCancel&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = $pjReservationModel
					->reset()
					->select('t1.*, t2.content as type, t3.content as country_title')
					->join('pjMultiLang', "t2.model='pjBooth' AND t2.foreign_id=t1.booth_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjMultiLang', "t3.model='pjCountry' AND t3.foreign_id=t1.c_country AND t3.field='name' AND t3.locale='".$this->getLocaleId()."'", '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{
	
							$this->set('arr', $arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
	
	
	public function pjActionReservationDetails()
	{
		$id = $this->_get('id');
		$date_iso = $this->_get('date_iso');
			
		$arr = pjBoothModel::factory()
			->select("t1.*, t2.content AS type, t3.content AS description,
							(SELECT SUM(`TR`.cnt) FROM `".pjReservationModel::factory()->getTable()."` AS `TR` WHERE `TR`.`date`='".$date_iso."' AND `TR`.status <> 'cancelled' AND `TR`.booth_id=t1.id) AS cnt_booked,
							(SELECT `TP`.price FROM `".pjPriceModel::factory()->getTable()."` AS `TP` WHERE `TP`.`date`='".$date_iso."' AND `TP`.booth_id=t1.id LIMIT 1) AS custom_price")
			->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjBooth' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'type'", 'left')
			->join('pjMultiLang', "t3.foreign_id = t1.id AND t3.model = 'pjBooth' AND t3.locale = '".$this->getLocaleId()."' AND t3.field = 'description'", 'left')
			->find($id)
			->getData();
			
		$prices = $this->pjActionCalPrices($arr);
		
		$STORE = $_SESSION[$this->defaultStore];

		$category_arr = array();
		$extra_arr = array();
		$category_id_arr = array();
		$extra_id_arr = array();
			
		if(isset($STORE['extras']) && count($STORE['extras']) > 0)
		{
			foreach($STORE['extras'] as $cid => $extra_arr)
			{
				$category_id_arr[] = $cid;
				foreach($extra_arr as $eid => $pair)
				{
					$extra_id_arr[] = $eid;
				}
			}
			$category_arr = pjCategoryModel::factory()
				->select('t1.*, t2.content as name')
				->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->where('status', 'T')
				->whereIn('t1.id', $category_id_arr)
				->findAll()
				->getDataPair('id', 'name');
		
			$extra_arr = pjExtraModel::factory()
				->select("t1.*, t2.content AS title")
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'title'", 'left')
				->where('status', 'T')
				->whereIn('t1.id', $extra_id_arr)
				->findAll()
				->getDataPair('id', 'title');
		}
		
		return compact('arr', 'prices', 'category_arr', 'extra_arr');
	}
	public function pjActionCalPrices($arr)
	{
		$price = 0;
		$subtotal = 0;
		$tax = 0;
		$total = 0;
		$deposit = 0;
		$extra_price = 0;
		
		$STORE = $_SESSION[$this->defaultStore];
		
		$price = $arr['price'];
		if(!empty($arr['custom_price']))
		{
			$price = $arr['custom_price'];
		}
		if(isset($STORE['cnt']))
		{
			$price = $price * $STORE['cnt'];
		}
		
		if(isset($STORE['extras']) && count($STORE['extras']) > 0)
		{
			foreach($STORE['extras'] as $cid => $extra_arr)
			{
				foreach($extra_arr as $eid => $pair)
				{
					$extra_price += $pair['price'] * $pair['cnt'];
				}
			}
		}
		$subtotal = $price + $extra_price;
		$tax = ($subtotal * $this->option_arr['o_tax_payment']) / 100;
		$total = $subtotal + $tax;
		$deposit = ($total * $this->option_arr['o_deposit_payment']) / 100;
		
		return compact('price', 'subtotal', 'tax', 'total', 'deposit', 'extra_price');
	}
	
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjReservationModel::factory()
				->select('t1.*, t2.content as type')
				->join('pjMultiLang', "t2.model='pjBooth' AND t2.foreign_id=t1.booth_id AND t2.field='type' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->find($_GET['reservation_id'])
				->getData();
				
			if (!empty($arr))
			{
				switch ($arr['payment_method'])
				{
					case 'paypal':
						$this->set('params', array(
							'name' => 'ncbPaypal',
							'id' => 'ncbPaypal',
							'business' => $this->option_arr['o_paypal_address'],
							'item_name' => pjSanitize::html($arr['type']),
							'custom' => $arr['id'],
							'amount' => $arr['deposit'],
							'currency_code' => $this->option_arr['o_currency'],
							'return' => $this->option_arr['o_thankyou_page'],
							'notify_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmPaypal',
							'target' => '_self',
							'charset' => 'utf-8'
						));
						break;
					case 'authorize':
						$this->set('params', array(
							'name' => 'ncbAuthorize',
							'id' => 'ncbAuthorize',
							'target' => '_self',
							'timezone' => $this->option_arr['o_authorize_timezone'],
							'transkey' => $this->option_arr['o_authorize_transkey'],
							'x_login' => $this->option_arr['o_authorize_merchant_id'],
							'x_description' => pjSanitize::html($arr['type']),
							'x_amount' => $arr['deposit'],
							'x_invoice_num' => $arr['id'],
							'x_receipt_link_url' => $this->option_arr['o_thankyou_page'],
							'x_relay_url' => PJ_INSTALL_URL . 'index.php?controller=pjFront&action=pjActionConfirmAuthorize'
						));
						break;
				}
			}
			$this->set('arr', $arr);
			$this->set('get', $_GET);
		}
	}
	
	public function pjActionConfirmAuthorize()
	{
		$this->setAjax(true);
	
		if (pjObject::getPlugin('pjAuthorize') === NULL)
		{
			$this->log('Authorize.NET plugin not installed');
			exit;
		}
		$pjReservationModel = pjReservationModel::factory();
	
		$reservation_arr = $pjReservationModel
			->find($_POST['x_invoice_num'])
			->getData();
		if (count($reservation_arr) == 0)
		{
			$this->log('No such reservation');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	
		if (count($reservation_arr) > 0)
		{
			$params = array(
					'transkey' => $this->option_arr['o_authorize_transkey'],
					'x_login' => $this->option_arr['o_authorize_merchant_id'],
					'md5_setting' => $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')
			{
				$pjReservationModel->reset()
					->setAttributes(array('id' => $response['transaction_id']))
					->modify(array('status' => $this->option_arr['o_payment_status'], 'processed_on' => ':NOW()'));
	
				pjReservationPaymentModel::factory()
					->setAttributes(array('reservation_id' => $response['transaction_id'], 'payment_type' => 'online'))
					->modify(array('status' => 'paid'));
					
				pjFront::pjActionConfirmSend($this->option_arr, $reservation_arr, PJ_SALT, 'payment');
	
			} elseif (!$response) {
				$this->log('Authorization failed');
			} else {
				$this->log('Booking not confirmed. ' . $response['response_reason_text']);
			}
			?>
			<script type="text/javascript">window.location.href="<?php echo $this->option_arr['o_thankyou_page']; ?>";</script>
			<?php
			return;
		}
	}
	
	public function pjActionConfirmPaypal()
	{
		$this->setAjax(true);
	
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			exit;
		}
		$pjReservationModel = pjReservationModel::factory();
	
		$reservation_arr = $pjReservationModel
			->find($_POST['custom'])
			->getData();
		if (count($reservation_arr) == 0)
		{
			$this->log('No such reservation');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	
		$params = array(
				'txn_id' => @$reservation_arr['txn_id'],
				'paypal_address' => $this->option_arr['o_paypal_address'],
				'deposit' => @$reservation_arr['deposit'],
				'currency' => $this->option_arr['o_currency'],
				'key' => md5($this->option_arr['private_key'] . PJ_SALT)
		);
		$response = $this->requestAction(array('controller' => 'pjPaypal', 'action' => 'pjActionConfirm', 'params' => $params), array('return'));
	
		if ($response !== FALSE && $response['status'] === 'OK')
		{
			$this->log('Reservation confirmed');
			$pjReservationModel->reset()->setAttributes(array('id' => $reservation_arr['id']))->modify(array(
					'status' => $this->option_arr['o_payment_status'],
					'txn_id' => $response['transaction_id'],
					'processed_on' => ':NOW()'
			));
			pjReservationPaymentModel::factory()
				->setAttributes(array('reservation_id' => $reservation_arr['id'], 'payment_type' => 'online'))
				->modify(array('status' => 'paid'));
				
			pjFront::pjActionConfirmSend($this->option_arr, $reservation_arr, PJ_SALT, 'payment');
				
		} elseif (!$response) {
			$this->log('Authorization failed');
		} else {
			$this->log('Booking not confirmed');
		}
		pjUtil::redirect($this->option_arr['o_thankyou_page']);
	}
	
	public function pjActionConfirmSend($option_arr, $reservatoin_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();
		$admin_phone = $this->getAdminPhone();
		$from_email = $admin_email;
	
		$locale_id = $this->getLocaleId();
	
		$tokens = pjAppController::getTokens($reservatoin_arr, $option_arr, PJ_SALT, $locale_id);
	
		$pjMultiLangModel = pjMultiLangModel::factory();
	
		if ($option_arr['o_email_payment'] == 1 && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->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('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)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($reservatoin_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if ($option_arr['o_admin_email_payment'] == 1 && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_payment_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($admin_email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if(!empty($admin_phone) && $opt == 'payment')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_sms_payment_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1)
			{
				$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'] = $admin_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('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('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)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
					
				$Email
					->setTo($reservatoin_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if ($option_arr['o_admin_email_confirmation'] == 1 && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_confirmation_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
				$Email
					->setTo($admin_email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if(!empty($reservatoin_arr['c_phone']) && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->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)
			{
				$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'] = $reservatoin_arr['c_phone'];
					$this->requestAction(array('controller' => 'pjSms', 'action' => 'pjActionSend', 'params' => $params), array('return'));
				}
			}
		}
		if(!empty($admin_phone) && $opt == 'confirm')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_sms_confirmation_message')
				->limit(0, 1)
				->findAll()->getData();
			if (count($lang_message) === 1)
			{
				$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'] = $admin_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('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('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)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($reservatoin_arr['c_email'])
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
		if ($option_arr['o_admin_email_cancel'] == 1 && $opt == 'cancel')
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_cancel_message')
				->limit(0, 1)
				->findAll()->getData();
			$lang_subject = $pjMultiLangModel->reset()->select('t1.*')
				->where('t1.model','pjOption')
				->where('t1.locale', $locale_id)
				->where('t1.field', 'o_admin_email_cancel_subject')
				->limit(0, 1)
				->findAll()->getData();
	
			if (count($lang_message) === 1 && count($lang_subject) === 1)
			{
				$message = str_replace($tokens['search'], $tokens['replace'], $lang_message[0]['content']);
	
				$Email
					->setTo($admin_email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send($message);
			}
		}
	}
	
	
	public function isXHR()
	{
		return parent::isXHR() || isset($_SERVER['HTTP_ORIGIN']);
	}
	
	static protected function allowCORS()
	{
		$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");
	}
}
?>