<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Revised: 6/15/2007
// Added head_name and WHERE clause for saving different head content.
// Revised: 3/26/2010	ELL
// Redirected save to edit_head.php instead of returning to the main menu.
// Fixed bug with ecape codes.
// Revised: 10/12/2010	ELL
// Changed timestamping of `revised` field due to change from VARCHAR to DATETIME in table structure.
// Revised: 1/16/2012	ELL
// Added "Publish" button and changed "Save" button function to save to draft. Also added "Revert" so that draft can be discarded.
// Revised: 2/10/2012	ELL
// Added table prefix handling.
// Revised: 7/29/2014	ELL
// Converted save functions to JQuery AJAX operations.
// Revised: 11/6/2014	ELL
// Added save to backup everytime save or publish is clicked.
	
	include ("check_session.php");

	$head_name = $_POST['head_name'];
	$head_content = $_POST['head_content'];
	$head_content = addslashes($head_content);
	$action = $_REQUEST['action'];
	
	if (!isset($action))	// Something went foobar.  Don't do anything and bale out.
	{
		echo "Error: Action not defined.";
		exit;
	}
	
	// Whether saving draft of publishing, save latest revision to draft table.
	$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data_draft WHERE page_name='$head_name' AND `source`=2";
	$result = $bwb_dbh->query($query);
	if ($result->rowCount() > 0)	
		$query = "UPDATE " . BWB_TABLE_PREFIX . "page_data_draft SET page_content=:head_content, `source`=2 WHERE page_name='$head_name'";
	else
		$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_draft SET page_name='$head_name', page_content=:head_content, `source`=2";
	$stmt = $bwb_dbh->prepare($query);
	$stmt->execute(array(':head_content' => $head_content));
	
	if ($action == "Publish")	// Publish latest changes.
	{
		$query = "SELECT head_name FROM " . BWB_TABLE_PREFIX . "head WHERE head_name='$head_name'";
		$result = $bwb_dbh->query($query);
		if ($result->rowCount() > 0)
			$query = "UPDATE " . BWB_TABLE_PREFIX . "head SET head_content=:head_content WHERE head_name='$head_name'";
		else
			$query = "INSERT INTO " . BWB_TABLE_PREFIX . "head SET head_name='$head_name', head_content=:head_content";
		$stmt = $bwb_dbh->prepare($query);
		$stmt->execute(array(':head_content' => $head_content));
	}
	
	$query = "INSERT INTO " . BWB_TABLE_PREFIX . "page_data_bkup SET page_name='$head_name', page_content=:head_content, source=2";
	$stmt = $bwb_dbh->prepare($query);
	$stmt->execute(array(':head_content' => $head_content));
	
	if ($action == "Publish")
		echo "Head content has been published.";
	else
		echo "Head content has been saved.";
	
?>
