<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjCBS_Captcha';
	
	public $defaultLocale = 'pjCBS_LocaleId';
	
	public $defaultFrontUser = 'pjCBS_User';
	
	public $defaultLangMenu = 'pjCBS_LangMenu';
	
	public $defaultStore = 'pjCBS_Store';
	
	public $defaultForm = 'pjCBS_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']);
			}
		}
		
		$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_theme'];
		if(isset($_GET['theme']) && in_array($_GET['theme'], array('theme1', 'theme2', 'theme3', 'theme4', 'theme5', 'theme6', 'theme7', 'theme8', 'theme9', 'theme10')))
		{
			$theme = $_GET['theme'];
		}
		$arr = array(
				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/")
		);
		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',
								"pjWrapperCleaning_" . $theme
						),
						$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionAddServices()
	{
		$this->setAjax(true);
		
		if($this->isXHR())
		{
			$_SESSION[$this->defaultStore]['services'] = $_POST;
			$arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
			
			$this->set('price_arr', $this->calcPrice($_SESSION[$this->defaultStore]['services'], $this->option_arr, $this->getLocaleId()));
			$this->set('arr', $arr);
		}	
	}
	public function pjActionAddDateTime()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			$_SESSION[$this->defaultStore]['datetime'] = $_POST;
			$arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
				
			$this->set('price_arr', $this->calcPrice($_SESSION[$this->defaultStore]['services'], $this->option_arr, $this->getLocaleId()));
			$this->set('arr', $arr);
		}
	}
	public function pjActionServices()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			$arr = pjServiceModel::factory()
				->select('t1.*, t2.content AS included')
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjService' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'included'", 'left')
				->find($this->getServiceId())->getData();
			
			$extra_arr = pjExtraModel::factory()
				->select('t1.*, t2.content AS name')
				->join('pjMultiLang', "t2.foreign_id = t1.id AND t2.model = 'pjExtra' AND t2.locale = '".$this->getLocaleId()."' AND t2.field = 'name'", 'left')
				->where('t1.service_id', $this->getServiceId())
				->findAll()
				->getData();
			
			$services = isset($_SESSION[$this->defaultStore]['services']) ? $_SESSION[$this->defaultStore]['services'] : array();
			
			$this->set('price_arr', $this->calcPrice($services, $this->option_arr, $this->getLocaleId()));
			$this->set('arr', $arr);
			$this->set('extra_arr', $extra_arr);
		}
	}
	public function pjActionDateTime()
	{
		$this->setAjax(true);
	
		if($this->isXHR())
		{
			if (isset($_SESSION[$this->defaultStore]) &&
					count($_SESSION[$this->defaultStore]) > 0 &&
					isset($_SESSION[$this->defaultStore]['services']) &&
					!empty($_SESSION[$this->defaultStore]['services']))
			{
				$arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
				$services = isset($_SESSION[$this->defaultStore]['services']) ? $_SESSION[$this->defaultStore]['services'] : array();
				
				$this->set('price_arr', $this->calcPrice($services, $this->option_arr, $this->getLocaleId()));
				$this->set('arr', $arr);
			}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]['services']) &&
					!empty($_SESSION[$this->defaultStore]['services']) &&
					isset($_SESSION[$this->defaultStore]['datetime']) &&
					!empty($_SESSION[$this->defaultStore]['datetime']))
			{
				if(isset($_POST['cbs_checkout']))
				{
					$_SESSION[$this->defaultForm] = $_POST;
				
					pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200));
				}else{
					$arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
					$services = isset($_SESSION[$this->defaultStore]['services']) ? $_SESSION[$this->defaultStore]['services'] : array();
		
					$this->set('price_arr', $this->calcPrice($services, $this->option_arr, $this->getLocaleId()));
					$this->set('arr', $arr);
					
					$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();
					$this->set('country_arr', $country_arr);
					
					$_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);
				}
			}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]['services']) &&
					!empty($_SESSION[$this->defaultStore]['services']) &&
					isset($_SESSION[$this->defaultStore]['datetime']) &&
					!empty($_SESSION[$this->defaultStore]['datetime']))
			{
				$arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
				$services = isset($_SESSION[$this->defaultStore]['services']) ? $_SESSION[$this->defaultStore]['services'] : array();

				$this->set('price_arr', $this->calcPrice($services, $this->option_arr, $this->getLocaleId()));
				$this->set('arr', $arr);

				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')
						->orderBy('`country_title` ASC')
						->find($_SESSION[$this->defaultForm]['c_country'])
						->getData();
					$this->set('country_arr', $country_arr);
				}
				$STORE = @$_SESSION[$this->defaultStore];
				
			}else{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => ''));
				exit;
			}
		}
	}
	public function pjActionSaveEnquiry()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_POST['cbs_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];
	
			$client_data = array();
			$enquiry_data = array();
	
			$client_id = ':NULL';
			if(isset($FORM['c_email']) && !empty($FORM['c_email']))
			{
				$client_data['c_title'] = @$FORM['c_title'];
				$client_data['c_name'] = @$FORM['c_name'];
				$client_data['c_phone'] = @$FORM['c_phone'];
				$client_data['c_email'] = @$FORM['c_email'];
				
				$pjClientModel = pjClientModel::factory();
				$client_arr = $pjClientModel->where('t1.c_email', $client_data['c_email'])->limit(1)->findAll()->getData();
				
				if(count($client_arr) > 0)
				{
					$client_id = $client_arr[0]['id'];
					$pjClientModel->reset()->where('id', $client_id)->limit(1)->modifyAll($client_data);
				}else{
					$client_data['c_password'] = 'pass';
					$client_data['created'] = date('Y-m-d H:i:s');
					$client_data['status'] = 'T';
					$client_id = $pjClientModel->reset()->setAttributes($client_data)->insert()->getInsertId();
				}
			}
			
			$arr = pjServiceModel::factory()->find($this->getServiceId())->getData();
			$services = isset($STORE['services']) ? $STORE['services'] : array();
			$date_time = $STORE['datetime'];
			
			$price_arr = $this->calcPrice($services, $this->option_arr, $this->getLocaleId());
			
			$enquiry_data['uuid'] = time();
			$enquiry_data['ip'] = pjUtil::getClientIp();
			$enquiry_data['client_id'] = $client_id;
			$enquiry_data['status'] = $this->option_arr['o_booking_status'];
			$enquiry_data['created'] = date('Y-m-d H:i:s');
			
			$enquiry_data['how_often'] = $date_time['how_often'];
			$enquiry_data['date'] =  pjUtil::formatDate($date_time['date'], $this->option_arr['o_date_format']);
			$enquiry_data['when'] = $date_time['when'];
			$enquiry_data['home'] = @$FORM['home'];
			
			$enquiry_data['cleaning_materials'] = @$services['cleaning_materials'];
			$enquiry_data['cleaning_materials_price'] = $arr['cleaning_materials_price'];
			$enquiry_data['bedrooms'] = $services['bedrooms'];
			$enquiry_data['time_per_bedroom'] = $arr['time_per_bedroom'];
			$enquiry_data['bathrooms'] = @$services['bathrooms'];
			$enquiry_data['time_per_bathroom'] = $arr['time_per_bathroom'];
			
			$enquiry_data['subtotal'] = $price_arr['subtotal'];
			$enquiry_data['tax'] = $price_arr['tax'];
			$enquiry_data['total'] = $price_arr['total'];
			$enquiry_data['deposit'] = $price_arr['deposit'];
			
			$enquiry_data['price_per_hour'] = $arr['price_per_hour'];
			$enquiry_data['c_notes'] = @$FORM['c_notes'];
			
			$enquiry_data['c_address'] = @$FORM['c_address'];
			$enquiry_data['c_city'] = @$FORM['c_city'];
			$enquiry_data['c_state'] = @$FORM['c_state'];
			$enquiry_data['c_zip'] = @$FORM['c_zip'];
			$enquiry_data['c_country'] = @$FORM['c_country'];
			
			$payment = ':NULL';
			if(isset($FORM['payment_method']))
			{
				$payment = $FORM['payment_method'];
				if($payment != 'creditcard')
				{
					$enquiry_data['cc_exp_month'] = '';
					$enquiry_data['cc_exp_year'] = '';
				}else{
					$enquiry_data['cc_type'] = @$FORM['cc_type'];
					$enquiry_data['cc_num'] = @$FORM['cc_num'];
					$enquiry_data['cc_exp_month'] = @$FORM['cc_exp_month'];
					$enquiry_data['cc_exp_year'] = @$FORM['cc_exp_year'];
					$enquiry_data['cc_code'] = @$FORM['cc_code'];
				}
			}
			$enquiry_data['payment_method'] = $payment;
			
			$pjEnquiryModel = pjEnquiryModel::factory();
			$id = $pjEnquiryModel->setAttributes($enquiry_data)->insert()->getInsertId();
			if ($id !== false && (int) $id > 0)
			{
				$pjEnquiryExtraModel = pjEnquiryExtraModel::factory();
				if(isset($services['extra_id']) && is_array($services['extra_id']))
				{
					foreach($services['extra_id'] as $extra_id => $on)
					{
						$extra_data = array();
						$extra_data['enquiry_id'] = $id;
						$extra_data['extra_id'] = $extra_id;
						$pjEnquiryExtraModel->reset()->setAttributes($extra_data)->insert();
					}
				}
				
				$arr = $pjEnquiryModel
					->reset()
					->find($id)
					->getData();
	
				$pdata = array();
				$pdata['enquiry_id'] = $id;
				$pdata['payment_method'] = $payment;
				$pdata['payment_type'] = 'online';
				$pdata['amount'] = $arr['deposit'];
				$pdata['status'] = 'notpaid';
				pjEnquiryPaymentModel::factory()->setAttributes($pdata)->insert();
				
				pjFront::pjActionConfirmSend($this->option_arr, $id, PJ_SALT, 'confirm');
	
				unset($_SESSION[$this->defaultStore]);
				unset($_SESSION[$this->defaultForm]);
	
				$json = array('code' => 200, 'text' => '', 'enquiry_id' => $id, 'payment' => $payment);
				pjAppController::jsonResponse($json);
			}else {
				pjAppController::jsonResponse(array('code' => 'ERR', 'code' => 119));
			}
		}
	}
	public function pjActionGetPaymentForm()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjEnquiryModel::factory()
				->find($_GET['enquiry_id'])
				->getData();
				
			if (!empty($arr))
			{
				switch ($arr['payment_method'])
				{
					case 'paypal':
						$this->set('params', array(
							'name' => 'cbsPaypal',
							'id' => 'cbsPaypal',
							'business' => $this->option_arr['o_paypal_address'],
							'item_name' => pjSanitize::html($arr['uuid']),
							'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' => 'cbsAuthorize',
							'id' => 'cbsAuthorize',
							'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['uuid']),
							'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;
		}
		$pjEnquiryModel = pjEnquiryModel::factory();
	
		$enquiry_arr = $pjEnquiryModel
			->find($_POST['x_invoice_num'])
			->getData();
		if (count($enquiry_arr) == 0)
		{
			$this->log('No such enquiry');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	
		if (count($enquiry_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')
			{
				$pjEnquiryModel->reset()
					->setAttributes(array('id' => $response['transaction_id']))
					->modify(array('status' => $this->option_arr['o_payment_status'], 'processed_on' => ':NOW()'));
	
				pjEnquiryPaymentModel::factory()
					->setAttributes(array('enquiry_id' => $response['transaction_id'], 'payment_type' => 'online'))
					->modify(array('status' => 'paid'));
					
				pjFront::pjActionConfirmSend($this->option_arr, $enquiry_arr['id'], PJ_SALT, 'payment');
	
			} elseif (!$response) {
				$this->log('Authorization failed');
			} else {
				$this->log('Enquiry 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 pjActionCancel()
	{
		$this->setLayout('pjActionCancel');
	
		$pjEnquiryModel = pjEnquiryModel::factory();
	
		if (isset($_POST['enquiry_cancel']))
		{
			$enquiry_arr = $pjEnquiryModel->find($_POST['id'])->getData();
			if (count($enquiry_arr) > 0)
			{
				$sql = "UPDATE `".$pjEnquiryModel->getTable()."` SET status = 'cancelled' WHERE SHA1(CONCAT(`id`, `created`, '".PJ_SALT."')) = '" . $_POST['hash'] . "'";
	
				$pjEnquiryModel->reset()->execute($sql);
	
				pjFront::pjActionConfirmSend($this->option_arr, $_POST['id'], PJ_SALT, 'cancel');
	
				pjUtil::redirect($_SERVER['PHP_SELF'] . '?controller=pjFront&action=pjActionCancel&err=200');
			}
		}else{
			if (isset($_GET['hash']) && isset($_GET['id']))
			{
				$arr = $pjEnquiryModel
					->reset()
					->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`")
					->find($_GET['id'])
					->getData();
				$client_arr = pjClientModel::factory()
					->select('t1.*, t2.content as country_title')
					->join('pjMultiLang', "t2.model='pjCountry' AND t2.foreign_id=t1.c_country AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->find($arr['client_id'])->getData();
				
				$enquiry_extra_arr = pjEnquiryExtraModel::factory()
					->select('t1.*, t2.content as extra_name, t3.time_needed')
					->join('pjMultiLang', "t2.model='pjExtra' AND t2.foreign_id=t1.extra_id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
					->join('pjExtra', 't3.id=t1.extra_id', 'left outer')
					->where('t1.enquiry_id', $_GET['id'])
					->findAll()->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);
							$this->set('client_arr', $client_arr);
							$this->set('enquiry_extra_arr', $enquiry_extra_arr);
						}
					}
				}
			}else if (!isset($_GET['err'])) {
				$this->set('status', 1);
			}
		}
	}
	
	public function pjActionConfirmPaypal()
	{
		$this->setAjax(true);
	
		if (pjObject::getPlugin('pjPaypal') === NULL)
		{
			$this->log('Paypal plugin not installed');
			exit;
		}
		$pjEnquiryModel = pjEnquiryModel::factory();
	
		$enquiry_arr = $pjEnquiryModel
			->find($_POST['custom'])
			->getData();
		if (count($enquiry_arr) == 0)
		{
			$this->log('No such enquiry');
			pjUtil::redirect($this->option_arr['o_thankyou_page']);
		}
	
		$params = array(
				'txn_id' => @$enquiry_arr['txn_id'],
				'paypal_address' => $this->option_arr['o_paypal_address'],
				'deposit' => @$enquiry_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('Enquiry confirmed');
			$pjEnquiryModel->reset()->setAttributes(array('id' => $enquiry_arr['id']))->modify(array(
					'status' => $this->option_arr['o_payment_status'],
					'txn_id' => $response['transaction_id'],
					'processed_on' => ':NOW()'
			));
			pjEnquiryPaymentModel::factory()
				->setAttributes(array('enquiry_id' => $enquiry_arr['id'], 'payment_type' => 'online'))
				->modify(array('status' => 'paid'));
				
			pjFront::pjActionConfirmSend($this->option_arr, $enquiry_arr['id'], PJ_SALT, 'payment');
				
		} elseif (!$response) {
			$this->log('Authorization failed');
		} else {
			$this->log('Enquiry not confirmed');
		}
		pjUtil::redirect($this->option_arr['o_thankyou_page']);
	}
	
	public function pjActionConfirmSend($option_arr, $id, $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($id, $option_arr, PJ_SALT, $locale_id);
		$enquiry_arr = pjEnquiryModel::factory()->find($id)->getData();
		$client_arr = pjClientModel::factory()->find($enquiry_arr['client_id'])->getData();
		
		$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($client_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($client_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($client_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'] = $client_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($client_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");
	}
}
?>