<?php

/**
 * Description of MainController
 *
 * @author MAKL
 */
abstract class MainController extends Controller {

	protected $user;

	public function AdminLoginRedirectAction($param) {
		$this->AddRedirect(Router::GenerateUrl(array('login' => 'index')), 0);
	}

	/**
	 * Dodatkowy starter kontrolera
	 *
	 */
	protected function Run($param = array()) {
		$urlMain = URL_MAIN;
		$this->smarty->assign('urlMain', $urlMain);
		$this->smarty->assign('pathStatic', PATH_STATIC_CONTENT);
//		$logger = LoggerManager::getLogger(__CLASS__ . ' - ' . __METHOD__);
//		$logger->debug(' ' . serialize($param));
		//Utils::ArrayDisplay($param);

		$location = Config::Get('site');


		switch ($location) {


			case 'Strona':
				session_start();
				if ($param['lang'] == '') {
					$param['lang'] = 'pl';
					Router::$curLang = $param['lang'];
				}
				
				$searchLabel = 'search'.$param['lang'];
				$this->smarty->assign('searchLabel', $searchLabel);

				$analyticsCode = Registry::Get('analytics_code');
				$this->smarty->assign('analyticsCode', $analyticsCode);

				//=====Coockie========================================================
				if (isset($_COOKIE['polityka_akceptacja'])) {
					$polityka_akceptacja = $_COOKIE['polityka_akceptacja'];
				}
				if (isset($polityka_akceptacja)) {
					$this->smarty->assign('polityka_akceptacja', true);
				}
				//--------------------------------------------------------------------

				if (!isset($param['idStructure'])) {
					$getContent = true;
				}

				Dictionary::Init($param['lang']);
				$this->GetRedirectInfo();
				$this->AddTitle(Dictionary::Translate(HEAD_TITLE));

				if (isset($param['idStructure']) && !Utils::CheckPublication($param['idStructure'], 'mf_structure', 'id_mf_structure')) {
					//$logger->debug('nie ma takiej strony, przekierowanie');
					$this->addRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('mainUrl', array()), 0);
				}

				$this->smarty->assign('lang', $param['lang']);
				$this->smarty->assign('title', Dictionary::Translate(HEAD_TITLE));


				//====Script=Loader=========================================================
				$this->addScript('jQuery/jquery.js', 'file', 'top', 1);
				$this->addScript('jQuery/jquery-migrate.min.js', 'file', 'top', 2);
//				$this->AddScript('jQuery/jquery-ui.min.js', 'file', 'top', 7);
//				$this->AddScript('jQuery/jquery.ui.datepicker-pl.js', 'file', 'top', 7);
				$this->AddScript('jQuery/jquery.swipebox.js', 'file', 'top', 2);
				$this->AddScript('gray.js', 'file', 'top', 3);
				$this->AddScript('jQuery/bjqs-1.3.js', 'file', 'top', 4);
				$this->AddScript('init.js', 'file', 'top', 5);
				//$this->AddScript('doubletaptogo.js', 'file', 'top', 6);
				$this->AddScript('jQuery/jquery.sticky.js', 'file', 'top', 7);
				$this->addScript('jQuery/jquery.validate.js', 'file', 'top', 8);
				$this->addScript('jQuery/jquery.flexslider.js', 'file', 'top', 9);
				$this->addScript('jQuery/jquery.scrollex.min.js', 'file', 'top', 10);

				//--------------------------------------------------------------------------
				//===Run=Structure=element==================================================
				if (isset($param['idStructure'])) {
					$objElement = StructureDAL::GetById($param['idStructure'], true);

					if (!is_object($objElement)) {
						MFLog::Debug('brak obiektu, przekierowanie');
						$this->addRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('Index', array()), 0);
					}

					$router = MfRouterDAL::GetById($objElement->GetIdRouter());
					$this->smarty->assign('idModule', $router->GetIdMfModule());
					$param['idModule'] = $router->GetIdMfModule();

//					Utils::ArrayDisplay($objElement);
					//==TODO==Zmianić=na=automat========================
					if (isset($param['idModule']) && $param['idModule'] == 16) {
						$this->smarty->assign('showGallery', true);
					}
					//--end-TODO----------------------------------------

					$this->smarty->assign('title', $objElement->GetName());
					$this->smarty->assign('objElement', $objElement);
					$this->smarty->assign('contentObj', $objElement->GetContent());
					$this->AddTitle($objElement->GetName());
					if (isset($param['urlDetailLabel'])) {
						$this->smarty->assign('labelDetal', $param['urlDetailLabel']);
					}
					//==meta-do-elementu======================
					$objMetaTag = MfMetaTagDAL::GetResult(array('id_source' => $param['idStructure'], 'source_type' => "'mf_structure'"), array());
					if (isset($objMetaTag[0])) {
						$objMetaTag = $objMetaTag[0];
						$descriptionObj = $objMetaTag->GetDescriptionObj();
						$this->smarty->assign('metaDescription', $descriptionObj->GetDescription());
						$this->smarty->assign('metaKeywords', $descriptionObj->GetKeywords());
						$this->smarty->assign('statistic', $descriptionObj->GetStatistic());
					} else {
						$this->smarty->assign('metaDescription', HEAD_DESCRIPTION);
						$this->smarty->assign('metaKeywords', HEAD_KEYWORDS);
						$this->smarty->assign('statistic', '');
					}

					//=====Uruchamianie==ActionSet=====================================
					$actionSetTemplate = '';
					$config = $router->GetConfig();
					$arrayConfig = unserialize($config);
					$actionSet = $arrayConfig['actionSet'];

					if (is_array($actionSet)) {
						foreach ($actionSet as $action) {
							$arrayAction = explode(',', $action);
							$this->RunModuleController($arrayAction[0], $arrayAction[1], $param);
							//Utils::ArrayDisplay('template :'.$arrayAction[1]);
							$actionSetTemplate .= $this->smarty->get_template_vars(strtolower($arrayAction[1]));
							//Utils::ArrayDisplay($this->smarty->get_template_vars($arrayAction[1]));
						}
					}
					//Utils::ArrayDisplay($actionSetTemplate);
					$this->smarty->assign('actionSetTemplate', $actionSetTemplate);

					//-----------------------------------------------------------------
				} else {
					$this->smarty->assign('metaDescription', HEAD_DESCRIPTION);
					$this->smarty->assign('metaKeywords', HEAD_KEYWORDS);
					$this->smarty->assign('statistic', STATISTIC);
				}


