<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Controller extends MY_Controller
{
	public function index()
	{
		$site = Mainframe::site();
		$page_name_temp = implode("/", func_get_args());

		if($page_name_temp)
		{
			$page_id   = $page_name_temp;
			$page_name = $page_name_temp;
		}
		else
		{
			// Top level domain
			$page_id   = $site->default_page_id;
			$page_name = "index";
		}

		// Not installed yet - likely showing the landing page.
		if(!isset($site->site_id) || $site->site_id <= 0)
		{
			if(defined("LOGGING")) { error_log(PRODUCT_NAME . ": Could not determine which site to load."); }
			return;
		}

		$page = Mainframe::LoadPage($site->site_id, $page_id);

		if(!isset($page->page_id) || !$page->page_id)
		{
			// The full URL didn't match. We're going to chop off segments one at a time,
			// checking if that part of the URL matches a page. If it does and the page
			// allows for additional URL segments to be passed in, we'll load the page.
			// Otherwise, 404.
			$url = str_replace(site_url(), "", current_url());

			while(strpos($url, "/") !== false)
			{
				$url  = substr($url, 0, strrpos($url, "/"));
				$page = Mainframe::LoadPage($site->site_id, $url);

				// If a page loaded, check if we're allowed to have additional URL segments.
				if(isset($page->page_id) && $page->page_id > 0)
				{
					if($page->allow_url_segments)
					{
						break;
					}
					else
					{
						if(defined("LOGGING")) { error_log(PRODUCT_NAME . ": 404: Could not determine which page to load. Additional URL segments were not checked."); }
						$this->http404();
						exit();
					}
				}
			}

			// If we still don't have a page loaded after checking URL segments, 404.
			if(!isset($page->page_id) || !$page->page_id)
			{
				if(defined("LOGGING")) { error_log(PRODUCT_NAME . ": 404: Could not determine which page to load. Additional URL segments were also checked."); }
				$this->http404();
				exit();
			}
		}

		// If the page is not published, 404.
		if(!$page->published)
		{
			if(defined("LOGGING")) { error_log(PRODUCT_NAME . ": 404: `" . $page->url . "` is not published."); }
			$this->http404();
			exit();
		}

		// If the page does not allow query strings but there is a query string passed, 301 back to the main page.
		// UNLESS gclid is set, which is required by Google AdWords.
		if(!$page->allow_url_query && count($this->input->get()) > 0 && !$this->input->get("gclid"))
		{
			if(defined("LOGGING")) { error_log(PRODUCT_NAME . ": 301: Query strings are diabled on `" . $page->url . "`."); }
			redirect($page->url, "auto", 301);
		}

		$this->end();
	}
}
