<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 7/19/2012	ELL
// Complete retrofit from older design.
// Revised: 1/11/2016	ELL
// Updated for new dynamics page-template files used in version 6.1 and later.
// Revised: 1/19/2016	ELL
// Added preview of style sheets. (special = 3)
// Added preview of menu styles. (special = 4)
// Revised: 4/25/2019	ELL
// Added device emulation.
// 

	include ("check_session.php");
		
	$page_name = $_REQUEST['page_name'];
	$special = $_REQUEST['special'];	//Flag to tell if editing special page (header, footer, side panel...).
	$mode = $_REQUEST['mode'];
	$blog_id = $_REQUEST['blog_id'];
	$style_sheet = $_REQUEST['style_sheet'];
	$device_emulation = $_SESSION['device_emulation'];
		
	$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_cache WHERE id = 1";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);
	$sValue = $row["tmp_page_data"];
	
	if (($mode == "blog") || ($special == 3) || ($special == 4))
	{
		$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name = '" . $page_name . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		if ($mode == "blog")
			$sValue .= stripslashes($row["page_content"]);
		else
			$sValue = stripslashes($row["page_content"]);
	}
	
	if (BWB_BASE_DIR == '')
		$userfiles_path = '';
	else
		$userfiles_path = "/" . BWB_BASE_DIR;
		
	if (BWB_WEBPAGE_DIR == '')
		$website_path = $userfiles_path;
	else
		$website_path = $userfiles_path . "/" . BWB_WEBPAGE_DIR;
		
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Preview Page | Breeze Website Builder</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">

<style type="text/css">
	html {
	   padding-top: 0px;
	   padding-right: 0px;
	   padding-bottom: 0px;
	   padding-left: 0px;
	   border: 0;
	   margin-top: 0px;
	   margin-right: 0px;
	   margin-left: 0px;
	   margin-bottom: 0px;
	}
	body {
	   margin-top: 0px;
	   margin-right: 0px;
	   margin-left: 0px;
	   margin-bottom: 0px;
	   height: 100%;
	}
	
	#preview_toolbar	{
		width:100%;
		height:33px;
		background-color:#CCC;
	}
	#preview_title	{
		font-family:Arial, Helvetica, sans-serif;
		font-weight:bold;
		font-size:16px;
		margin-left:50px;
		padding-top:5px;
	}
	#preview_refresh_button	{
		display:block;
		position:absolute;
		left:50%;
		top:1px;
		cursor:pointer;
	}
	#preview_device_emulation	{
		display:block;
		position:absolute;
		left:70%;
		top:5px;
		cursor:pointer;
	}
	#preview_close_button	{
		display:block;
		position:absolute;
		right:50px;
		top:1px;
		cursor:pointer;
	}
</style>

<script>
function ResizeWorkspace()
{
	var mainWidth = 0, mainHeight = 0, scrollWidth = 20, headerHeight = 33;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		mainWidth = window.innerWidth;
		mainHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		mainWidth = document.documentElement.clientWidth;
		mainHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		mainWidth = document.body.clientWidth;
		mainHeight = document.body.clientHeight;
	}
	
	var workspaceWidth = mainWidth - scrollWidth;
	var workspaceHeight = mainHeight - headerHeight;
	sWorkspaceWidth = workspaceWidth.toString() + "px";
	sWorkspaceHeight = workspaceHeight.toString() + "px";
	document.getElementById("preview_frame").style.width = sWorkspaceWidth;
	document.getElementById("preview_frame").style.height = sWorkspaceHeight;
}

window.addEventListener('resize', function(event) {
	mTimer = setTimeout("ResizeWorkspace();", 500);
});

function CallPreview()
{
	document.getElementById("preview_refresh_img").src = "theme/<?php echo $theme; ?>/images/refresh.gif";
	window.opener.Preview('<?php echo $page_name; ?>', 1);
}

function ChangeDeviceEmulation(device_emulation)
{
	$.post( "set_device_emulation.php", { device_emulation: device_emulation  } ).done(function( data ) { CompleteChangeDeviceEmulation(data); } ) ;
}
function CompleteChangeDeviceEmulation(data)
{
	CallPreview();
}

function ClosePreview()
{
	$.post( "set_device_emulation.php", { device_emulation: "unset_device_emulation" } ).done(function( data ) { CompleteClosePreview(data); } ) ;
}
function CompleteClosePreview(data)
{
	window.close();
}
</script>
<script src="js/jquery.min.js"> </script>
</head>

<body onLoad="ResizeWorkspace();">
	<div id="preview_toolbar">
	<div id="preview_title"><?php	echo EDITOR_PAGE_NAME . ": $page_name";	?></div>
	<div id="preview_refresh_button"><img src="theme/<?php echo $theme; ?>/images/icon_Reset.png" alt="<?php echo REFRESH_WORD;  ?>" id="preview_refresh_img" onClick="CallPreview();" /></div>
    <div id="preview_device_emulation">
    	<select name="device_emulation" id="device_emulation" onChange="ChangeDeviceEmulation(this.value);">
        	<option value="desktop"<?php if ($device_emulation == "desktop") echo "selected='selected'"; ?>)><?php echo DESKTOP_WORD;  ?></option>
            <option value="mobile"<?php if ($device_emulation == "mobile") echo "selected='selected'"; ?>><?php echo MOBILE_WORD;  ?></option>
            <option value="touchscreen"<?php if ($device_emulation == "touchscreen") echo "selected='selected'"; ?>><?php echo TOUCHSCREEN_WORD;  ?></option>
        </select>
    </div>
    <div id="preview_close_button"><img src="theme/<?php echo $theme; ?>/images/close-button.png" alt="<?php echo CLOSE_WORD; ?>" onClick="ClosePreview();" /></div>
