<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAppController extends pjController
{
	public $models = array();
	
	public $defaultLocale = 'admin_locale_id';
	
	public $defaultForeignId = 1;
	
	public $defaultFields = 'front_fields';
	
	public $defaultFieldsIndex = 'fields_index';
	
	protected function loadSetFields($force=FALSE, $locale_id=NULL, $fields=NULL)
	{
		if (is_null($locale_id))
		{
			$locale_id = $this->getLocaleId();
		}
		
		if (is_null($fields))
		{
			$fields = $this->defaultFields;
		}
		
		$registry = pjRegistry::getInstance();
		if ($force
				|| !isset($_SESSION[$this->defaultFieldsIndex])
				|| $_SESSION[$this->defaultFieldsIndex] != $this->option_arr['o_fields_index']
				|| !isset($_SESSION[$fields])
				|| empty($_SESSION[$fields]))
		{
			pjAppController::setFields($locale_id);
	
			# Update session
			if ($registry->is('fields'))
			{
				$_SESSION[$fields] = $registry->get('fields');
			}
			$_SESSION[$this->defaultFieldsIndex] = $this->option_arr['o_fields_index'];
		}
	
		if (isset($_SESSION[$fields]) && !empty($_SESSION[$fields]))
		{
			# Load fields from session
			$registry->set('fields', $_SESSION[$fields]);
		}
		
		return TRUE;
	}
	
	public function isCountryReady()
    {
    	return $this->isAdmin();
    }
    
	public function isOneAdminReady()
    {
    	return $this->isAdmin();
    }
	
	public function isEditor()
	{
		return $this->getRoleId() == 2;
	}
    
	public static function setTimezone($timezone="UTC")
    {
    	if (in_array(version_compare(phpversion(), '5.1.0'), array(0,1)))
		{
			date_default_timezone_set($timezone);
		} else {
			$safe_mode = ini_get('safe_mode');
			if ($safe_mode)
			{
				putenv("TZ=".$timezone);
			}
		}
    }

	public static function setMySQLServerTime($offset="-0:00")
    {
		pjAppModel::factory()->prepare("SET SESSION time_zone = :offset;")->exec(compact('offset'));
    }
    
	public function setTime()
	{
		if (isset($this->option_arr['o_timezone']))
		{
			$offset = $this->option_arr['o_timezone'] / 3600;
			if ($offset > 0)
			{
				$offset = "-".$offset;
			} elseif ($offset < 0) {
				$offset = "+".abs($offset);
			} elseif ($offset === 0) {
				$offset = "+0";
			}
	
			pjAppController::setTimezone('Etc/GMT' . $offset);
			if (strpos($offset, '-') !== false)
			{
				$offset = str_replace('-', '+', $offset);
			} elseif (strpos($offset, '+') !== false) {
				$offset = str_replace('+', '-', $offset);
			}
			pjAppController::setMySQLServerTime($offset . ":00");
		}
	}
	public function getDirection()
	{
		$dir = 'ltr';
		if($this->getLocaleId() != false)
		{
			$locale_arr = pjLocaleModel::factory()->find($this->getLocaleId())->getData();
			$dir = $locale_arr['dir'];
		}
		return $dir;
	}
    public function beforeFilter()
    {
    	$this->appendJs('jquery.min.js', PJ_THIRD_PARTY_PATH . 'jquery/');
		$dm = new pjDependencyManager(PJ_INSTALL_PATH, PJ_THIRD_PARTY_PATH);
		$dm->load(PJ_CONFIG_PATH . 'dependencies.php')->resolve();
		$this->appendJs('jquery-migrate.min.js', $dm->getPath('jquery_migrate'), FALSE, FALSE);
		$this->appendJs('pjAdminCore.js');
		$this->appendCss('reset.css');
		 
		$this->appendJs('js/jquery-ui.custom.min.js', PJ_THIRD_PARTY_PATH . 'jquery_ui/');
		$this->appendCss('css/smoothness/jquery-ui.min.css', PJ_THIRD_PARTY_PATH . 'jquery_ui/');
				
		$this->appendCss('pj-all.css', PJ_FRAMEWORK_LIBS_PATH . 'pj/css/');
		$this->appendCss('admin.css');
		
    	if ($_GET['controller'] != 'pjInstaller')
		{
			$this->models['Option'] = pjOptionModel::factory();
			$this->option_arr = $this->models['Option']->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 getForeignId()
    {
    	return $this->defaultForeignId;
    }
    
    public static function setFields($locale)
    {
    	if(isset($_SESSION['lang_show_id']) && (int) $_SESSION['lang_show_id'] == 1)
		{
			$fields = pjMultiLangModel::factory()
				->select('CONCAT(t1.content, CONCAT(":", t2.id, ":")) AS content, t2.key')
				->join('pjField', "t2.id=t1.foreign_id", 'inner')
				->where('t1.locale', $locale)
				->where('t1.model', 'pjField')
				->where('t1.field', 'title')
				->findAll()
				->getDataPair('key', 'content');
		}else{
			$fields = pjMultiLangModel::factory()
				->select('t1.content, t2.key')
				->join('pjField', "t2.id=t1.foreign_id", 'inner')
				->where('t1.locale', $locale)
				->where('t1.model', 'pjField')
				->where('t1.field', 'title')
				->findAll()
				->getDataPair('key', 'content');
		}
		$registry = pjRegistry::getInstance();
		$tmp = array();
		if ($registry->is('fields'))
		{
			$tmp = $registry->get('fields');
		}
		$arrays = array();
		foreach ($fields as $key => $value)
		{
			if (strpos($key, '_ARRAY_') !== false)
			{
				list($prefix, $suffix) = explode("_ARRAY_", $key);
				if (!isset($arrays[$prefix]))
				{
					$arrays[$prefix] = array();
				}
				$arrays[$prefix][$suffix] = $value;
			}
		}
		require PJ_CONFIG_PATH . 'settings.inc.php';
		$fields = array_merge($tmp, $fields, $settings, $arrays);
		$registry->set('fields', $fields);
    }

    public static function jsonDecode($str)
	{
		$Services_JSON = new pjServices_JSON();
		return $Services_JSON->decode($str);
	}
	
	public static function jsonEncode($arr)
	{
		$Services_JSON = new pjServices_JSON();
		return $Services_JSON->encode($arr);
	}
	
	public static function jsonResponse($arr)
	{
		header("Content-Type: application/json; charset=utf-8");
		echo pjAppController::jsonEncode($arr);
		exit;
	}

	public function getLocaleId()
	{
		return isset($_SESSION[$this->defaultLocale]) && (int) $_SESSION[$this->defaultLocale] > 0 ? (int) $_SESSION[$this->defaultLocale] : false;
	}
	
	public function setLocaleId($locale_id)
	{
		$_SESSION[$this->defaultLocale] = (int) $locale_id;
	}
	
	public function pjActionCheckInstall()
	{
		$this->setLayout('pjActionEmpty');
		
		$result = array('status' => 'OK', 'code' => 200, 'text' => 'Operation succeeded', 'info' => array());
		$folders = array('app/web/backup', 'app/web/upload', 'app/web/upload/lines', 'app/web/upload/lines/source', 'app/web/upload/lines/thumb');
		foreach ($folders as $dir)
		{
			if (!is_writable($dir))
			{
				$result['status'] = 'ERR';
				$result['code'] = 101;
				$result['text'] = 'Permission requirement';
				$result['info'][] = sprintf('Folder \'<span class="bold">%1$s</span>\' is not writable. You need to set write permissions (chmod 777) to directory located at \'<span class="bold">%1$s</span>\'', $dir);
			}
		}
		
		return $result;
	}
	
	public function friendlyURL($str, $divider='-')
	{
		$str = mb_strtolower($str, mb_detect_encoding($str));
		$str = trim($str);
		$str = preg_replace('/[_|\s]+/', $divider, $str);
		$str = preg_replace('/\x{00C5}/u', 'AA', $str);
		$str = preg_replace('/\x{00C6}/u', 'AE', $str);
		$str = preg_replace('/\x{00D8}/u', 'OE', $str);
		$str = preg_replace('/\x{00E5}/u', 'aa', $str);
		$str = preg_replace('/\x{00E6}/u', 'ae', $str);
		$str = preg_replace('/\x{00F8}/u', 'oe', $str);
		$str = preg_replace('/[^a-z\x{0400}-\x{04FF}0-9-]+/u', '', $str);
		$str = preg_replace('/[-]+/', $divider, $str);
		$str = preg_replace('/^-+|-+$/', '', $str);
		return $str;
	}
	public function calcPrices($line_id, $location_id, $traveling, $passengers, $option_arr)
	{
		$sub_total = 0;
		$tax = 0;
		$total = 0;
		$deposit = 0;
		
		$line_arr = pjLineDetailModel::factory()->where('t1.line_id', $line_id)->where('t1.location_id', $location_id)->findAll()->getDataIndex(0);
		
		if(!empty($line_arr))
		{
			$price_per_person = 0;
			if($traveling == 'from')
			{
				$price_per_person = (float) $line_arr['price_dropoff'];
			}else{
				$price_per_person = (float) $line_arr['price_pickup'];
			}
			$sub_total = $passengers * $price_per_person;
			$tax = ($sub_total * $option_arr['o_tax_payment']) / 100;
			$total = $sub_total + $tax;
			$deposit = 	($total * $option_arr['o_deposit_payment']) / 100;
		}
		return compact('sub_total', 'tax', 'total', 'deposit');
	}
	public function pjActionGetLineDetails($line_id, $location_id, $dropoff_id, $traveling, $booking_date)
	{
		$week_number = date('w', strtotime($booking_date));
		$timetable_arr = pjTimetableModel::factory()
			->where('t1.status', 'T')
			->where('t1.location_id', $location_id)
			->where('t1.line_id', $line_id)
			->where('t1.direction', $traveling == 'from' ? 'departing' : 'arriving')
			->where("(t1.every LIKE '%$week_number%')")
			->findAll()
			->getDataIndex(0);
		$line_detail_arr = pjLineDetailModel::factory()->where('t1.line_id', $line_id)->where('t1.location_id', $dropoff_id)->findAll()->getDataIndex(0);
		return compact('timetable_arr', 'line_detail_arr');
	}
	public function getTokens($option_arr, $booking_arr, $salt, $locale_id)
	{
		$country = NULL;
		if (isset($booking_arr['country']) && !empty($booking_arr['country']))
		{
			$country = $booking_arr['country'];
		}
		$name_titles = __('personal_titles', true, false);
		
		$title = !empty($booking_arr['c_title']) ? $name_titles[$booking_arr['c_title']] : NULL;
		$first_name = pjSanitize::clean(@$booking_arr['c_fname']);
		$last_name = pjSanitize::clean(@$booking_arr['c_lname']);
		$phone = pjSanitize::clean(@$booking_arr['c_phone']);
		$email = pjSanitize::clean(@$booking_arr['c_email']);
		$address = pjSanitize::clean(@$booking_arr['c_address']);
		$state = pjSanitize::clean(@$booking_arr['c_state']);
		$city = pjSanitize::clean(@$booking_arr['c_city']);
		$zip = pjSanitize::clean(@$booking_arr['c_zip']);
		$password = NULL;
		if (isset($booking_arr['client_id']) && (int) $booking_arr['client_id'] > 0)
		{
			$client = pjClientModel::factory()->find($booking_arr['client_id'] )->getData();
			$title =  !empty($client['title']) ? $name_titles[$client['title']] : NULL;
			$first_name = pjSanitize::clean($client['fname']);
			$last_name = pjSanitize::clean($client['lname']);
			$phone = pjSanitize::clean($client['phone']);
			$email = pjSanitize::clean($client['email']);
			$address = pjSanitize::clean($client['address']);
			$state = pjSanitize::clean($client['state']);
			$city = pjSanitize::clean($client['city']);
			$zip = pjSanitize::clean($client['zip']);
			$password = pjSanitize::clean($client['password']);
		}
		
		$sub_total = pjUtil::formatCurrencySign(pjUtil::convertToCurrencyFormat($booking_arr['sub_total'], $option_arr), $option_arr['o_currency']);
		$tax = pjUtil::formatCurrencySign(pjUtil::convertToCurrencyFormat($booking_arr['tax'], $option_arr), $option_arr['o_currency']);
		$total = pjUtil::formatCurrencySign(pjUtil::convertToCurrencyFormat($booking_arr['total'], $option_arr), $option_arr['o_currency']);
		$deposit = pjUtil::formatCurrencySign(pjUtil::convertToCurrencyFormat($booking_arr['deposit'], $option_arr), $option_arr['o_currency']);
		
		$booking_date = NULL;
		if (isset($booking_arr['booking_date']) && !empty($booking_arr['booking_date']))
		{
			$tm = strtotime($booking_arr['booking_date'] . ' ' . $booking_arr['booking_time']);
			$booking_date = date($option_arr['o_date_format'] . ', ' . $option_arr['o_time_format'], $tm);
		}
		$return_date = NULL;
		if ($booking_arr['has_return'] == 'T' && isset($booking_arr['return_date']) && !empty($booking_arr['return_date']))
		{
			$tm = strtotime($booking_arr['return_date'] . ' ' . $booking_arr['return_time']);
			$return_date = date($option_arr['o_date_format'], $tm) . ', ' . date($option_arr['o_time_format'], $tm);
		}
		
		$flight_time = null;
		if(!empty($booking_arr['c_flight_time']))
		{
			$flight_time = date($option_arr['o_time_format'], strtotime($booking_arr['c_flight_time']));
		}
		$from = $booking_arr['traveling'] == 'from' ? $booking_arr['from_location'] . ' ('.pjSanitize::html($booking_arr['from_address']).')' : $booking_arr['to_location'] . ' ('.pjSanitize::html($booking_arr['to_address']).')';
		$to = $booking_arr['traveling'] == 'from' ? $booking_arr['to_location'] . ' ('.pjSanitize::html($booking_arr['to_address']).')' : $booking_arr['from_location'] . ' ('.pjSanitize::html($booking_arr['from_address']).')';
		$distance = @$booking_arr['distance'] . ($option_arr['o_mileage'] == 'km' ? 'km' : ($booking_arr['distance'] == 1 ? 'mile' : __('front_miles', true)));
		$duration = @$booking_arr['duration'] . ' ' . __('front_minutes', true);
		$return_duration = @$booking_arr['return_duration'] . ' ' . __('front_minutes', true);
				
		$cancelURL = PJ_INSTALL_URL . 'index.php?controller=pjFrontEnd&action=pjActionCancel&id='.@$booking_arr['id'].'&hash='.sha1(@$booking_arr['id'].@$booking_arr['created'].$salt);
		$cancelURL = '<a href="'.$cancelURL.'">'.$cancelURL.'</a>';
		$search = array(
			'{Title}', '{FirstName}', '{LastName}', '{Email}', '{Password}', '{Phone}', '{Country}', '{City}', '{State}', '{Zip}', '{Address}','{Company}', 
			'{Airline}', '{FlightNumber}', '{ArrivalTime}', '{Terminal}',
			'{CCType}', '{CCNum}', '{CCExp}','{CCSec}', '{PaymentMethod}', 
			'{UniqueID}', '{DateTime}', '{ReturnDateTime}', '{From}', '{To}', '{Line}', '{ReturnLine}',
			'{Passengers}','{Distance}','{Duration}','{ReturnDuration}',
			'{SubTotal}', '{Tax}', '{Total}', '{Deposit}', '{Notes}',
			'{CancelURL}');
		$replace = array(
			$title, $first_name, $last_name, $email, $password, $phone, $country, $city, $state, $zip, $address, pjSanitize::clean(@$booking_arr['c_company']),
			pjSanitize::clean(@$booking_arr['c_airline_company']), pjSanitize::clean(@$booking_arr['c_flight_number']), $flight_time, $booking_arr['c_terminal'],
			@$booking_arr['cc_type'], @$booking_arr['cc_num'], (@$booking_arr['payment_method'] == 'creditcard' ? @$booking_arr['cc_exp_month'] . '-' . @$booking_arr['cc_exp_year'] : NULL), @$booking_arr['cc_code'], @$booking_arr['payment_method'], 
			@$booking_arr['uuid'], $booking_date, $return_date, $from, $to, @$booking_arr['line'], @$booking_arr['return_line'],
			@$booking_arr['passengers'],$distance,$duration, $return_duration,
			@$sub_total, @$tax, @$total, @$deposit, @$booking_arr['c_notes'],
			$cancelURL);

		return compact('search', 'replace');
	}
	public function getClientTokens($option_arr, $client, $salt, $locale_id)
	{
		$name_titles = __('personal_titles', true, false);
		$title =  !empty($client['title']) ? $name_titles[$client['title']] : NULL;
		$first_name = pjSanitize::clean($client['fname']);
		$last_name = pjSanitize::clean($client['lname']);
		$phone = pjSanitize::clean($client['phone']);
		$email = pjSanitize::clean($client['email']);
		$password = $client['password'];
	
		$search = array('{Title}', '{FirstName}', '{LastName}', '{Email}', '{Password}', '{Phone}');
		$replace = array($title, $first_name, $last_name, $email, $password, $phone);
	
		return compact('search', 'replace');
	}
	
	public function getFromEmail($option_arr)
	{
		$email = $option_arr['o_email_address'];
		if($email == '')
		{
			$arr = pjUserModel::factory()->find(1)->getData();
			$email = $arr['email'];
		}
		return $email;
	}
	public function getAdminEmail()
	{
		$arr = pjUserModel::factory()->where('role_id', 1)->findAll()->getDataPair(null, 'email');
		return $arr;
	}
	
	public function getAdminPhone()
	{
		$arr = pjUserModel::factory()
			->findAll()
			->orderBy("t1.id ASC")
			->limit(1)
			->getData();
		return !empty($arr) ? (!empty($arr[0]['phone']) ? $arr[0]['phone'] : null) : null;	
	}
	
	public function pjActionAccountSend($option_arr, $client_id, $salt, $locale_id)
	{
		$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');
	
		$client = pjClientModel::factory()->find($client_id)->getData();
		$tokens = pjAppController::getClientTokens($option_arr, $client, PJ_SALT, $locale_id);
			
		$pjMultiLangModel = pjMultiLangModel::factory();
	
		$locale_id = $this->getLocaleId();
	
		$admin_email = $this->getAdminEmail();
		$from_email = $this->getFromEmail($option_arr);
	
		if ($option_arr['o_email_client_account'] == 1)
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
			->where('t1.model','pjOption')
			->where('t1.locale', $locale_id)
			->where('t1.field', 'o_email_client_account_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_client_account_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['email'])
				->setFrom($from_email)
				->setSubject($lang_subject[0]['content'])
				->send(pjUtil::textToHtml($message));
			}
		}
		if ($option_arr['o_admin_email_client_account'] == 1)
		{
			$lang_message = $pjMultiLangModel->reset()->select('t1.*')
			->where('t1.model','pjOption')
			->where('t1.locale', $locale_id)
			->where('t1.field', 'o_admin_email_client_account_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_client_account_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']);
	
				foreach($admin_email as $k => $email)
				{
					$Email
						->setTo($email)
						->setFrom($from_email)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($message));
				}
			}
		}
	}
	public function pjActionForgotSend($option_arr, $client_id, $salt, $locale_id)
	{
		$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');
	
		$client = pjClientModel::factory()->find($client_id)->getData();
		$tokens = pjAppController::getClientTokens($option_arr, $client, PJ_SALT, $locale_id);
			
		$pjMultiLangModel = pjMultiLangModel::factory();
	
		$locale_id = $this->getLocaleId();
	
		$from_email = $this->getFromEmail($option_arr);
	
		$lang_message = $pjMultiLangModel->reset()->select('t1.*')
			->where('t1.model','pjOption')
			->where('t1.locale', $locale_id)
			->where('t1.field', 'o_email_forgot_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_forgot_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['email'])
			->setFrom($from_email)
			->setSubject($lang_subject[0]['content'])
			->send(pjUtil::textToHtml($message));
		}
	}
	
	public function pjActionConfirmSend($option_arr, $booking_arr, $salt, $opt, $locale_id)
	{
		$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');
	
		$tokens = pjAppController::getTokens($option_arr, $booking_arr, PJ_SALT, $locale_id);
			
		$pjMultiLangModel = pjMultiLangModel::factory();
	
		$admin_email = $this->getAdminEmail();
		$from_email = $this->getFromEmail($option_arr);
		$admin_phone = $this->getAdminPhone();
	
		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($booking_arr['c_email'])
				->setFrom($from_email)
				->setSubject($lang_subject[0]['content'])
				->send(pjUtil::textToHtml($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']);
				foreach($admin_email as $k => $email)
				{
					$Email
						->setTo($email)
						->setFrom($from_email)
						->setSubject($lang_subject[0]['content'])
						->send(pjUtil::textToHtml($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']);
				$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($booking_arr['c_email'])
				->setFrom($from_email)
				->setSubject($lang_subject[0]['content'])
				->send(pjUtil::textToHtml($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']);
				foreach($admin_email as $email)
				{
					$Email
					->setTo($email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
				}
			}
		}
		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']);
				$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($booking_arr['c_email'])
				->setFrom($from_email)
				->setSubject($lang_subject[0]['content'])
				->send(pjUtil::textToHtml($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']);
				foreach($admin_email as $email)
				{
					$Email
					->setTo($email)
					->setFrom($from_email)
					->setSubject($lang_subject[0]['content'])
					->send(pjUtil::textToHtml($message));
				}
			}
		}
	}
}
?>