				$this->smarty->assign('defaultKeywords', Dictionary::Translate('defaultKeywords'));
				$this->smarty->assign('defaultDescription', Dictionary::Translate('defaultDescription'));

				$this->RunShared('MenuBox', $param);
				$this->RunShared('BanerBox', $param);
				$this->RunShared('News', $param);
				$this->RunShared('GetUrlLang', $param);
//				$this->RunShared('Boxs', $param);
//				$this->RunShared('LogoBoxMedia', $param);
//				$this->RunShared('LogoBox', $param);
				$this->smarty->assign('lang', $param['lang']);

				break;


			case 'Admin':
				$this->GetRedirectInfo();

				$this->AddScript('../../Admin/plugins/ckeditor/ckeditor.js');

				$this->smarty->assign('projectName', PROJECT_NAME);

				if (SessionProxy::GetValue('lang')) {
					$param['lang'] = SessionProxy::GetValue('lang');
					Router::$curLang = $param['lang'];
				}

				if (isset($param['lang'])) {
					if ($param['lang'] == '') {
						$param['lang'] = 'pl';
						Router::$curLang = $param['lang'];
						SessionProxy::SetValue('lang', $param['lang']);
					} else {
						Router::$curLang = $param['lang'];
						SessionProxy::SetValue('lang', $param['lang']);
					}
				} else {
					if (!SessionProxy::GetValue('lang')) {
						$param['lang'] = 'pl';
						Router::$curLang = $param['lang'];
						SessionProxy::SetValue('lang', $param['lang']);
					} else {
						$param['lang'] = SessionProxy::GetValue('lang');
						Router::$curLang = $param['lang'];
					}
				}

