<?php

cx_require('third_party', 'mime', 'mime_types.php');

function cx_template_content_path($class, $path) {
	$segments = array(CX_PATH, 'templates', $class, 'assets', $path);
	$path = join(DIRECTORY_SEPARATOR, $segments);
	return $path;
}

function cx_template_has_content($class, $path) {
	return file_exists(cx_template_content_path($class, $path));
}

function cx_template_output_content($class, $path, $cache_age = 30 * 86400) {
	$full_path = cx_template_content_path($class, $path);

	$extension = pathinfo($path, PATHINFO_EXTENSION);

	if (isset(MIME_REVERSE_MAP[$extension])) {
		$mime_type = MIME_REVERSE_MAP[$extension][0];
	} else {
		$finfo = finfo_open(FILEINFO_MIME_TYPE);
		$mime_type = finfo_file($finfo, $full_path);
		//finfo_close($finfo); - Deprecated
	}

	$file_size = filesize($full_path);
	$file_modified_time = filemtime($full_path);

	header('Content-Type: ' . $mime_type);
	header('Content-Length: ' . $file_size);
	header('Cache-Control: public, max-age=604800');
	header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache_age) . ' GMT');
	header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $file_modified_time) . ' GMT');

	if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
		$request_modification = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
		if ($request_modification >= $file_modified_time) {
			http_response_code(304);
			return;
		}
	}

	$fp = fopen($full_path, 'rb');
	fpassthru($fp);
	fclose($fp);
}

function cx_template_render($class, $name, $variables = null) {
	global $cx_template_base, $cx_template_content;
	
	$base_template = null;

	$output = '';
	while ($name != null) {
		$segments = array(CX_PATH, 'templates', $class, 'pages', $name . '.php');
		$path = join(DIRECTORY_SEPARATOR, $segments);
		
		$base_template = null;
		$base_template_variables = null;

		$cx_template_base_previous = $cx_template_base;
		$cx_template_base = function($name, $base_variables) use (&$base_template, &$base_template_variables) {
			$base_template = $name;
			$base_template_variables = $base_variables;
		};

		$cx_template_content_previous = $cx_template_content;
		$cx_template_content = function() use ($output) {
			return $output;
		};

		cx_require('lib', 'url.php'); // For templates

		if ($variables != null) {
			extract($variables);
		}

		ob_start();
		include($path);
		$output = ob_get_contents();
		ob_end_clean();

		$cx_template_base = $cx_template_base_previous;
		$cx_template_content = $cx_template_content_previous;

		$name = $base_template;
		$variables = $base_template_variables;
	}

	return $output;
}

function cx_template_base($name, $variables = null) {
	global $cx_template_base;
	$cx_template_base($name, $variables);
}

function cx_template_content() {
	global $cx_template_content;
	return $cx_template_content();
}
