<?php
/*
 * This file is part of Web Pro Manager.
 * 
 * Web Pro Manager is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Web Pro Manager is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Web Pro Manager.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL
 * @package WebProManager
*/

require("../inc/stop_cache.php");
$nAdminOnlyPg = 0;
// Secure and connect
require("../../inc/dbconnect.php");
require("../inc/secure_page.php");

// bring in other required files
require("../../inc/config.php");
require("../inc/lang.php");
require("../inc/langutil.php");

// config
$nRefreshCall = "refreshSections();";

// pull in all active languages (used to create multiple fields, when needed)
$nActiveLangARRAY = nGetLangActiveARRAY();

// Get passed-in vars
$nRecID = (isset($_GET['id']) ? $_GET['id'] : NULL);
if(!$nRecID){ $nRecID = (isset($_POST['id']) ? $_POST['id'] : NULL); }

// AJAX Specific vars
$nPassThru = "";
$nDivToUpdate = "editModal";
$nPageInDiv = "dialog/section_add.php";

// Get info
if($nRecID){
	$nSQL = "SELECT * FROM nSection WHERE nID='$nRecID' LIMIT 1";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nName = $Row["nName"];
		$nParentID = $Row["nParentID"];
		$nLocked = $Row["nLocked"];
	} else { echo "<div align=\"center\" style=\"padding:20px;\"><em>"._("No record found.")."</em></div>"; }
}
$nLocked = "";
if($nLocked){ exit(_("This record is locked and cannot be edited.")); }
?>

<div id="<?php echo $nDivToUpdate;?>">
<?php
include("../inc/form_class.php");

$nFormName = "FormSectionAdd";
$nForm1 = new Form();
//$nForm1->DEBUG = true;
$nForm1->Name = $nFormName;
$nForm1->Action = $_SERVER['PHP_SELF'];
$nForm1->CancelText = _("Cancel");
$nForm1->CancelRedirect = "$.colorbox.close()";
$nForm1->CancelRedirectIsJS = true;
if($nRecID){
	$nForm1->SubmitText = _("Update");
} else {
	$nForm1->SubmitText = _("Add Section");
}
$nForm1->DBLink = $Link;
$nForm1->nUseADODB = false;
// AJAX settings
$nForm1->SubmitIsJS = true;
$nForm1->SubmitToJS = "return submitForm('$nDivToUpdate','$nPageInDiv$nPassThru','$nFormName');return false;";
$nForm1->DontProcess = "id";

// Create groups
$nFormGroup1 = new FormGroup();

// Create fields
if($nRecID){
	$nFormField = new FormField("hidden","id");
	$nFormField->Value = $nRecID;
	$nFormGroup1->AddField($nFormField);
}
$nForm1->AddGroup($nFormGroup1);

foreach($nActiveLangARRAY as $nLangCode => $nLangName) {
	$nFormGroup1 = new FormGroup();
	
	if($nLangCode==$nDefaultLang){ $nLangSuffix = ""; } else { $nLangSuffix = "_$nLangCode"; $nFormGroup1->Style = "display:none;"; }
	$nFormGroup1->ID = "tabbody_$nLangCode";
	
	$nFormField = new FormField("text","nName$nLangSuffix",_("Section Name")." ($nLangName):");
	$nFormField->Caption = _("(max. 50 characters)");
	if($nLangCode==$nDefaultLang){ $nFormField->Value = $nName; } else { $nFormField->Value = nGetLangContent($nLangCode,$nRecID,"section","nText"); }
	$nFormField = $nForm1->AddValidation("maxlength",$nFormField,50);
	$nFormField->RowSize = "Half";
	$nFormGroup1->AddField($nFormField);
	
	if($nLangCode==$nDefaultLang){
		$nFormField = new FormField("select","nParentID$nLangSuffix",_("This is a sub-section of")." ($nLangName):");
		$nFormField->DataARRAY = nGetSectionARRAY();
		if($nLangCode==$nDefaultLang){ $nRecIDSelected = $nParentID; } else { $nRecIDSelected = nGetLangContent($nLangCode,$nRecID,"section","nImgID"); }
		if($nRecIDSelected){
			$nFormField->SelectedARRAY = array("$nRecIDSelected" => "selected");
		} else {
			$nFormField->SelectedARRAY = array("0" => "selected"); // default
		}
		$nFormField->RowSize = "Half";
		$nFormField->Style = "width:200px;";
		$nFormGroup1->AddField($nFormField);
	}
	
	$nForm1->AddGroup($nFormGroup1);
}
if(count($nActiveLangARRAY)>1){ $nForm1->AddGroup(nGetLangTabGroup()); }

