<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 8/20/09		ELL
// Revised: 2/10/2012	ELL
// Added table prefix handling.  Added references to CSS folder configurations.
// 
//
//
	include ("check_session.php");

	
	$site_css_table = "site_css";
	$custom_site_css_table = "custom_site_css";
	$css_file = "site.css";
	$submit_action = $_POST['submit_action'];
	
	// Custom CSS
	$custom_css = $_POST['textarea_custom_css'];
	$custom_css = str_replace("'", "", $custom_css);
	
	if ($submit_action == "Preview")
	{
		//Start by deleting all old data in table.
		$query = "TRUNCATE TABLE " . BWB_TABLE_PREFIX . $custom_site_css_table . "_preview";
		$cnt = $bwb_dbh->exec($query);
		
		//Insert new data into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . $custom_site_css_table . "_preview (custom_css) VALUES ('" . $custom_css . "')";	
		$cnt = $bwb_dbh->exec($query);
	}
	else
	{
		//Start by deleting all old data in table.
		$query = "TRUNCATE TABLE " . BWB_TABLE_PREFIX . $custom_site_css_table;
		$cnt = $bwb_dbh->exec($query);
		
		//Insert new data into table.
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . $custom_site_css_table . " (custom_css) VALUES ('" . $custom_css . "')";	
		$cnt = $bwb_dbh->exec($query);
	}

	/////////////////////////////////////////////
	// Build string for site.css file /////
	include("build_css_string.php");
			

	////////////////////////////////////////////////////////
	/// Write menu items to menu.css file /////////////
	//Test to see if file already exists.
	$document_root = $_SERVER['DOCUMENT_ROOT'];
	if (BWB_BASE_DIR == '')
		$userfiles = '';
	else
		$userfiles = "/" . BWB_BASE_DIR;
		
	if ($submit_action == "Update")
		$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
	else
		$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/site_preview.css";
		
	if (file_exists($file_name))
	{
		$bkup_file_name = $file_name . time();
		if (!rename($file_name, $bkup_file_name))
			echo "Could not rename $file_name to $bkup_file_name.<br>";
		@chmod($bkup_file_name, 0644);
	}
	
	// Create file.
	$fh = fopen($file_name, 'x') or die("Can't create $file_name: $php_errormsg");
	$result = (fputs($fh, $css_string));
	fclose($fh) or die($php_errormsg);
	@chmod($file_name, 0644);
	
	
	//////////////////////////////////////////////////////////
	if ($submit_action == "Preview")
		header("Location: preview_css.php?style_sheet=site&custom=1");
	else
	// Go back to custom CSS editor. /////////////////////
		header("Location: edit_custom_css.php?custom_css_saved=1");
	
?>