</div>
<?php
	// If head content, then get index page.
	if ($special == 2)
	{
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data WHERE head_name = '$page_name'";
		$result = $bwb_dbh->query($query);
		$page_found = false;
		while($row = $result->fetch(PDO::FETCH_ASSOC))
		{
			$host_page_name = $row["page_name"];	
			/////////////////////////////////////////
			//Test to see if file already exists.
			$document_root = $_SERVER['DOCUMENT_ROOT'];
			$file_name = $document_root . $website_path . "/" . $host_page_name . ".php";
			if (!file_exists($file_name))
				continue;	// Somehow file not found.  Just go find another one.
				
			// Read file.
			$fh = fopen($file_name, 'r') or die("Can't read $file_name: $php_errormsg");
			$page_content = fread($fh, filesize($file_name));
			fclose($fh) or die($php_errormsg);
		
			$page_found = true;
			break;	// Found this border area in this file.  Use this file.
		}
		if (!$page_found)
			echo "Oops!  This head is not used is any pages.";
	}
	// If border area, find a host page to use for display.
	elseif ($special == 1)
	{
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data WHERE (header_name = '$page_name') OR (top_name = '$page_name') OR (left_name = '$page_name') OR (right_name = '$page_name') OR (bottom_name = '$page_name') OR (footer_name = '$page_name')";
		$result = $bwb_dbh->query($query);
		$page_found = false;
		while($row = $result->fetch(PDO::FETCH_ASSOC))
		{
			$host_page_name = $row["page_name"];	
			/////////////////////////////////////////
			//Test to see if file already exists.
			$document_root = $_SERVER['DOCUMENT_ROOT'];
			$file_name = $document_root . $website_path . "/" . $host_page_name . ".php";
			if (!file_exists($file_name))
				continue;	// Somehow file not found.  Just go find another one.
				
			// Read file.
			$fh = fopen($file_name, 'r') or die("Can't read $file_name: $php_errormsg");
			$page_content = fread($fh, filesize($file_name));
			fclose($fh) or die($php_errormsg);
		
			$page_found = true;
			break;	// Found this border area in this file.  Use this file.
		}
		if (!$page_found)
			echo "Oops!  This border area is not used is any pages.  We need to display content of just this border area.";
	}
	// If normal page content, then go get that page.
	elseif (($special != 1) && ($special != 2))	// Page content
	{
		//Test to see if file already exists.
		$document_root = $_SERVER['DOCUMENT_ROOT'];
		$file_name = $document_root . $website_path . "/" . $page_name . ".php";
		if (!file_exists($file_name))
		{
			echo "Error: $file_name does not exist.  Click <a href=\"manage_border_area.php\" title=\"here\">here</a> to return to the area assignment page.";
			exit;
		}
		
		// Read file.
		$fh = fopen($file_name, 'r') or die("Can't read $file_name: $php_errormsg");
		$page_content = fread($fh, filesize($file_name));
		fclose($fh) or die($php_errormsg);
		if (($special == 3) || ($special == 4))	{		
			$search = "\$name = \$row[\"name\"];";
			$page_content_arr = explode($search, $page_content);
				$preview_style_sheet = "site_preview";
			$insert = "\nif (\$name == '" . $style_sheet . "')\n \$name = '" . $preview_style_sheet . "';\n";
			$page_content = $page_content_arr[0] . "\n" . $search . $insert . $page_content_arr[1] . "\n" . $search . $insert . $page_content_arr[2];
			
			$search = "include(\$is_mobile_path);";
			if (strpos($style_sheet, "_mobile") === false)
				$replace = "\$is_mobile = false;";
			else
				$replace = "\$is_mobile = true;";
			$page_content = str_replace($search, $replace, $page_content);
		}
	}
	
	// If special, than swap sValue to correct location.
	if (($special == 1) || ($special == 2))
	{
		if (strpos($page_name, "head") !== false)
			$tmp = "head";
		elseif (strpos($page_name, "header") !== false)
			$tmp = "header";
		elseif (strpos($page_name, "top") !== false)
			$tmp = "top";
		elseif (strpos($page_name, "bottom") !== false)
			$tmp = "bottom";
		elseif (strpos($page_name, "left") !== false)
			$tmp = "left";
		elseif (strpos($page_name, "right") !== false)
			$tmp = "right";
		elseif (strpos($page_name, "footer") !== false)
			$tmp = "footer";
			
		$search = "echo \$$tmp;";
		$sValue = addslashes($sValue);
		$replace = "echo \"$sValue\";";
		$page_content = str_replace($search, $replace, $page_content);
		$sValue = "<br><br><b>Host Test Page for $page_name.</b><br><br>";
	}
		
	$contents_arr = explode("<!-- Page Content Divider -->", $sValue, 2);
	$page_content = str_replace("<?php echo \$page_content_arr[0]; ?>", $contents_arr[0], $page_content);
	$page_content = str_replace("<?php if (isset($page_content_arr[1])) echo $page_content_arr[1]; ?>", $contents_arr[1], $page_content);
	
	
	$preview_file = "pREVIEW.php";
	$preview_path = $document_root . $website_path . "/" . $preview_file;
	$fh = fopen($preview_path, 'w') or die("can't open file");
	fwrite($fh, $page_content);
	fclose($fh);

?>

	<iframe width="978" scrolling="auto" src="<?php echo $website_path . "/" . $preview_file; ?>" id="preview_frame" ></iframe>

</body>
</html>