server()) {
	metaRefresh("../login.php");
	exit;
}
// Write $_POST variables to $_GET when form was submitted via post
if (isset($_POST['type'])) {
	$_GET = $_POST;
}
$typeManager = new \LAM\TYPES\TypeManager();
$type = $typeManager->getConfiguredType($_GET['type']);
if ($type->isHidden() || !checkIfWriteAccessIsAllowed($type->getId())) {
	logNewMessage(LOG_ERR, 'User tried to access hidden PDF structure: ' . $type->getId());
	die();
}
// Abort and go back to main pdf structure page
if(isset($_GET['abort'])) {
	metarefresh('pdfmain.php');
	exit;
}
// Load PDF structure from file if it is not defined in session
if(!isset($_SESSION['currentPDFStructure'])) {
	// Load structure file to be edit
	$reader = new PDFStructureReader();
	try {
		if(isset($_GET['edit'])) {
			$_SESSION['currentPDFStructure'] = $reader->read($type->getId(), $_GET['edit']);
		}
		// Load default structure file when creating a new one
		else {
			$_SESSION['currentPDFStructure'] = $reader->read($type->getId(), 'default');
		}
	}
	catch (\LAMException $e) {
		metaRefresh('pdfmain.php?loadFailed=1&name=' . $_GET['edit']);
		exit;
	}
}
if (!empty($_POST['form_submit'])) {
	updateBasicSettings($_SESSION['currentPDFStructure']);
	updateSectionTitles($_SESSION['currentPDFStructure']);
	addSection($_SESSION['currentPDFStructure']);
	addSectionEntry($_SESSION['currentPDFStructure']);
	removeItem($_SESSION['currentPDFStructure']);
	moveUp($_SESSION['currentPDFStructure']);
	moveDown($_SESSION['currentPDFStructure']);
}
// Check if pdfname is valid, then save current structure to file and go to
// main pdf structure page
$saveErrors = array();
if(isset($_GET['submit'])) {
	$writer = new PDFStructureWriter();
	try {
		$writer->write($type->getId(), $_POST['pdfname'], $_SESSION['currentPDFStructure']);
		unset($_SESSION['currentPDFStructure']);
		metaRefresh('pdfmain.php?savedSuccessfully=' . $_POST['pdfname']);
		exit;
	}
	catch (\LAMException $e) {
		$saveErrors[] = array('ERROR', $e->getTitle(), $e->getMessage());
	}
}
$availablePDFFields = getAvailablePDFFields($type->getId());
// Create the values for the dropdown boxes for section headline defined by
// value entries and fetch all available modules
$modules = array();
$section_items_array = array();
$section_items = '';
$sortedModules = array();
foreach($availablePDFFields as $module => $fields) {
	if ($module != 'main') {
		$title = getModuleAlias($module, $type->getScope());
	}
	else {
		$title = _('Main');
	}
	$sortedModules[$module] = $title;
}
natcasesort($sortedModules);
foreach($sortedModules as $module => $title) {
	$values = $availablePDFFields[$module];
	if (!is_array($values) || (sizeof($values) < 1)) {
		continue;
	}
	$modules[] = $module;
	$section_items .= "\n";
}
$modules = join(',',$modules);
// print header
include '../main_header.php';
// print error messages if any
if (sizeof($saveErrors) > 0) {
	for ($i = 0; $i < sizeof($saveErrors); $i++) {
		call_user_func_array('StatusMessage', $saveErrors[$i]);
	}
	echo "
\n";
}
$newFieldFieldElements = array();
foreach($sortedModules as $module => $title) {
	$fields = $availablePDFFields[$module];
	if (isset($fields) && is_array($fields) && (sizeof($fields) > 0)) {
		$moduleFields = array();
		foreach ($fields as $field => $fieldLabel) {
			$moduleFields[$fieldLabel] = $module . "_" . $field;
		}
		$newFieldFieldElements[$title] = $moduleFields;
	}
}
// structure name
$structureName = '';
if (isset($_GET['edit'])) {
	$structureName = $_GET['edit'];
}
else if (isset($_POST['pdfname'])) {
	$structureName = $_POST['pdfname'];
}
// headline
$headline = $_SESSION['currentPDFStructure']->getTitle();
// logo
$logoFiles = \LAM\PDF\getAvailableLogos();
$logos = array(_('No logo') => 'none');
foreach($logoFiles as $logoFile) {
	$logos[$logoFile['filename'] . ' (' . $logoFile['infos'][0] . ' x ' . $logoFile['infos'][1] . ")"] = $logoFile['filename'];
}
$selectedLogo = array('printLogo.jpg');
if (isset($_SESSION['currentPDFStructure'])) {
	$selectedLogo = array($_SESSION['currentPDFStructure']->getLogo());
}
?>
	
';
include '../main_footer.php';
/**
 * Translates a given field ID (e.g. inetOrgPerson_givenName) to its descriptive name.
 *
 * @param String $id field ID
 * @param String $scope account type
 * @param array $availablePDFFields available PDF fields
 */
function translateFieldIDToName($id, $scope, $availablePDFFields) {
	foreach ($availablePDFFields as $module => $fields) {
		if (!(strpos($id, $module . '_') === 0)) {
			continue;
		}
		foreach ($fields as $name => $label) {
			if ($id == $module . '_' . $name) {
				if ($module == 'main') {
					return _('Main') . ': ' . $label;
				}
				else  {
					return getModuleAlias($module, $scope) . ': ' . $label;
				}
			}
		}
	}
	return $id;
}
/**
 * Updates basic settings such as logo and head line.
 *
 * @param PDFStructure $structure
 */