				if (isset($param['location'])) {
					if ($param['location'] == '') {

						$param['location'] = '1';

						SessionProxy::SetValue('location', $param['location']);
					} else {

						SessionProxy::SetValue('location', $param['location']);
					}
				} else {
					if (!SessionProxy::GetValue('location')) {
						$param['location'] = '1';
						SessionProxy::SetValue('location', $param['location']);
					} else {
						$param['location'] = SessionProxy::GetValue('location');
					}
				}

				if (SessionProxy::GetValue('location')) {
					$param['location'] = SessionProxy::GetValue('location');
				}


				$this->RunShared('DefaultPanel', $param);
				//Utils::ArrayDisplay($param);
				if ((isset($param['Structure']) || isset($param['structure'])) && isset($param['id']) && $param['id'] != -1) {

					$id = $param['id'];
					$objElement = StructureDAL::GetById($id);
					if (is_object($objElement)) {

						$router = MfRouterDAL::GetById($objElement->GetIdRouter());

						if ($objElement->GetIdRouter() > 0) {

							if (($router->GetLang() != $param['lang'])) {

								$idRouter = MfRouterDAL::AddRouterByStructure($router, $objElement, $param['lang']);

								$router = MfRouterDAL::GetById($idRouter);
							}
						}


						if ($objElement->GetIdRouter() == 0) {
							$objModule = MfModuleDAL::GetById(22);
						} else {
							$unserializedParam = unserialize($router->GetParam());
							SessionProxy::SetValue('idCategory', $unserializedParam['idCategory']);
							SessionProxy::SetValue('router', $router);
							SessionProxy::SetValue('idStructure', $id);
							$objModule = MfModuleDAL::GetById($router->GetIdMfModule());
						}

						SessionProxy::SetValue('objModule', $objModule);
					} else {
						Utils::Redirect(Router::GenerateUrl('Index', array()));
					}
				}


				$this->AddScript('jQuery/jquery.js', 'file', 'top', 1);
				$this->AddScript('jQuery/jquery-ui.js', 'file', 'top', 2);
				$this->AddScript('jQuery/jquery-ui-timepicker-addon.js', 'file', 'top', 3);
				$this->AddScript('jQuery/jquery.uploadify.v2.1.4.min.js', 'file', 'top', 4);
				$this->AddScript('dropDown.js', 'file', 'top', 5);
				$this->smarty->assign('lang', SessionProxy::GetValue('lang'));
				$this->smarty->assign('admin', Registry::Get('admin'));
				$this->smarty->assign('galleryUrlLabel', 'customerEdit' . SessionProxy::GetValue('lang'));

