<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjWeb extends pjAppController
{
	public $defaultLocale = 'web_locale_id';
	
	public $defaultItemPerPage = 'web_item_per_page';
	
	public $defaultCaptcha = 'web_captcha';
	
	public $defaultCommentCaptcha = 'web_comment_captcha';
	
	public $defaultFormRegister = 'web_form_register';
	
	protected $locales = array();
	
	public function __construct()
	{
		$this->setLayout('pjActionWeb');
	}
	
	public function afterFilter()
	{
		
	}
	
	public function beforeFilter()
	{
		$locale_arr = pjLocaleModel::factory()->select('t1.*, t2.file, t2.title')
			->join('pjLocaleLanguage', 't2.iso=t1.language_iso', 'left outer')
			->where('t2.file IS NOT NULL')
			->orderBy('t1.sort ASC')->findAll()->getDataPair('id');
		
		$this->set('locale_arr', $locale_arr);
		
		foreach ($locale_arr as $locale)
		{
			$this->locales[$locale['language_iso']] = $locale['id'];
		}
		
		if (isset($_GET['language']) && array_key_exists($_GET['language'], $this->locales))
		{
			$this->setLocaleId($this->locales[$_GET['language']]);
		}
		
		$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']);
				pjUtil::redirect(PJ_INSTALL_URL . $locale_arr[0]['language_iso'] . '/', 301);
			}
		}
		
		$this->loadSetFields();
		
		$this->appendJs('jquery-1.11.0.min.js', PJ_THIRD_PARTY_PATH . 'jquery/');
		$this->appendCss('pjWeb.css');
		$this->appendJs('pjWeb.js');
	}
	
	protected static function pjActionNotFound()
	{
		header("HTTP/1.1 404 Not Found");
		header("Location: " . PJ_INSTALL_URL);
		exit;
	}
	
	public function beforeRender()
	{
		$this->set('page_arr', pjPageModel::factory()
			->select('t1.id, t1.seo_url, t1.status')
			->findAll()
			->getDataPair('id')
		);
	}

	public function pjActionSetLocale()
	{
		$this->setLocaleId(@$_GET['locale']);
		pjUtil::redirect($_SERVER['HTTP_REFERER']);
	}
	
 	public function getLanguage()
    {
    	$language = array_search($this->getLocaleId(), $this->locales);
    	
    	return $language !== FALSE ? $language : 'en';
    }
}
?>