<?php 

class theme {

	public $theme;
	public $theme_root;

	public function __construct($app) {
		$this->app = $app;
		$this->theme = ($option = get_option("current_theme")) ? $option : "default";
		$this->theme_root = "contents/themes/".$this->theme;
		$this->themespath = ABSPATH."contents/themes/";
		$this->primary_color = ($option = get_option('primary_color')) ? $option : "#337ab7";
		$this->secondary_color = ($option = get_option('secondary_color')) ? $option : "#1a2226";
	}

	public function load() {
		$app = $this->app;
		$post_meta = $this->app->post_meta;
		$user_meta = $this->app->user_meta;
		$page_cache = $this->has_cache();
		if($page_cache) {
			echo $page_cache;
			return;
		}
		$functions = "contents/themes/".$this->theme."/functions.php";
		if(file_exists($functions)) {
			require_once($functions);
		}
		$default = "contents/themes/".$this->theme."/".$this->theme.".php";
		if(isset($_GET['media']) && (strtolower($_GET['media']) === "print")) {
			$template = apply_filters("template_print", "contents/themes/".$this->theme."/template-print.php", $post_meta);
			if(file_exists($template)) {
				ob_start();
				require_once($template);
				require_once("contents/themes/print.php");
				$content = ob_get_contents();
				ob_get_clean();
				echo $this->cache_page($content);
				return;
			}	
		}
		if(isset($_POST['page_template'])) {
			$template = apply_filters("template_".$_POST['page_template'], "contents/themes/".$this->theme."/template-".$_POST['page_template'].".php", $post_meta);
			if(file_exists($template)) {
				ob_start();
				require_once($template);
				$content = ob_get_contents();
				ob_get_clean();
				echo $this->cache_page($content);
				return;
			}
		}
		if(isset($_GET['template'])) {
			$template = apply_filters("template_".$_GET['template'], "contents/themes/".$this->theme."/template-".$_GET['template'].".php", $post_meta);
			if(file_exists($template)) {
				ob_start();
				require_once($template);
				$content = ob_get_contents();
				ob_get_clean();
				echo $this->cache_page($content);
				return;
			}
		}
		if(isset($_GET['ispopup']) && (strtolower($_GET['ispopup']) === "true")) {
			$template = apply_filters("template_print", "contents/themes/".$this->theme."/template-print.php", $post_meta);
			if(file_exists($template)) {
				ob_start();
				require_once($template);
				$content = ob_get_contents();
				ob_get_clean();
				echo $this->cache_page($content);
				return;
			}	
		}
		if(isset($_GET['iframe']) && (strtolower($_GET['iframe']) === "true")) {
			$template = apply_filters("template_iframe", "contents/themes/".$this->theme."/template-iframe.php", $post_meta);
			if(file_exists($template)) {
				ob_start();
				require_once($template);
				$content = ob_get_contents();
				ob_get_clean();
				echo $this->cache_page($content);
				return;
			}	
		}
		if(isset($post_meta['template'])) {
			$template = apply_filters("template_".$post_meta['template'], "contents/themes/".$this->theme."/template-".$post_meta['template'].".php", $post_meta);
			if(file_exists($template)) {
				ob_start();
				require_once($template);
				$content = ob_get_contents();
				ob_get_clean();
				echo $this->cache_page($content);
				return;
			}
		}
		ob_start();
		require_once($default);
		$content = ob_get_contents();
		ob_get_clean();
		echo $this->cache_page($content);
	}

	public function set_themes() {
		$results = scandir($this->themespath);

		if(count($results)) {
			foreach ($results as $result) {
			    if ($result === '.' or $result === '..') continue;

			    if (is_dir($this->themespath . $result)) {
			        $this->themes[] = $result;
			    }
			}
		}
	}

