<?php
//Set up the system
require('config.include.php');
//Auth stuff
require('auth.include.php');
//Save data if given
$saved=false;
//The path to the theme html
$themefile='../'.THEMEFOLDER.'/'.THEME.'/'.THEME.'.html';
if(isset($_REQUEST['templateCode'])&&$_REQUEST['action']!='Just Rebuild') {
	$tmpFile=@fopen($themefile,'w+');
	if($tmpFile===false)
		die('Could not open "'.$themefile.'" for writing, please check the file permissions.');
	fwrite($tmpFile,fetch::unescapePostVar($_POST['templateCode']));
	fclose($tmpFile);
	$saved=true;
}
$rebuilt=false;
//Rebuild if requested
if($_REQUEST['action']=='Save and Rebuild'||$_REQUEST['action']=='Just Rebuild') {
	//Set paths
	$blockCodePath='../'.THEMEFOLDER.'/'.THEME.'/'.THEME.'.bcd';
	$themehtml='../'.THEMEFOLDER.'/'.THEME.'/'.THEME.'.html';
	//Start timer
	$buildTmr=new timer();
	//New template
	$bcGen=new ubertemplate;
	//Add html
	$bcGen->addCode(file_get_contents($themehtml));
	//Get the blockcode
	$blockCode=$bcGen->getBlockCode();
	//Write to file
	$blockCodeFile=@fopen($blockCodePath,'w+');
	if($blockCodeFile===false)
		die('Could not open "'.$blockCodePath.'" for writing, please check the file permissions.');
	else {
		fwrite($blockCodeFile,$blockCode);
		fclose($blockCodeFile);
	}
	//Get time
	$buildtime=$buildTmr->getElapsed();
	$rebuilt=true;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Template</title>
<link rel="stylesheet" href="admin.css" />
</head>

<body>
<div id="wrapper">
	<div id="header">
    	<?php echo('<a href="../" class="breadcrumb">'.SITE_TITLE.'</a> &raquo; <a href="dashboard.php" class="breadcrumb">Dashboard</a> &raquo; <a href="edithtml.php" class="breadcrumb">Edit Template</a>'); ?>
    </div>
    <div id="sidebar">
<?php
	require('nav.include.php');
?>
    </div>
    <div id="content">
        <div class="contentblock">
		<h2>Update Template HTML</h2>
		<form action="edithtml.php" method="post">
			<textarea name="templateCode" class="full" cols="60" rows="30"><?php echo(htmlentities(file_get_contents($themefile),ENT_QUOTES,"UTF-8")); ?></textarea>
			<br />
			<input type="submit" name="action" value="Save" />
			<input type="submit" name="action" value="Save and Rebuild" />
			<input type="submit" name="action" value="Just Rebuild" />
		</form>
		<?php
		if($saved) {
			echo('Template saved.<br />');
			if($rebuilt)
				echo('Template rebuilt.');
			else
				echo('HTML changes will not appear until the template has been rebuilt.');
		}
		?>
		</div>
    </div>
    <div id="footer">
    </div>
</div>
</body>
</html>