<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjFront extends pjAppController
{	
	public $defaultCaptcha = 'pjProductComparison_Captcha';
	
	public $defaultLocale = 'pjProductComparison_LocaleId';
	
	public $defaultIndex = 'pjProductComparison_Index';
	
	public $defaultLangMenu = 'pjProductComparison_LangMenu';
	
	public $defaultStore = 'pjProductComparison_Store';
	
	public function __construct()
	{
		$this->setLayout('pjActionFront');
		self::allowCORS();
	}
	
	private function _get($key)
	{
		if ($this->_is($key))
		{
			return $_SESSION[$this->defaultStore][$key];
		}
		return false;
	}
	
	private function _is($key)
	{
		return isset($_SESSION[$this->defaultStore]) && isset($_SESSION[$this->defaultStore][$key]);
	}
	
	private function _set($key, $value)
	{
		$_SESSION[$this->defaultStore][$key] = $value;
		return $this;
	}

	public function afterFilter()
	{		
		if (!isset($_GET['hide']) || (isset($_GET['hide']) && (int) $_GET['hide'] !== 1) &&
			in_array($_GET['action'], array('pjActionSearch', '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']);
				
				pjAppController::setFields($this->getLocaleId());
				
				$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 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'];
		$fonts = $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'];
			$fonts = $_GET['theme'];
		}
		$arr = array(
				array('file' => "$fonts.css", 'path' => PJ_CSS_PATH . "fonts/"),
				array('file' => 'style.css', 'path' => PJ_CSS_PATH),
				array('file' => "$theme.css", 'path' => PJ_CSS_PATH . "themes/",
				array('file' => 'transitions.css', 'path' => PJ_CSS_PATH))
		);
		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',
								"pjWrapperProductComparison_" . $theme
						),
						$string
				) . "\n";
			}
		}
		exit;
	}
	
	public function pjActionLoad()
	{
		ob_start();
		header("Content-Type: text/javascript; charset=utf-8");
		
		if(isset($_GET['locale']) && $_GET['locale'] > 0)
		{
			$_SESSION[$this->defaultLocale] = (int) $_GET['locale'];
			$_SESSION[$this->defaultLangMenu] = 'hide';
		}else{
			$_SESSION[$this->defaultLangMenu] = 'show';
		}
	}
	
	public function pjActionIndex()
	{
		$this->setAjax(true);
		
		if ($this->isXHR() || isset($_GET['_escaped_fragment_']))
		{
			$pjProductFeatureModel = pjProductFeatureModel::factory();

			$product_arr = pjProductModel::factory()
				->select('t1.*, t2.content AS name, t3.content AS description')
				->join('pjMultiLang', "t2.model='pjProduct' AND t2.foreign_id=t1.id AND t2.field='product_name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjProduct' AND t3.foreign_id=t1.id AND t3.field='product_description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->find($_GET['product_id'])
				->getData();
			
			$model_arr = pjProductModModel::factory()
				->select('t1.*, t2.content AS name, t3.content AS description')
				->join('pjMultiLang', "t2.model='pjProductMod' AND t2.foreign_id=t1.id AND t2.field='model_name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjProductMod' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->where('product_id', $_GET['product_id'])
				->findAll()
				->getData();
				
			$category_arr = pjCategoryModel::factory()
				->select('t1.*, t2.content AS name, t3.content as description')
				->join('pjMultiLang', "t2.model='pjCategory' AND t2.foreign_id=t1.id AND t2.field='name' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->join('pjMultiLang', "t3.model='pjCategory' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
				->where("t1.id IN(SELECT TPC.category_id FROM `".pjProductCategoryModel::factory()->getTable()."` AS TPC WHERE TPC.product_id = '".$_GET['product_id']."')")
				->where('t1.status', 'T')
				->orderBy("`order` ASC")
				->findAll()
				->getData();
			$grid_arr = array();
			$empty_id_arr = array();
			
			if($this->_is('model_' . $_GET['product_id']))
			{
				$model_id_arr = $this->_get('model_' . $_GET['product_id']);
				if(count($model_id_arr))
				{
					$feature_mod_arr = pjFeatureModModel::factory()
						->select('t1.*, t2.content as title')
						->join('pjMultiLang', "t2.model='pjFeatureMod' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
						->where("t1.model_id IN(".join(',', $model_id_arr).")")
						->findAll()
						->getData();
					
					foreach($feature_mod_arr as $k => $v)
					{
						$grid_arr[$v['feature_id']][$v['model_id']] = $v;
					}
					
					foreach($grid_arr as $k => $v)
					{
						$has_value = false;
						foreach($v as $cell)
						{
							if($cell['title'] != '')
							{
								$has_value = true;
								break;
							}
						}
						if($has_value == false)
						{
							$empty_id_arr[] = $k;
						}
					}
					if(!empty($empty_id_arr))
					{
						foreach($empty_id_arr as $v)
						{
							unset($grid_arr[$v]);
						}
					}
					foreach($category_arr as $k => $v)
					{
						$pjProductFeatureModel
							->reset()
							->select('t1.*, t2.content AS title, t3.content as description')
							->join('pjMultiLang', "t2.model='pjProductFeature' AND t2.foreign_id=t1.id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
							->join('pjMultiLang', "t3.model='pjProductFeature' AND t3.foreign_id=t1.id AND t3.field='description' AND t3.locale='".$this->getLocaleId()."'", 'left outer')
							->where('t1.category_id', $v['id'])
							->where("t1.id IN(SELECT `TFM`.`feature_id` FROM `".pjFeatureModModel::factory()->getTable()."` AS `TFM`)");
						if(!empty($empty_id_arr))
						{
							$pjProductFeatureModel->whereNotIn('t1.id', $empty_id_arr);
						}
						$v['features'] = $pjProductFeatureModel
							->where('t1.status', 'T')
							->orderBy("`order` ASC")
							->findAll()
							->getData();
						$category_arr[$k] = $v;
					}
				}
			}
			
			$this->set('product_arr',$product_arr);
			$this->set('model_arr',$model_arr);
			$this->set('category_arr',$category_arr);
			$this->set('grid_arr',$grid_arr);
		}
	}
	
	public function pjActionSetModel()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$resp = array();
			if (!isset($_SESSION[$this->defaultStore]) || count($_SESSION[$this->defaultStore]) === 0)
			{
				$_SESSION[$this->defaultStore] = array();
			}
			if(isset($_GET['model_id']) && (int) $_GET['model_id'] > 0)
			{
				if($this->_is('model_' . $_GET['product_id']))
				{
					$model_arr = $this->_get('model_' . $_GET['product_id']);
					if(in_array($_GET['model_id'], $model_arr))
					{
						$model_arr = array_diff($model_arr, array($_GET['model_id']));
						if(empty($model_arr))
						{
							$_SESSION[$this->defaultStore]['model_' . $_GET['product_id']];
						}
					}else{
						$model_arr[] = $_GET['model_id'];
					}
				}else{
					$model_arr = array();
					$model_arr[] = $_GET['model_id'];
				}
				$this->_set('model_' . $_GET['product_id'], $model_arr);
				$resp['code'] = 200;
			}else{
				$resp['code'] = 100;
			}
			
			pjAppController::jsonResponse($resp);
		}
	}
	
	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="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
		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");
	}
}
?>