<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 7/21/2009	ELL
// Added ability to operate using different class tables.  This was done to give the ability
// to style calendar grids and event grids without adding 14 more classes to the site style list.
// Renamed from set_tag_sort_order.php to set_class_sort_order.php.
// Added feed thru to show/hide custom styles.
// Revised: 2/10/2012	ELL
// Added table prefix handling.
// Revised: 3/11/2016	ELL
// Added regeneration of CSS file such that sort order takes effect immediately.
// Modified: 12/2/2016	ELL
// Consolidated all class tables into site_classes table indexed by style_sheet field.
// Consolidated all CSS tables into site_css table indexed by style_sheet field.
// 
// 
// 
// 
	include ("check_session.php");
		
	$style_sheet = $_REQUEST['style_sheet'];
	
	$i = 0;
	$query_tags = "SELECT * FROM `" . BWB_TABLE_PREFIX . "site_classes` WHERE `style_sheet` = '$style_sheet' ORDER BY `sort_order`";
	$result_tags = $bwb_dbh->query($query_tags);
	while ($row_tags = $result_tags->fetch(PDO::FETCH_ASSOC))
	{
		$class_id_string = "class_" . $i;
		$sort_order_id_string = "sort_order_" . $i;
		
		$class = $_POST[$class_id_string];
		if ($_POST[$sort_order_id_string])
			$sort_order = $_POST[$sort_order_id_string];
		else
			$sort_order = 0;
			
		//Insert new data into table.
		$query = "UPDATE `" . BWB_TABLE_PREFIX . "site_classes` SET `sort_order` = " . $sort_order . " WHERE `style_sheet` = '$style_sheet' AND `class` = '" . $class . "'";
		$cnt = $bwb_dbh->exec($query);
				
		$i++;
	} // end while
	
	////////////////////////////////////////////////////
	// Build string for css file and re-write file /////
	include("lib/build_css_string.php");

	$css_file = $style_sheet . ".css";
	$css_string = BuildCSSString($style_sheet, $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);

	$document_root = $_SERVER['DOCUMENT_ROOT'];
	if (BWB_BASE_DIR == '')
		$userfiles = '';
	else
		$userfiles = "/" . BWB_BASE_DIR;

	$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
		
	if (file_exists($file_name))
	{
		$bkup_file_name = $file_name . time();
		if (!rename($file_name, $bkup_file_name))
			echo EDIT_CSS_COULD_NOT_RENAME_1_ERR . " $file_name " . EDIT_CSS_COULD_NOT_RENAME_2_ERR . " $bkup_file_name.<br>";
		@chmod($bkup_file_name, 0644);
	}

	// Create file.
	$fh = fopen($file_name, 'x') or die(EDIT_CSS_CANT_CREATE_ERR . " $file_name: $php_errormsg");
	$result = (fputs($fh, $css_string));
	fclose($fh) or die($php_errormsg);
	@chmod($file_name, 0644);
	
	echo 1;
?>