function updateBasicSettings(&$structure) {
	// set headline
	if (isset($_POST['headline'])) {
		$structure->setTitle(str_replace('<', '', str_replace('>', '', $_POST['headline'])));
	}
	// set logo
	if (isset($_POST['logoFile'])) {
		$structure->setLogo($_POST['logoFile']);
	}
	// set folding marks
	if (isset($_POST['foldingmarks'])) {
		$structure->setFoldingMarks($_POST['foldingmarks']);
	}
}
/**
 * Updates section titles.
 *
 * @param PDFStructure $structure
 */
function updateSectionTitles(&$structure) {
	$sections = $structure->getSections();
	foreach ($_POST as $key => $value) {
		if (strpos($key, 'section_') === 0) {
			$pos = substr($key, strlen('section_'));
			$sections[$pos]->setTitle($value);
		}
	}
}
/**
 * Adds a new section if requested.
 *
 * @param PDFStructure $structure
 */
function addSection(&$structure) {
	$sections = $structure->getSections();
	// add a new text field
	if(isset($_POST['add_text'])) {
		// Check if text for static text field is specified
		if(empty($_POST['text_text'])) {
			StatusMessage('ERROR',_('No static text specified'),_('The static text must contain at least one character.'));
		}
		else {
			$section = new PDFTextSection(str_replace("\r", "", $_POST['text_text']));
			array_splice($sections, $_POST['add_text_position'], 0, array($section));
			$structure->setSections($sections);
		}
	}
	// add a new section with text headline
	elseif(isset($_POST['add_sectionText'])) {
		// Check if name for new section is specified when needed
		if(empty($_POST['new_section_text'])) {
			StatusMessage('ERROR',_('No section text specified'),_('The headline for a new section must contain at least one character.'));
		}
		else {
			$section = new PDFEntrySection($_POST['new_section_text']);
			array_splice($sections, $_POST['add_text_position'], 0, array($section));
			$structure->setSections($sections);
		}
	}
	// Add a new section with item as headline
	elseif(isset($_POST['add_section'])) {
		$section = new PDFEntrySection('_' . $_POST['new_section_item']);
		array_splice($sections, $_POST['add_text_position'], 0, array($section));
		$structure->setSections($sections);
	}
}
/**
 * Adds a new entry to a section if requested.
 *
 * @param PDFStructure $structure
 */
function addSectionEntry(&$structure) {
	if(isset($_POST['add_new_field'])) {
		$field = new PDFSectionEntry($_POST['new_field']);
		$sections = $structure->getSections();
		$pos = $_POST['add_field_position'];
		$entries = $sections[$pos]->getEntries();
		$entries[] = $field;
		$sections[$pos]->setEntries($entries);
		$structure->setSections($sections);
	}
}
/**
 * Removes a section or entry if requested.
 *
 * @param PDFStructure $structure
 */
function removeItem(&$structure) {
	$sections = $structure->getSections();
	foreach ($_POST as $key => $value) {
		// remove section
		if (strpos($key, 'remove_section_') === 0) {
			$pos = substr($key, strlen('remove_section_'));
			unset($sections[$pos]);
			$sections = array_values($sections);
			$structure->setSections($sections);
		}
		// remove section entry
		if (strpos($key, 'remove_entry_') === 0) {
			$parts = substr($key, strlen('remove_entry_'));
			$parts = explode('_', $parts);
			$sectionPos = $parts[0];
			$entryPos = $parts[1];
			$entries = $sections[$sectionPos]->getEntries();
			unset($entries[$entryPos]);
			$entries = array_values($entries);
			$sections[$sectionPos]->setEntries($entries);
			$structure->setSections($sections);
		}
	}
}
/**
 * Moves up a section or entry if requested.
 *
 * @param PDFStructure $structure
 */
function moveUp(&$structure) {
	$sections = $structure->getSections();
	foreach ($_POST as $key => $value) {
		// move section
		if (strpos($key, 'up_section_') === 0) {
			$pos = substr($key, strlen('up_section_'));
			$sectionTmp = $sections[$pos - 1];
			$sections[$pos - 1] = $sections[$pos];
			$sections[$pos] = $sectionTmp;
			$structure->setSections($sections);
		}
		// move section entry
		if (strpos($key, 'up_entry_') === 0) {
			$parts = substr($key, strlen('up_entry_'));
			$parts = explode('_', $parts);
			$sectionPos = $parts[0];
			$entryPos = $parts[1];
			$entries = $sections[$sectionPos]->getEntries();
			$entryTmp = $entries[$entryPos - 1];
			$entries[$entryPos - 1] = $entries[$entryPos];
			$entries[$entryPos] = $entryTmp;
			$sections[$sectionPos]->setEntries($entries);
			$structure->setSections($sections);
		}
	}
}
/**
 * Moves down a section or entry if requested.
 *
 * @param PDFStructure $structure
 */
function moveDown(&$structure) {
	$sections = $structure->getSections();
	foreach ($_POST as $key => $value) {
		// move section
		if (strpos($key, 'down_section_') === 0) {
			$pos = substr($key, strlen('down_section_'));
			$sectionTmp = $sections[$pos + 1];
			$sections[$pos + 1] = $sections[$pos];
			$sections[$pos] = $sectionTmp;
			$structure->setSections($sections);
		}
		// move section entry
		if (strpos($key, 'down_entry_') === 0) {
			$parts = substr($key, strlen('down_entry_'));
			$parts = explode('_', $parts);
			$sectionPos = $parts[0];
			$entryPos = $parts[1];
			$entries = $sections[$sectionPos]->getEntries();
			$entries = $sections[$sectionPos]->getEntries();
			$entryTmp = $entries[$entryPos + 1];
			$entries[$entryPos + 1] = $entries[$entryPos];
			$entries[$entryPos] = $entryTmp;
			$sections[$sectionPos]->setEntries($entries);
			$structure->setSections($sections);
		}
	}
}
?>