				break;
		}
	}

	protected function Seo($class = __CLASS__, $method = __METHOD__) {


		$seoObj = WpSeoDAL::GetByType(WpSeo::GetMapByController($class . $method));
		if (isset($seoObj) && is_object($seoObj)) {
			if ($seoObj->getTitle() != '') {

				$this->AddTitle($seoObj->getTitle());
			}
			if ($seoObj->getDescription() != '') {
				$this->AddDescription($seoObj->getDescription());
			}
			if ($seoObj->getKeywords() != '') {
				$this->AddKeywords($seoObj->getKeywords());
			}
		}
	}

	public function Error404Action($param) {
		$this->SetAjaxRender();
		//Utils::ArrayDisplay($param);
		//$this->SetNoRender();
		//header("Status: 404 Not Found");
		//Utils::ArrayDisplay($param);
		//$this->content=file_get_contents('error.html');
		//include("error.html");
		header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
		//$this->AddRedirect('error.html', 0);
		$this->AddRedirectInfo('wybrana strona nie istnieje', null, Router::GenerateUrl('urlMain', array('lang' => $param['lang'])), 0, 404);
	}

	/**
	 * informacjay o przekierowaniu
	 *
	 * @param string $url
	 * @param string $info
	 */
	protected function AddRedirectInfo($info, $type = null, $url = null, $jsRedirect = false) {
		Utils::ArrayDisplay($info);
		SessionProxy::SetValue("frameInfo", $info);

		if ($type != null) {
			SessionProxy::SetValue("frameType", $type);
		}

		if ($url != null && $jsRedirect == false)
			$this->AddRedirect($url, 0);
		else if ($url != null)
			$this->content = "document.location.href='$url';";
	}

	protected function AddInfo($info, $type) {
		$this->RunShared('infoFrame', array('type' => $type, 'info' => $info), true, true);
	}

	/**
	 * Pobranie informacji o przekierowaniu
	 *
	 */
	private function GetRedirectInfo() {
		
		if (SessionProxy::GetValue("frameInfo") != "") {
			$this->AddInfo(SessionProxy::GetValue("frameInfo"), SessionProxy::GetValue('frameType'));

			SessionProxy::ClearValue('frameType');
			SessionProxy::ClearValue('frameInfo');
			SessionProxy::ClearValue('sendFormInfo');
		}
	}

	/**
	 * Kontrola sesji usera
	 *
	 */
	public function CheckLogin() {
		//	session_start();
		//Utils::ArrayDisplay('sds');
		$this->user = AuthDAL::GetUser();
		Registry::Set('user', $this->user);
		$this->smarty->assign('userObj', $this->user);
		$this->UserSession();
	}

	/**
	 * Weryfikacja czy user jest zalogowany
	 *
	 * @return boolean
	 */
	public function IsUser() {
		if (is_object($this->user)) {

			return true;
		} else {
			return false;
		}
	}

	protected function UserSession() {
		if ($this->user) {
			$id = $this->user->GetId();
			if (!empty($id) && (int) $id > 0) {
				ActiveChecker::Touch($id);
			}
		}
	}

	protected function RemoveUserSession() {
		if ($this->user) {
			$id = $this->user->GetId();
			if (!empty($id) && (int) $id > 0) {
				ActiveChecker::Remove($id);
			}
		}
	}

	protected function FormatAjaxOutput($errors, $param) {
		$out = array();
		$validateField = null;
		if (Request::Check('validate'))
			$validateField = Request::GetPost('validate');
		if (isset($param['redirect']) && !isset($param['field'])) {
			$out['redirect'] = $param['redirect'];
		}
		if (empty($errors)) {
			$out['success'] = true;
		} else {
			$out['fields'] = array();
			foreach ($errors as $row) {
				if (isset($param['field'])) {
					if ($param['field'] == $row['field'] || $row['field'] == urldecode($param['field'])) {
						$out['fields'][$param['field']] = $row;
					} elseif ($validateField == $row['field']) {
						$out['fields'][$validateField] = $row;
					}
				} else {
					$out['fields'][$row['field']] = $row;
				}
			}
			if (!empty($out['fields'])) {
				$out['success'] = false;
			} else {
				$out['success'] = true;
			}
		}
		if (isset($param['msg'])) {
			$out['msg'] = $param['msg'];
		}
		if (isset($param['hide'])) {
			$out['hide'] = $param['hide'];
		}
		return json_encode($out);
	}

	public final function GeneratePopover($title, $image, $message, $buttons, $inputText = false) {
		$this->SetAjaxRender(true);
		$this->smarty->assign('popoverButtons', $buttons);
		$this->smarty->assign('popoverTitle', $title);
		$this->smarty->assign('popoverImage', $image);
		$this->smarty->assign('popoverMessage', $message);
		$this->smarty->assign('popoverInputText', $inputText);

		return $this->smarty->fetch('partial/Popover/PopoverSmall.tpl');
	}

	public function GetDictionary($keyword, $replacement = array()) {
		$dictionaryArray = Registry::Get("dictionary");
		return vsprintf($dictionaryArray[$keyword], $replacement);
	}

	private function LoadDictionary($lang = "pl") {
		Registry::Set("dictionary", MfDictionaryDAL::GetAllVariables($lang, 36000));
	}

}

?>