	public function set_templates() {
		$templates = glob($this->theme_root."/template-*.php");
		if(count($templates)) {
			foreach ($templates as $template) {
				$template = str_replace($this->theme_root."/template-", "", $template);
				$template = str_replace(".php", "", $template);
				$this->templates[] = $template;
			}
		}
		$this->templates = apply_filters("more_templates", $this->templates);
	}

	public function install($theme) {
		$theme = $theme ? $theme : $this->theme;
		require_once($this->themespath.$theme."/functions.php");
		if(function_exists("__".$theme."_install")) {
			$install = "__".$theme."_install";
			$install();
		}
	}

	public function get_content($post_meta) {
		ob_start();
		if(isset($_GET['content'])) {
			render_page_content($_GET['content']);
			$template = apply_filters("page_filter_".$post_meta['permalink'], ob_get_contents(), $post_meta);
			ob_get_clean();
			echo $template;
			return;
		}

		//default registration and login callbacks
		switch ($post_meta['permalink']) {
			case 'login':
				$post_meta['callback'] = !function_exists($post_meta['callback']) ? 'login_cb' : $post_meta['callback'];
				break;

			case 'registration':
				$post_meta['callback'] = !function_exists($post_meta['callback']) ? 'registration_cb' : $post_meta['callback'];
				break;
			
			default:
				# code...
				break;
		}

		if(isset($post_meta['availability'])) {
			if($post_meta['availability'] == 'public') {
				if (function_exists($post_meta['callback'])) {
					do_action("before_render_public_page");
                	do_action("before_render_page_".$post_meta['permalink']);
		            $post_meta['callback']();
		            do_action("after_render_public_page");
                	do_action("after_render_page_".$post_meta['permalink']);
                	$template = apply_filters("page_filter_".$post_meta['permalink'], ob_get_contents(), $post_meta);
					ob_get_clean();
					echo $template;
		            return;
		        } else echo "You have not created the function ".$post_meta['callback']." to display this page";
			}
		}
		
		if(current_user_can($post_meta['access'])) :
	        if (function_exists($post_meta['callback'])) {
	        	do_action("before_render_page");
                do_action("before_render_page_".$post_meta['permalink']);
	            $post_meta['callback']();
	            do_action("after_render_page");
                do_action("after_render_page_".$post_meta['permalink']);
                $template = apply_filters("page_filter_".$post_meta['permalink'], ob_get_contents(), $post_meta);
				ob_get_clean();
				echo $template;
	            return;
	        } else echo "You have not created the function ".$post_meta['callback']." to display this page";
        else:
            echo 'You are not allowed to view this page';
        endif;
	}

	function cache_page($content) {
		$session_string = $this->build_cookie_string();
		$session = Session::getInstance();
		$session->{$session_string} = $content;
		$session->{$session_string.'-expiry'} = time() + 300;
		return $content;
	}

	function has_cache() {
		return false;
		$session_string = $this->build_cookie_string();
		if($this->cache_expired($session_string)) {
			return false;
		}
		if(isset($_SESSION[$session_string])) {
			if(isset($_GET['clear_cache'])) {
				$session = Session::getInstance();
				$session->{$session_string.'-expiry'} = time() - 1;
				return false;
			}
			return $_SESSION[$session_string];
		} else return false;
	}

	function cache_expired($session_string) {
		if(isset($_SESSION[$session_string.'-expiry'])) {
			if(time() < $_SESSION[$session_string.'-expiry']) {
				return false;
			}
		}
		return true;
	}

	function build_cookie_string() {
		$get = $_GET;
		$post = $_POST;
		if(isset($get['clear_cache'])) unset($get['clear_cache']);
		if(isset($post['clear_cache'])) unset($post['clear_cache']);
		$query = !empty($get) ? "&Get?".http_build_query($get) : "";
		$query .= !empty($post) ? "&Post?".http_build_query($post) : "";
		$permalink = $this->app->post_meta['permalink'];
		$role = $this->app->user_meta ? $this->app->user_meta['role'] : "unroled";
		return "cache-".$role."-".$permalink.$query;
	}
}