<?php

class Configs extends Controller{

	//! HTTP route pre-processor
	/**
	 * @param $f3 \Base
	 */
	function beforeroute($f3) {
		parent::beforeroute($f3);

		// Only super admins can use this class
		if ($f3->get('USER')->role < 9){
			$f3->error(403);
		}
	}

	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getEdit($f3, $params){

		$config = new \Models\Config();
		$config->load(array('_id = ?', 1));
		if ($config->dry()) $f3->reroute('/index.php');

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1){
			$config->paypal_api_username = null;
			$config->paypal_api_password = null;
			$config->paypal_api_signature = null;
			$config->stripe_publishable_key = null;
			$config->stripe_secret_key = null;
			$config->coinbase_api_key = null;
			$config->coinbase_api_secret = null;
			$config->mail_smtp_username = null;
			$config->mail_smtp_password = null;
		}

		$f3->set('config', $config);

		// Template settings
		$f3->set('active','configs');
		$f3->set('inc','configs-edit.html');
		$f3->set('inc_bottom', 'configs-edit-bottom.html');
		$f3->set('title',$f3->get('lang_configuration'));
		$f3->set('time_last_updated', date('Y/m/d H:i:s', $config->last_updated));

		$f3->set('templates',$this->_getTemplates());
		$f3->set('themes',$this->_getThemes($config->site_template));

		echo Template::instance()->render('layout.html');
	}

	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postEdit($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php');

		try {
			$params['id'] = 1;
			if (!file_exists(dirname(__FILE__) .'/../../ui/'.$f3->get('POST.site_template').'/assets/css/theme-'.$f3->get('POST.site_theme').'.css'))
				$f3->set('POST.site_theme', null);
			$res_config = new \Models\Config();
			$result = $res_config->post($f3, $params, false);
			$result ? $f3->reroute('/index.php') : $f3->reroute('/index.php?config');

		} catch (Exception $e){
			Utils::Logger('postEdit:Error posting config - '.$e);
		}

	}

	/** Get template options for select list - uses ddslick library
	 */
	private function _getTemplates(){
		$uiDir =dirname(__FILE__) .'/../../ui/*';
		$rawDirs = array_filter(glob($uiDir), 'is_dir');
		$templates = array();
		foreach ($rawDirs as $rawDir) {
			$dirName = basename($rawDir);
			if (file_exists($rawDir.'/template.ini')){
				$imagesrc = (file_exists($rawDir.'/screenshot.jpg')) ? 'data-imagesrc="'.'ui/'.$dirName.'/screenshot.jpg"' : 'data-imagesrc="ui/default/assets/img/screenshot-default.jpg"';
				$template = parse_ini_file($rawDir.'/template.ini');
				$description = 'data-description="'.$template['author'].' '.$template['url'].'"';
				$optionText = $template['name'].' '.$template['version'];
				$templates[] = array(
					'imagesrc' => $imagesrc,
					'description' => $description,
					'optiontext' => $optionText,
					'optionvalue' => $dirName
				);
			} else {
				$templates[] = array(
						'imagesrc' => 'data-imagesrc="ui/default/assets/img/screenshot-default.jpg"',
						'description' => $dirName,
						'optiontext' => $dirName,
						'optionvalue' => $dirName
				);
			}
		}
		return $templates;
	}


	/** Get theme options for select list - uses ddslick library
	 * @param $f3 \Base
	 * @param $params
	 */
	private function _getThemes($template){
		if (empty($template)) return ('');

		$templateDir = dirname(__FILE__) .'/../../ui/'.$template.'/assets/css';
		$themeFiles =$templateDir.'/theme-*.css';
		$rawFiles = array_filter(glob($themeFiles), 'is_file');

		$themes = array();
		$keys = array();
		if (!file_exists($templateDir.'/theme.ini')){
			$template = 'default';
			$templateDir = dirname(__FILE__) .'/../../ui/'.$template.'/assets/css';
		}
		$theme = parse_ini_file($templateDir.'/theme.ini', true);
		$keys = array_keys($theme);

		foreach ($keys as $key) {
			$key = strtolower($key);
			if (file_exists($templateDir.'/theme-'.$key.'.css')){
				$imagesrc = (file_exists($templateDir.'/theme-'.$key.'-screenshot.jpg')) ? 'data-imagesrc="'.'ui/'.$template.'/assets/css/theme-'.$key.'-screenshot.jpg"' : 'data-imagesrc="ui/default/assets/img/screenshot-default.jpg"';
				$description = 'data-description="'.$theme[$key]['author'].' '.$theme[$key]['url'].'"';
				$optionText = $theme[$key]['name'].' '.$theme[$key]['version'];
				$themes[] = array(
						'imageSrc' => $imagesrc,
						'description' => $description,
						'text' => $optionText,
						'value' => $key,
						'selected' => false
				);
			}

		}

		return ($themes);
	}


	/** Get theme options [ajax]
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getThemesOptions($f3, $params){
		$template = $f3->get('PARAMS.template');
		if (empty($template)) return;

		$themes = $this->_getThemes($template);

		echo (json_encode($themes));
	}


	/** Check for GeoIP DB Update [ajax]
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getGeoIpDatabaseUpdate($f3, $params){
		echo (json_encode(Utils::CheckGeoIPDBUpdate()));
	}


	/** Backup the database [ajax]
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getDatabaseBackup($f3, $params){
		echo (json_encode(Utils::BackupDB()));
	}

	/** Update mysa [ajax]
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getMysaUpdate($f3, $params){
		echo (json_encode(Utils::getMysaUpdate()));
	}

	/** Clean cache [ajax]
	 * @param $f3 \Base
	 * @param $params
	 */
	public function getCleanCache($f3, $params){
		echo (json_encode(Utils::CleanCache()));
	}
}