<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAppController extends pjController
{
	public $models = array();

	/**
	 * Generate (or return existing) CSRF token for the current session.
	 */
	public static function getCsrfToken()
	{
		if (empty($_SESSION['csrf_token']))
		{
			$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
		}
		return $_SESSION['csrf_token'];
	}

	/**
	 * Validate CSRF token (admin POST; reads POST field or X-CSRF-Token header; no URL slug).
	 */
	public static function validateCsrfToken()
	{
		$token = '';
		if (!empty($_POST['csrf_token'])) {
			$token = $_POST['csrf_token'];
		} elseif (!empty($_SERVER['HTTP_X_CSRF_TOKEN'])) {
			$token = $_SERVER['HTTP_X_CSRF_TOKEN'];
		}
		if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], (string) $token))
		{
			header('HTTP/1.1 403 Forbidden');
			exit('Invalid CSRF token.');
		}
	}
	
	public $option_arr = array();
	
	public $defaultLocale = 'admin_locale_id';
  
	public $defaultFields = 'fields';
	
	public $defaultFieldsIndex = 'fields_index';
	
	public $defaultTheme = 'front_theme_id';
  
	protected function loadSetFields($force=FALSE)
	{
		$registry = pjRegistry::getInstance();
		if ($force
			|| !isset($_SESSION[$this->defaultFieldsIndex])
			|| (isset($this->option_arr['o_fields_index']) && $_SESSION[$this->defaultFieldsIndex] != $this->option_arr['o_fields_index'])
			|| !isset($_SESSION[$this->defaultFields])
			|| empty($_SESSION[$this->defaultFields]))
		{
			pjAppController::setFields($this->getLocaleId());
			 
			# Update session
			if ($registry->is('fields'))
			{
				$_SESSION[$this->defaultFields] = $registry->get('fields');
			}
			if(isset($this->option_arr['o_fields_index']))
			{
				$_SESSION[$this->defaultFieldsIndex] = $this->option_arr['o_fields_index'];
			}
		}
	
		if (isset($_SESSION[$this->defaultFields]) && !empty($_SESSION[$this->defaultFields]))
		{
			# Load fields from session
			$registry->set('fields', $_SESSION[$this->defaultFields]);
		}
								 
		return TRUE;
	}
	
	public function isCountryReady()
    {
    	return $this->isAdmin();
    }
    
	public function isOneAdminReady()
    {
    	return $this->isAdmin();
    }
    
    public function isWebsiteContentReady()
    {
    	return $this->isAdmin();
    }
    
    public function isContactFormReady()
    {
    	return $this->isAdmin();
    }
	
	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 beforeFilter()
    {
		if (strtoupper(@$_SERVER['REQUEST_METHOD']) === 'POST')
		{
			$_csrf_ctrl = isset($_GET['controller']) ? $_GET['controller'] : '';
			$_csrf_act = isset($_GET['action']) ? $_GET['action'] : '';
			if (strpos($_csrf_ctrl, 'pjAdmin') === 0
				&& !in_array($_csrf_act, array('pjActionLogin', 'pjActionForgot', 'pjActionLogout', 'pjActionPreview'), true)) {
				pjAppController::validateCsrfToken();
			}
		}

    	$this->appendJs('jquery-1.8.2.min.js', PJ_THIRD_PARTY_PATH . 'jquery/');
    	$this->appendJs('pjAdminCore.js');
    	$this->appendCss('reset.css');
    	
    	$this->appendJs('jquery-ui.custom.min.js', PJ_THIRD_PARTY_PATH . 'jquery_ui/js/');
		$this->appendCss('jquery-ui.min.css', PJ_THIRD_PARTY_PATH . 'jquery_ui/css/smoothness/');
				
		$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 isEditor()
    {
    	return $this->getRoleId() == 2;
    }
    
    public function isOwner()
    {
    	return $this->getRoleId() == 3;
    }
    
    public function getForeignId()
    {
    	if($this->isOwner())
    	{
    		return $this->getUserId();
    	}else{
    		return 1;
    	}
    }
    
    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 setTheme($theme)
	{
		$_SESSION[$this->defaultTheme] = $theme;
	}
	
	public function getTheme()
	{
		return isset($_SESSION[$this->defaultTheme]) && !empty($_SESSION[$this->defaultTheme]) ? $_SESSION[$this->defaultTheme] : false;
	}
	
	public function pjActionAfterInstall()
	{
		$this->setLayout('pjActionEmpty');
		$pjOptionModel = pjOptionModel::factory();
		$pjOptionModel->initMultiLang(1, 1);
		$pjOptionModel->updateListingPage();
		return array('status' => 'OK', 'code' => 200, 'text' => 'Operation succeeded');
	}
	
	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 getAdminEmail()
	{
		$arr = pjUserModel::factory()
			->findAll()
			->orderBy("t1.id ASC")
			->limit(1)
			->getData();
		return !empty($arr) ? $arr[0]['email'] : null;	
	}
	
	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 getPrices($price, $option_arr)
	{
		$tax = 0;
		$deposit = 0;
		$subtotal = $price;
		if($option_arr['o_tax_payment'] > 0)
		{
			$tax = ($subtotal * $option_arr['o_tax_payment']) / 100;
		}
		$total = $subtotal + $tax;
		if($option_arr['o_deposit_payment'] > 0)
		{
			$deposit =($total * $option_arr['o_deposit_payment']) / 100;
		}
		return compact('subtotal', 'tax', 'total', 'deposit');
	}
	
	public function calPrices($listing_id, $week, $option_arr)
	{
		$arr = pjPriceModel::factory()
			->where('listing_id', $listing_id)
			->where("DATE_FORMAT(t1.start_date,'%Y-%m-%d')", date('Y-m-d', $week))
			->limit(1)
			->findAll()
			->getData();
		if(count($arr) == 1)
		{
			return $this->getPrices($arr[0]['price'], $option_arr);
		}else{
			return false;
		}
	}
	
	public function getData($option_arr, $booking_arr, $salt, $locale_id)
	{
		$personal_titles = __('personal_titles', true, false);
		$cancelURL = PJ_INSTALL_URL . 'index.php?controller=pjListings&action=pjActionCancel&id='.@$booking_arr['id'].'&hash='.sha1(@$booking_arr['id'].@$booking_arr['created'].$salt);
		$cancelURL = '<a href="'.$cancelURL.'">'.$cancelURL.'</a>';
	
		$search = array(
			'{Title}',
			'{Name}',
			'{Email}',
			'{Phone}',
			'{Country}',
			'{City}',
			'{State}',
			'{Zip}',
			'{Address}',
			'{Company}',
			'{Notes}',
			'{Yacht}',
			'{BookingID}',
			'{BookingTime}',
			'{SubTotal}',
			'{Tax}',
			'{Total}',
			'{Deposit}',
			'{PaymentMethod}',
			'{CCType}',
			'{CCNum}',
			'{CCExp}',
			'{CCSec}',
			'{CancelURL}',
		);
		$replace = array(
			(!empty($booking_arr['c_title']) ? $personal_titles[$booking_arr['c_title']] : null),
			$booking_arr['c_name'],
			$booking_arr['c_email'],
			$booking_arr['c_phone'],
			$booking_arr['country_title'],
			$booking_arr['c_city'],
			$booking_arr['c_state'],
			$booking_arr['c_zip'],
			$booking_arr['c_address'],
			$booking_arr['c_company'],
			$booking_arr['c_notes'],
			$booking_arr['title'],
			$booking_arr['uuid'],
			__('front_week', true) . ' '. date('W', strtotime($booking_arr['week_start'])). ' '. date($option_arr['o_date_format'], strtotime($booking_arr['week_start'])) . ' - '. date($option_arr['o_date_format'], strtotime($booking_arr['week_start']) + (6 * 60 * 60 * 24) ),
			pjUtil::formatCurrencySign($booking_arr['sub_total'], $option_arr['o_currency']),
			pjUtil::formatCurrencySign($booking_arr['tax'], $option_arr['o_currency']),
			pjUtil::formatCurrencySign($booking_arr['total'], $option_arr['o_currency']),
			pjUtil::formatCurrencySign($booking_arr['deposit'], $option_arr['o_currency']),
			@$booking_arr['payment_method'],
			@$booking_arr['cc_type'],
			@$booking_arr['cc_number'],
			(@$booking_arr['payment_method'] == 'creditcard' ? @$booking_arr['cc_exp'] : NULL),
			@$booking_arr['cc_code'],
			$cancelURL
		);
	
		return compact('search', 'replace');
	}
}
?>