<?php
	Class Layout {
		
		public $locale;
		protected $config;
		protected $settings;
			
		function __construct() {
			global $locale, $config;
			
			$this->locale = $locale;
			$this->config = $config;
			$this->settings = $this->config['settings'];
		}
		
		public function getPage($file) {
			$cache = $this->settings['cache-layout'];
			
			$file_path = LAYOUTS_DIR.$file.'.php';
			
			if (file_exists($file_path)) {
				
				if ($cache) {
					return $this->cacheFile($file, $this->requireFile($file_path));
				} else {
					return $this->requireFile($file_path);
				}
				
			} else {
				return 'Layout file not found in '.LAYOUTS_DIR;
			}
		}
		
		public function setFileTimestamp() {
			$ts = '';
			
			if ($this->settings['debug']) {
				$ts = '?t='.time();
			}
			
			return $ts;
		}
		
		public function getPublicUri() {
			$protocol = $this->settings['http-protocol'];
			$domain = $_SERVER['SERVER_NAME'];
			
			return $protocol.$domain.'/';
		}
		
		private function requireFile($file_path) {
			$ob_string = $this->config['settings']['gzip-content'] ? 'ob_gzhandler' : '';		
			ob_start($ob_string);
		    require($file_path);
		    return ob_get_clean();
		}
		
		private function cacheFile($file_name, $file_data=null) {
			
			$cache_dir = CACHE_DIR.'Layouts/';
			
			if (is_writable($cache_dir)) {
				$file_path = $cache_dir.$file_name.'-cache.html';
				
				if (!file_exists($file_path)) {
					file_put_contents($file_path, $file_data);
				}
				
				return file_get_contents($file_path);
			} else {
				return 'Layout cache directory is not writable.';
			}
		}
	}