// Finalize and display form
$nFormToDisplay = $nForm1->GetForm();

// AJAX redirect if form submitted w/o error, otherwise display form (again, if necessary)
if($nForm1->HasProcessed){
	// Post-processing
	$nRecID = $_POST["id"];
	$nName = nConvertIntChars($_POST["nName"]);
	$nParentID = $_POST["nParentID"];
	if($nRecID){
		// editing existing section
		$Query = "UPDATE nSection SET nName='$nName',nParentID='$nParentID' WHERE nID=$nRecID LIMIT 1";
		mysql_select_db($DBName);
		mysql_query($Query, $Link);
	} else {
		// creating new section
		$Query = "INSERT INTO nSection (nName,nParentID) VALUES ('$nName','$nParentID')";
		mysql_select_db($DBName);
		mysql_query($Query, $Link);
		$nRecID = mysql_insert_id(); // gets ID of last created row
	}
	// Update all additional language fields (default language already saved)
	if($nRecID && count($nActiveLangARRAY)){
		foreach($nActiveLangARRAY as $nLangCode => $nLangName) {
			$nType = "section";
			// Name
			$nFieldName="nName_".$nLangCode;
			if($nLangCode==$nDefaultLang){ $nName = nConvertIntChars($_POST["nName"]); } else { $nName = trim($_POST[$nFieldName]); $nName = nConvertIntChars($nName); }
			// Other Fields
			$nFieldName="nParentID_".$nLangCode;
			if($nLangCode==$nDefaultLang){ $nParentID = nConvertIntChars($_POST["nParentID"]); } else { $nParentID = trim($_POST[$nFieldName]); }
			if($nRecID){
				// first remove any current content for this language
				$Query = "DELETE FROM nTranslate WHERE nLang='$nLangCode' AND nItemID='$nRecID' AND nType='$nType'";
				mysql_select_db($DBName);
				mysql_query($Query, $Link);
				//print "$Query<BR><BR>";
			}
			// now save new content (if at least one field has content)
			if($nRecID){
				$Query = "INSERT INTO nTranslate VALUES ('','$nLangCode','$nRecID','$nType','$nName','','','$nParentID','1')";
				mysql_select_db($DBName);
				mysql_query($Query, $Link);
				//print "$Query<BR><BR>";
			}
		}
	}
	echo "<script>$nRefreshCall $.colorbox.close();</script>";
} else {
	echo $nFormToDisplay;
	echo "<script>$.colorbox.resize();</script>";
}
?>
</div>
<?php
function nGetNextSectionNum(){
	global $DBName,$Link;
	$nSQL = "SELECT Max(nID) AS nID FROM nSection";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	if($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"] + 1;
	}
	return $nID;
}
function nGetSectionARRAY(){
	global $DBName,$Link;
	global $nRecID;
	$nWhereSQL = "";
	$nDataARRAY = array();
	$nDataARRAY[0] = _("None (This is a main section)");
	// don't allow this to be a parented by itself OR any of its own children
	if($nRecID){ $nWhereSQL = "WHERE nParentID!=$nRecID AND nID!=$nRecID"; }
	$nSQL = "SELECT * FROM nSection $nWhereSQL ORDER BY nParentID,nName ASC";
	mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
	while($Row = mysql_fetch_array($Result)){
		$nID = $Row["nID"];
		$nName = $Row["nName"];
		$nParentID = $Row["nParentID"];
		if($nID!=$nRecID){
			if($nParentID){ $nDataARRAY["$nID"] = "- $nName"; } else { $nDataARRAY["$nID"] = "$nName"; }
		}
	}
	return $nDataARRAY;
}
// returns array of active storefront languages in alpha order, default will be first item in array 
function nGetLangActiveARRAY(){
	global $nDefaultLang;
	$nDefaultLangARRAY = array();
	$nLangARRAY = array();
	// Get all files in directory
	$path = "../../lang/";    
	$dir_handle = @opendir($path) or die("Unable to open $path");    
	while ($file = readdir($dir_handle)) {
		if($file == "." || $file == ".." || $file == "index.php" )
			continue;
		$nFileCode = str_replace(".php","",$file);
		if(!is_dir("$path$file/")){
			if(file_exists("$path$file")){ require("$path$file"); }
			if($nFileCode == $nDefaultLang){
				if($nLang){ $nDefaultLangARRAY["$nFileCode"] = $nLang; } // default language
			} else {
				if($nLang){ $nLangARRAY["$nFileCode"] = $nLang; }
			}
		}
	}
	closedir($dir_handle);
	krsort($nLangARRAY);
	foreach($nDefaultLangARRAY as $nLangCode => $nLangName) {
		$nLangARRAY["$nLangCode"] = $nLangName;
	}
	$nLangARRAY = array_reverse($nLangARRAY,true);
	return $nLangARRAY;
}
function nGetLangTabGroup(){
	global $nActiveLangARRAY,$nDefaultLang;
	$nFormGroup1 = new FormGroup();
	$nHideCodeJS = "";
	$nLangDivARRAY = array();
	$nLangTabARRAY = array();
	foreach($nActiveLangARRAY as $nLangCode => $nLangName) { $nLangDivARRAY[] = "#tabbody_$nLangCode"; $nLangTabARRAY[] = "#tab_$nLangCode"; }
	if($nLangDivARRAY){ $nLangDivList = implode(",",$nLangDivARRAY); }
	if($nLangTabARRAY){ $nLangTabList = implode(",",$nLangTabARRAY); }
	$nHideCodeJS.="$('$nLangDivList').hide(); $('$nLangTabList').removeClass('langTabActive').addClass('langTab');";
	foreach($nActiveLangARRAY as $nLangCode => $nLangName) {
		if($nLangCode==$nDefaultLang){ $nLangSuffix = ""; $nClass="langTabActive"; } else { $nLangSuffix = "_$nLangCode"; $nClass="langTab"; }
		$nLangLinks.="<a href=\"javascript:;\" onClick=\"$nHideCodeJS $('#tabbody_$nLangCode').show(); $('#tab_$nLangCode').removeClass('langTab').addClass('langTabActive');\" id=\"tab_$nLangCode\" class=\"$nClass\">$nLangName</a> ";
	}
	$nFormField = new FormField("static","",_("Language:")." $nLangLinks");
	$nFormField->RowStyle = "clear:both;float:none;font-weight:bold;";
	$nFormGroup1->AddField($nFormField);
	return $nFormGroup1;
}
function nGetLangContent($nLangCode,$nItemID,$nType,$nFieldName,$nOrderID=1){
	global $DBName, $Link;
	if(!$nLangCode || !$nItemID || !$nType || !$nFieldName){ return; };
	$Query = "SELECT $nFieldName AS nContent FROM nTranslate WHERE nLang='$nLangCode' AND nItemID='$nItemID' AND nType='$nType' AND nOrderID='$nOrderID'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nContent = $Row["nContent"];
	}
	return $nContent;
}
?>
<?php require("../../inc/db_close.php"); ?>
