<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * Admin page to manage installation element types
 */

$res = 0;
if (!$res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php";
if (!$res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php";
if (!$res) die("Include of main fails");

require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
dol_include_once('/kundenkarte/lib/kundenkarte.lib.php');
dol_include_once('/kundenkarte/class/anlagetype.class.php');

$langs->loadLangs(array('admin', 'kundenkarte@kundenkarte'));

// Security check
if (!$user->admin && !$user->hasRight('kundenkarte', 'admin')) {
	accessforbidden();
}

$action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha');
$typeId = GETPOSTINT('typeid');

// System filter - save in session for persistence
$sessionKey = 'kundenkarte_anlage_types_system_filter';
if (GETPOSTISSET('system')) {
	$systemFilter = GETPOSTINT('system');
	$_SESSION[$sessionKey] = $systemFilter;
} elseif (isset($_SESSION[$sessionKey])) {
	$systemFilter = $_SESSION[$sessionKey];
} else {
	$systemFilter = 0;
}

$form = new Form($db);
$anlageType = new AnlageType($db);

// Load systems
$systems = array();
$sql = "SELECT rowid, code, label FROM ".MAIN_DB_PREFIX."c_kundenkarte_anlage_system WHERE active = 1 ORDER BY position ASC";
$resql = $db->query($sql);
if ($resql) {
	while ($obj = $db->fetch_object($resql)) {
		$systems[$obj->rowid] = $obj;
	}
}

/*
 * Actions
 */

if ($action == 'add') {
	$anlageType->ref = GETPOST('ref', 'aZ09');
	$anlageType->label = GETPOST('label', 'alphanohtml');
	$anlageType->label_short = GETPOST('label_short', 'alphanohtml');
	$anlageType->description = GETPOST('description', 'restricthtml');
	$anlageType->fk_system = GETPOSTINT('fk_system');
	$anlageType->can_have_children = GETPOSTINT('can_have_children');
	$anlageType->can_be_nested = GETPOSTINT('can_be_nested');
	$anlageType->allowed_parent_types = preg_replace('/[^A-Z0-9_,]/i', '', GETPOST('allowed_parent_types', 'nohtml'));
	$anlageType->can_have_equipment = GETPOSTINT('can_have_equipment');
	$anlageType->picto = GETPOST('picto', 'alphanohtml');
	$anlageType->color = GETPOST('color', 'alphanohtml');
	$anlageType->position = GETPOSTINT('position');
	$anlageType->active = 1;

	if (empty($anlageType->ref) || empty($anlageType->label)) {
		setEventMessages($langs->trans('ErrorFieldRequired'), null, 'errors');
		$action = 'create';
	} else {
		$result = $anlageType->create($user);
		if ($result > 0) {
			// Create default fields for the new type
			$defaultFields = array(
				array('code' => 'manufacturer', 'label' => 'Hersteller', 'type' => 'text', 'position' => 10, 'show_in_hover' => 1, 'show_in_tree' => 1),
				array('code' => 'model', 'label' => 'Modell', 'type' => 'text', 'position' => 20, 'show_in_hover' => 1, 'show_in_tree' => 0),
				array('code' => 'serial_number', 'label' => 'Seriennummer', 'type' => 'text', 'position' => 30, 'show_in_hover' => 1, 'show_in_tree' => 0),
				array('code' => 'power_rating', 'label' => 'Leistung', 'type' => 'text', 'position' => 40, 'show_in_hover' => 1, 'show_in_tree' => 1),
				array('code' => 'location', 'label' => 'Standort', 'type' => 'text', 'position' => 50, 'show_in_hover' => 1, 'show_in_tree' => 0),
				array('code' => 'installation_date', 'label' => 'Installationsdatum', 'type' => 'date', 'position' => 60, 'show_in_hover' => 1, 'show_in_tree' => 0),
			);

			foreach ($defaultFields as $field) {
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field";
				$sql .= " (fk_anlage_type, field_code, field_label, field_type, field_options, show_in_tree, show_in_hover, required, position, active)";
				$sql .= " VALUES (".((int) $anlageType->id).", '".$db->escape($field['code'])."', '".$db->escape($field['label'])."',";
				$sql .= " '".$db->escape($field['type'])."', '', ".((int) $field['show_in_tree']).", ".((int) $field['show_in_hover']).", 0, ".((int) $field['position']).", 1)";
				$db->query($sql);
			}

			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
			header('Location: '.$_SERVER['PHP_SELF'].'?action=edit&typeid='.$anlageType->id.'&system='.$anlageType->fk_system);
			exit;
		} else {
			setEventMessages($anlageType->error, $anlageType->errors, 'errors');
			$action = 'create';
		}
	}
}

if ($action == 'update') {
	$anlageType->fetch($typeId);
	$anlageType->ref = GETPOST('ref', 'aZ09');
	$anlageType->label = GETPOST('label', 'alphanohtml');
	$anlageType->label_short = GETPOST('label_short', 'alphanohtml');
	$anlageType->description = GETPOST('description', 'restricthtml');
	$anlageType->fk_system = GETPOSTINT('fk_system');
	$anlageType->can_have_children = GETPOSTINT('can_have_children');
	$anlageType->can_be_nested = GETPOSTINT('can_be_nested');
	$anlageType->allowed_parent_types = preg_replace('/[^A-Z0-9_,]/i', '', GETPOST('allowed_parent_types', 'nohtml'));
	$anlageType->can_have_equipment = GETPOSTINT('can_have_equipment');
	$anlageType->picto = GETPOST('picto', 'alphanohtml');
	$anlageType->color = GETPOST('color', 'alphanohtml');
	$anlageType->position = GETPOSTINT('position');

	$result = $anlageType->update($user);
	if ($result > 0) {
		setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
		header('Location: '.$_SERVER['PHP_SELF'].'?system='.$anlageType->fk_system);
		exit;
	} else {
		setEventMessages($anlageType->error, $anlageType->errors, 'errors');
		$action = 'edit';
	}
}

if ($action == 'confirm_delete' && $confirm == 'yes') {
	$anlageType->fetch($typeId);
	$result = $anlageType->delete($user);
	if ($result > 0) {
		setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs');
	} else {
		setEventMessages($anlageType->error, $anlageType->errors, 'errors');
	}
	$action = '';
}

if ($action == 'activate') {
	$sql = "UPDATE ".MAIN_DB_PREFIX."kundenkarte_anlage_type SET active = 1 WHERE rowid = ".((int) $typeId);
	$db->query($sql);
	$action = '';
}

if ($action == 'deactivate') {
	$sql = "UPDATE ".MAIN_DB_PREFIX."kundenkarte_anlage_type SET active = 0 WHERE rowid = ".((int) $typeId);
	$db->query($sql);
	$action = '';
}

// Copy type with all fields
if ($action == 'copy' && $typeId > 0) {
	$sourceType = new AnlageType($db);
	if ($sourceType->fetch($typeId) > 0) {
		// Create new type with copied data
		$newType = new AnlageType($db);
		$newType->ref = $sourceType->ref.'_COPY';
		$newType->label = $sourceType->label.' (Kopie)';
		$newType->label_short = $sourceType->label_short;
		$newType->description = $sourceType->description;
		$newType->fk_system = $sourceType->fk_system;
		$newType->can_have_children = $sourceType->can_have_children;
		$newType->can_be_nested = $sourceType->can_be_nested;
		$newType->allowed_parent_types = $sourceType->allowed_parent_types;
		$newType->can_have_equipment = $sourceType->can_have_equipment;
		$newType->picto = $sourceType->picto;
		$newType->color = $sourceType->color;
		$newType->position = $sourceType->position + 1;
		$newType->active = 1;

		$result = $newType->create($user);
		if ($result > 0) {
			// Copy all fields from source type
			$sourceFields = $sourceType->fetchFields(0); // Get all fields including inactive
			foreach ($sourceFields as $field) {
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field";
				$sql .= " (fk_anlage_type, field_code, field_label, field_type, field_options, show_in_tree, show_in_hover, required, position, active)";
				$sql .= " VALUES (".((int) $newType->id).", '".$db->escape($field->field_code)."', '".$db->escape($field->field_label)."',";
				$sql .= " '".$db->escape($field->field_type)."', '".$db->escape($field->field_options)."', ".((int) $field->show_in_tree).",";
				$sql .= " ".((int) $field->show_in_hover).", ".((int) $field->required).", ".((int) $field->position).", ".((int) $field->active).")";
				$db->query($sql);
			}

			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
			header('Location: '.$_SERVER['PHP_SELF'].'?action=edit&typeid='.$newType->id.'&system='.$newType->fk_system);
			exit;
		} else {
			setEventMessages($newType->error, $newType->errors, 'errors');
		}
	}
	$action = '';
}

// Field actions
$fieldId = GETPOSTINT('fieldid');

if ($action == 'add_field') {
	$fieldCode = GETPOST('field_code', 'aZ09');
	$fieldLabel = GETPOST('field_label', 'alphanohtml');
	$fieldType = GETPOST('field_type', 'aZ09');
	$fieldOptions = GETPOST('field_options', 'nohtml');
	$showInTree = GETPOSTINT('show_in_tree');
	$treeDisplayMode = GETPOST('tree_display_mode', 'aZ09');
	if (empty($treeDisplayMode)) $treeDisplayMode = 'badge';
	$badgeColor = GETPOST('badge_color', 'alphanohtml');
	if ($badgeColor && !preg_match('/^#[0-9A-Fa-f]{6}$/', $badgeColor)) {
		$badgeColor = '';
	}
	$showInHover = GETPOSTINT('show_in_hover');
	$enableAutocomplete = GETPOSTINT('enable_autocomplete');
	$isRequired = GETPOSTINT('is_required');
	$fieldPosition = GETPOSTINT('field_position');

	if (empty($fieldCode) || empty($fieldLabel) || empty($fieldType)) {
		setEventMessages($langs->trans('ErrorFieldRequired'), null, 'errors');
	} else {
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field";
		$sql .= " (fk_anlage_type, field_code, field_label, field_type, field_options, show_in_tree, tree_display_mode, badge_color, show_in_hover, enable_autocomplete, required, position, active)";
		$sql .= " VALUES (".((int) $typeId).", '".$db->escape($fieldCode)."', '".$db->escape($fieldLabel)."',";
		$sql .= " '".$db->escape($fieldType)."', '".$db->escape($fieldOptions)."',";
		$sql .= " ".((int) $showInTree).", '".$db->escape($treeDisplayMode)."', ".($badgeColor ? "'".$db->escape($badgeColor)."'" : "NULL").", ".((int) $showInHover).", ".((int) $enableAutocomplete).", ".((int) $isRequired).", ".((int) $fieldPosition).", 1)";

		if ($db->query($sql)) {
			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
		} else {
			setEventMessages($db->lasterror(), null, 'errors');
		}
	}
	$action = 'edit';
}

if ($action == 'update_field') {
	$fieldCode = GETPOST('field_code', 'aZ09');
	$fieldLabel = GETPOST('field_label', 'alphanohtml');
	$fieldType = GETPOST('field_type', 'aZ09');
	$fieldOptions = GETPOST('field_options', 'nohtml');
	$showInTree = GETPOSTINT('show_in_tree');
	$treeDisplayMode = GETPOST('tree_display_mode', 'aZ09');
	if (empty($treeDisplayMode)) $treeDisplayMode = 'badge';
	$badgeColor = GETPOST('badge_color', 'alphanohtml');
	// Validate color format (#RRGGBB)
	if ($badgeColor && !preg_match('/^#[0-9A-Fa-f]{6}$/', $badgeColor)) {
		$badgeColor = '';
	}
	$showInHover = GETPOSTINT('show_in_hover');
	$enableAutocomplete = GETPOSTINT('enable_autocomplete');
	$isRequired = GETPOSTINT('is_required');
	$fieldPosition = GETPOSTINT('field_position');

	$sql = "UPDATE ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field SET";
	$sql .= " field_code = '".$db->escape($fieldCode)."',";
	$sql .= " field_label = '".$db->escape($fieldLabel)."',";
	$sql .= " field_type = '".$db->escape($fieldType)."',";
	$sql .= " field_options = '".$db->escape($fieldOptions)."',";
	$sql .= " show_in_tree = ".((int) $showInTree).",";
	$sql .= " tree_display_mode = '".$db->escape($treeDisplayMode)."',";
	$sql .= " badge_color = ".($badgeColor ? "'".$db->escape($badgeColor)."'" : "NULL").",";
	$sql .= " show_in_hover = ".((int) $showInHover).",";
	$sql .= " enable_autocomplete = ".((int) $enableAutocomplete).",";
	$sql .= " required = ".((int) $isRequired).",";
	$sql .= " position = ".((int) $fieldPosition);
	$sql .= " WHERE rowid = ".((int) $fieldId);

	if ($db->query($sql)) {
		setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
	} else {
		setEventMessages($db->lasterror(), null, 'errors');
	}
	$action = 'edit';
}

if ($action == 'confirm_delete_field' && $confirm == 'yes') {
	$sql = "DELETE FROM ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field WHERE rowid = ".((int) $fieldId);
	if ($db->query($sql)) {
		setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs');
	} else {
		setEventMessages($db->lasterror(), null, 'errors');
	}
	// Redirect back to edit page to stay in the fields list
	header('Location: '.$_SERVER['PHP_SELF'].'?action=edit&typeid='.$typeId.'&system='.$systemFilter);
	exit;
}

if ($action == 'activate_field') {
	$sql = "UPDATE ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field SET active = 1 WHERE rowid = ".((int) $fieldId);
	$db->query($sql);
	$action = 'edit';
}

if ($action == 'deactivate_field') {
	$sql = "UPDATE ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field SET active = 0 WHERE rowid = ".((int) $fieldId);
	$db->query($sql);
	$action = 'edit';
}

/*
 * View
 */

$title = $langs->trans('AnlagenTypes');

// Include CSS and JS
$morejs = array('/kundenkarte/js/kundenkarte.js?v=1769962608');
$morecss = array('/kundenkarte/css/kundenkarte.css?v=1769962608');

llxHeader('', $title, '', '', 0, 0, $morejs, $morecss);

$head = kundenkarteAdminPrepareHead();
print dol_get_fiche_head($head, 'types', $langs->trans('ModuleKundenKarteName'), -1, 'fa-file');

// Confirmation for type deletion
if ($action == 'delete') {
	print $form->formconfirm(
		$_SERVER['PHP_SELF'].'?typeid='.$typeId.'&system='.$systemFilter,
		$langs->trans('Delete'),
		$langs->trans('ConfirmDeleteType'),
		'confirm_delete',
		'',
		'yes',
		1
	);
}

// Confirmation for field deletion
if ($action == 'delete_field') {
	print $form->formconfirm(
		$_SERVER['PHP_SELF'].'?typeid='.$typeId.'&fieldid='.$fieldId.'&system='.$systemFilter,
		$langs->trans('Delete'),
		$langs->trans('ConfirmDeleteField'),
		'confirm_delete_field',
		'',
		'yes',
		1
	);
	$action = 'edit'; // Stay in edit mode to show the fields
}

// Add/Edit form
if (in_array($action, array('create', 'edit'))) {
	if ($action == 'edit' && $typeId > 0) {
		$anlageType->fetch($typeId);
	}

	// Get all types for parent selection
	// We need to filter by the same system OR show all types if this type is for all systems
	$allTypes = $anlageType->fetchAllBySystem(0, 0); // Get all types, we'll filter in the template

	print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
	print '<input type="hidden" name="token" value="'.newToken().'">';
	print '<input type="hidden" name="action" value="'.($action == 'edit' ? 'update' : 'add').'">';
	if ($action == 'edit') {
		print '<input type="hidden" name="typeid" value="'.$typeId.'">';
	}

	print '<table class="border centpercent">';

	// System
	print '<tr><td class="titlefield">'.$langs->trans('System').'</td>';
	print '<td><select name="fk_system" class="flat minwidth200">';
	$selAll = (empty($anlageType->fk_system)) ? ' selected' : '';
	print '<option value="0"'.$selAll.'>'.$langs->trans('AllSystems').'</option>';
	foreach ($systems as $sys) {
		if ($sys->code === 'GLOBAL') continue; // Gebaeude-Typen haben eigenen Tab
		$sel = ($anlageType->fk_system == $sys->rowid) ? ' selected' : '';
		print '<option value="'.$sys->rowid.'"'.$sel.'>'.dol_escape_htmltag($sys->label).'</option>';
	}
	print '</select>';
	print ' <span class="opacitymedium">('.$langs->trans('AllSystemsHint').')</span>';
	print '</td></tr>';

	// Reference
	print '<tr><td class="fieldrequired">'.$langs->trans('TypeRef').'</td>';
	print '<td><input type="text" name="ref" class="flat minwidth200" value="'.dol_escape_htmltag($anlageType->ref).'" maxlength="64" required>';
	print ' <span class="opacitymedium">(UPPERCASE, no spaces)</span></td></tr>';

	// Label
	print '<tr><td class="fieldrequired">'.$langs->trans('TypeLabel').'</td>';
	print '<td><input type="text" name="label" class="flat minwidth300" value="'.dol_escape_htmltag($anlageType->label).'" required></td></tr>';

	// Short label
	print '<tr><td>'.$langs->trans('TypeShortLabel').'</td>';
	print '<td><input type="text" name="label_short" class="flat" value="'.dol_escape_htmltag($anlageType->label_short).'" maxlength="64"></td></tr>';

	// Description
	print '<tr><td>'.$langs->trans('Description').'</td>';
	print '<td><textarea name="description" class="flat minwidth300" rows="2">'.dol_escape_htmltag($anlageType->description).'</textarea></td></tr>';

	// Can have children
	print '<tr><td>'.$langs->trans('CanHaveChildren').'</td>';
	print '<td><input type="checkbox" name="can_have_children" value="1"'.($anlageType->can_have_children ? ' checked' : '').'></td></tr>';

	// Can be nested
	print '<tr><td>'.$langs->trans('CanBeNested').'</td>';
	print '<td><input type="checkbox" name="can_be_nested" value="1"'.($anlageType->can_be_nested ? ' checked' : '').'>';
	print ' <span class="opacitymedium">('.$langs->trans('SameTypeUnderItself').')</span></td></tr>';

	// Can have equipment (Hutschienen-Komponenten)
	print '<tr><td>'.$langs->trans('CanHaveEquipment').'</td>';
	print '<td><input type="checkbox" name="can_have_equipment" value="1"'.($anlageType->can_have_equipment ? ' checked' : '').'>';
	print ' <span class="opacitymedium">('.$langs->trans('CanHaveEquipmentHelp').')</span></td></tr>';

	// Allowed parent types - with multi-select UI
	print '<tr><td>'.$langs->trans('AllowedParentTypes').'</td>';
	print '<td>';

	// Hidden field to store the actual value
	print '<input type="hidden" name="allowed_parent_types" id="allowed_parent_types" value="'.dol_escape_htmltag($anlageType->allowed_parent_types).'">';

	// Selection UI
	print '<div class="kundenkarte-parent-types-selector">';

	// Select dropdown with add button
	// Get current type's system for filtering (when editing)
	$currentTypeSystem = ($action == 'edit') ? $anlageType->fk_system : GETPOSTINT('fk_system');

	print '<div style="display:flex;gap:5px;margin-bottom:10px;align-items:center;">';
	print '<select id="parent_type_select" class="flat" style="height:30px;">';
	print '<option value="">'.$langs->trans('SelectType').'</option>';
	foreach ($allTypes as $t) {
		// Don't show current type in list (can't be parent of itself unless can_be_nested)
		if ($action == 'edit' && $t->id == $typeId) continue;

		// Filter by system: Show type if:
		// 1. Current type is for all systems (fk_system = 0) - show all parent types
		// 2. Parent type is for all systems (fk_system = 0) - always available
		// 3. Parent type has same system as current type
		$showType = false;
		if (empty($currentTypeSystem)) {
			// Current type is for all systems - show all possible parent types
			$showType = true;
		} elseif (empty($t->fk_system)) {
			// Parent type is global (all systems) - always show
			$showType = true;
		} elseif ($t->fk_system == $currentTypeSystem) {
			// Same system
			$showType = true;
		}

		if (!$showType) continue;

		// Add system indicator for clarity
		$systemHint = '';
		if (empty($t->fk_system)) {
			$systemHint = ' ['.$langs->trans('AllSystems').']';
		} elseif (isset($systems[$t->fk_system])) {
			$systemHint = ' ['.$systems[$t->fk_system]->label.']';
		}

		print '<option value="'.dol_escape_htmltag($t->ref).'" data-label="'.dol_escape_htmltag($t->label).'" data-system="'.$t->fk_system.'">'.dol_escape_htmltag($t->ref).' - '.dol_escape_htmltag($t->label).$systemHint.'</option>';
	}
	print '</select>';
	print '<button type="button" class="button" id="add_parent_type_btn"><i class="fa fa-plus"></i> '.$langs->trans('Add').'</button>';
	print '</div>';

	// List of selected parent types
	print '<div id="selected_parent_types" class="kundenkarte-selected-items">';
	// Will be filled by JavaScript
	print '</div>';

	print '</div>';

	print '<span class="opacitymedium">('.$langs->trans('AllowedParentTypesHelp').')</span>';
	print '</td></tr>';

	// Icon
	print '<tr><td>'.$langs->trans('SystemPicto').'</td>';
	print '<td><div class="kundenkarte-icon-picker-wrapper">';
	print '<span class="kundenkarte-icon-preview">';
	if ($anlageType->picto) {
		print kundenkarte_render_icon($anlageType->picto);
	}
	print '</span>';
	print '<input type="text" name="picto" class="flat minwidth200" value="'.dol_escape_htmltag($anlageType->picto).'" placeholder="fa-cube">';
	print '<button type="button" class="kundenkarte-icon-picker-btn" data-input="picto"><i class="fa fa-th"></i> '.$langs->trans('SelectIcon').'</button>';
	print '</div></td></tr>';

	// Position
	print '<tr><td>'.$langs->trans('Position').'</td>';
	print '<td><input type="number" name="position" class="flat" value="'.($anlageType->position ?: 0).'" min="0"></td></tr>';

	print '</table>';

	print '<div class="center" style="margin-top:20px;">';
	print '<button type="submit" class="button">'.$langs->trans('Save').'</button>';
	print ' <a class="button button-cancel" href="'.$_SERVER['PHP_SELF'].'?system='.$systemFilter.'">'.$langs->trans('Cancel').'</a>';
	print '</div>';

	print '</form>';

	// Fields management for existing type
	if ($action == 'edit' && $typeId > 0) {
		$editFieldId = GETPOSTINT('editfield');

		print '<br><br>';
		print '<h3>'.$langs->trans('AnlagenTypeFields').'</h3>';

		$fields = $anlageType->fetchFields(0);

		// Field types available
		$fieldTypes = array(
			'header' => '── Überschrift ──',
			'text' => 'Textfeld (einzeilig)',
			'textarea' => 'Textfeld (mehrzeilig)',
			'number' => 'Zahlenfeld',
			'select' => 'Dropdown-Auswahl',
			'date' => 'Datumsfeld',
			'checkbox' => 'Checkbox (Ja/Nein)',
		);

		// Output edit forms BEFORE the table (forms cannot be inside tables)
		foreach ($fields as $field) {
			if ($editFieldId == $field->rowid) {
				$formId = 'editfield_'.$field->rowid;
				print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" id="'.$formId.'">';
				print '<input type="hidden" name="token" value="'.newToken().'">';
				print '<input type="hidden" name="action" value="update_field">';
				print '<input type="hidden" name="typeid" value="'.$typeId.'">';
				print '<input type="hidden" name="fieldid" value="'.$field->rowid.'">';
				print '<input type="hidden" name="system" value="'.$systemFilter.'">';
				print '</form>';
			}
		}

		print '<table class="noborder centpercent">';
		print '<tr class="liste_titre">';
		print '<th>'.$langs->trans('FieldCode').'</th>';
		print '<th>'.$langs->trans('FieldLabel').'</th>';
		print '<th>'.$langs->trans('FieldType').'</th>';
		print '<th>'.$langs->trans('FieldOptions').'</th>';
		print '<th class="center">'.$langs->trans('ShowInTree').'</th>';
		print '<th class="center" title="Badge (rechts) oder Klammer (nach Bezeichnung)">'.$langs->trans('TreeDisplayMode').'</th>';
		print '<th class="center" title="Farbe des Badges im Baum"><i class="fa fa-paint-brush"></i></th>';
		print '<th class="center">'.$langs->trans('ShowInHover').'</th>';
		print '<th class="center" title="Autocomplete aus gespeicherten Werten"><i class="fa fa-magic"></i></th>';
		print '<th class="center">'.$langs->trans('IsRequired').'</th>';
		print '<th class="center">'.$langs->trans('Position').'</th>';
		print '<th class="center">'.$langs->trans('Status').'</th>';
		print '<th class="center">'.$langs->trans('Actions').'</th>';
		print '</tr>';

		foreach ($fields as $field) {
			// Check if we're editing this field
			if ($editFieldId == $field->rowid) {
				// Edit row - inputs linked to form outside table via form attribute
				$formId = 'editfield_'.$field->rowid;

				print '<tr class="oddeven">';
				print '<td><input type="text" name="field_code" form="'.$formId.'" class="flat minwidth100" value="'.dol_escape_htmltag($field->field_code).'" required></td>';
				print '<td><input type="text" name="field_label" form="'.$formId.'" class="flat minwidth150" value="'.dol_escape_htmltag($field->field_label).'" required></td>';
				print '<td><select name="field_type" form="'.$formId.'" class="flat">';
				foreach ($fieldTypes as $ftype => $flabel) {
					$sel = ($field->field_type == $ftype) ? ' selected' : '';
					print '<option value="'.$ftype.'"'.$sel.'>'.$flabel.'</option>';
				}
				print '</select></td>';
				print '<td><input type="text" name="field_options" form="'.$formId.'" class="flat minwidth100" value="'.dol_escape_htmltag($field->field_options).'" placeholder="opt1|opt2|opt3"></td>';
				print '<td class="center"><input type="checkbox" name="show_in_tree" form="'.$formId.'" value="1"'.($field->show_in_tree ? ' checked' : '').'></td>';
				$treeMode = $field->tree_display_mode ?? 'badge';
				print '<td class="center"><select name="tree_display_mode" form="'.$formId.'" class="flat" style="width:90px;">';
				print '<option value="badge"'.($treeMode == 'badge' ? ' selected' : '').'>'.$langs->trans('Badge').'</option>';
				print '<option value="parentheses"'.($treeMode == 'parentheses' ? ' selected' : '').'>'.$langs->trans('Parentheses').'</option>';
				print '</select></td>';
				$badgeColor = $field->badge_color ?? '';
				print '<td class="center"><input type="color" name="badge_color" form="'.$formId.'" value="'.($badgeColor ?: '#2a4a5e').'" style="width:30px;height:24px;padding:0;border:1px solid #ccc;cursor:pointer;" title="Badge-Farbe"></td>';
				print '<td class="center"><input type="checkbox" name="show_in_hover" form="'.$formId.'" value="1"'.($field->show_in_hover ? ' checked' : '').'></td>';
				print '<td class="center"><input type="checkbox" name="enable_autocomplete" form="'.$formId.'" value="1"'.($field->enable_autocomplete ? ' checked' : '').' title="Autocomplete aktivieren"></td>';
				print '<td class="center"><input type="checkbox" name="is_required" form="'.$formId.'" value="1"'.($field->required ? ' checked' : '').'></td>';
				print '<td class="center"><input type="number" name="field_position" form="'.$formId.'" class="flat" style="width:50px;" value="'.$field->position.'" min="0"></td>';
				print '<td></td>';
				print '<td class="center nowraponall">';
				print '<div style="display:inline-flex;gap:8px;">';
				print '<button type="submit" form="'.$formId.'" class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;background:#28a745;border-color:#28a745;color:#fff;" title="'.$langs->trans('Save').'"><i class="fas fa-save"></i></button>';
				print '<a class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;" href="'.$_SERVER['PHP_SELF'].'?action=edit&typeid='.$typeId.'&system='.$systemFilter.'" title="'.$langs->trans('Cancel').'"><i class="fas fa-times"></i></a>';
				print '</div>';
				print '</td>';
				print '</tr>';
			} else {
				// Display row
				print '<tr class="oddeven">';
				print '<td>'.dol_escape_htmltag($field->field_code).'</td>';
				print '<td>'.dol_escape_htmltag($field->field_label).'</td>';
				print '<td>'.dol_escape_htmltag($fieldTypes[$field->field_type] ?? $field->field_type).'</td>';
				print '<td class="small opacitymedium">'.dol_escape_htmltag(dol_trunc($field->field_options, 20)).'</td>';
				print '<td class="center">'.($field->show_in_tree ? img_picto('', 'tick') : '').'</td>';
				$treeMode = $field->tree_display_mode ?? 'badge';
				$treeModeIcon = ($treeMode == 'badge') ? '<span class="badge badge-secondary" style="font-size:9px;">B</span>' : '<span style="color:#666;">(K)</span>';
				print '<td class="center" title="'.($treeMode == 'badge' ? $langs->trans('Badge') : $langs->trans('Parentheses')).'">'.$treeModeIcon.'</td>';
				$badgeColor = $field->badge_color ?? '';
				if ($badgeColor) {
					print '<td class="center"><span style="display:inline-block;width:20px;height:20px;background:'.$badgeColor.';border-radius:3px;border:1px solid #555;"></span></td>';
				} else {
					print '<td class="center"><span style="color:#888;">-</span></td>';
				}
				print '<td class="center">'.($field->show_in_hover ? img_picto('', 'tick') : '').'</td>';
				$enableAutocomplete = isset($field->enable_autocomplete) ? $field->enable_autocomplete : 0;
				print '<td class="center">'.($enableAutocomplete ? '<i class="fa fa-magic" style="color:#3498db;" title="Autocomplete aktiv"></i>' : '').'</td>';
				print '<td class="center">'.($field->required ? img_picto('', 'tick') : '').'</td>';
				print '<td class="center">'.$field->position.'</td>';
				print '<td class="center">';
				if ($field->active) {
					print '<a href="'.$_SERVER['PHP_SELF'].'?action=deactivate_field&typeid='.$typeId.'&fieldid='.$field->rowid.'&system='.$systemFilter.'&token='.newToken().'">'.img_picto($langs->trans('Enabled'), 'switch_on').'</a>';
				} else {
					print '<a href="'.$_SERVER['PHP_SELF'].'?action=activate_field&typeid='.$typeId.'&fieldid='.$field->rowid.'&system='.$systemFilter.'&token='.newToken().'">'.img_picto($langs->trans('Disabled'), 'switch_off').'</a>';
				}
				print '</td>';
				print '<td class="center nowraponall">';
				print '<div style="display:inline-flex;gap:8px;">';
				print '<a class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;" href="'.$_SERVER['PHP_SELF'].'?action=edit&typeid='.$typeId.'&editfield='.$field->rowid.'&system='.$systemFilter.'" title="'.$langs->trans('Edit').'"><i class="fas fa-pen"></i></a>';
				print '<a class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;background:#dc3545;border-color:#dc3545;color:#fff;" href="'.$_SERVER['PHP_SELF'].'?action=delete_field&typeid='.$typeId.'&fieldid='.$field->rowid.'&system='.$systemFilter.'&token='.newToken().'" title="'.$langs->trans('Delete').'"><i class="fas fa-trash"></i></a>';
				print '</div>';
				print '</td>';
				print '</tr>';
			}
		}

		if (empty($fields)) {
			print '<tr class="oddeven"><td colspan="12" class="opacitymedium">'.$langs->trans('NoFieldsDefined').'</td></tr>';
		}

		print '</table>';

		// Add new field form - completely separate from table
		print '<div class="margintoponlyshort">';
		print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
		print '<input type="hidden" name="token" value="'.newToken().'">';
		print '<input type="hidden" name="action" value="add_field">';
		print '<input type="hidden" name="typeid" value="'.$typeId.'">';
		print '<input type="hidden" name="system" value="'.$systemFilter.'">';
		print '<table class="noborder centpercent">';
		print '<tr class="liste_titre">';
		print '<th colspan="12">'.$langs->trans('Add').' '.$langs->trans('Field').'</th>';
		print '</tr>';
		print '<tr class="oddeven">';
		print '<td><input type="text" name="field_code" class="flat minwidth100" placeholder="CODE" required></td>';
		print '<td><input type="text" name="field_label" class="flat minwidth150" placeholder="'.$langs->trans('FieldLabel').'" required></td>';
		print '<td><select name="field_type" class="flat" required>';
		print '<option value="">'.$langs->trans('Select').'</option>';
		foreach ($fieldTypes as $ftype => $flabel) {
			print '<option value="'.$ftype.'">'.$flabel.'</option>';
		}
		print '</select></td>';
		print '<td><input type="text" name="field_options" class="flat minwidth100" placeholder="opt1|opt2"></td>';
		print '<td class="center"><input type="checkbox" name="show_in_tree" value="1"></td>';
		print '<td class="center"><select name="tree_display_mode" class="flat" style="width:90px;">';
		print '<option value="badge">'.$langs->trans('Badge').'</option>';
		print '<option value="parentheses">'.$langs->trans('Parentheses').'</option>';
		print '</select></td>';
		print '<td class="center"><input type="color" name="badge_color" value="#2a4a5e" style="width:30px;height:24px;padding:0;border:1px solid #ccc;cursor:pointer;" title="Badge-Farbe"></td>';
		print '<td class="center"><input type="checkbox" name="show_in_hover" value="1" checked></td>';
		print '<td class="center"><input type="checkbox" name="enable_autocomplete" value="1" title="Autocomplete aktivieren"></td>';
		print '<td class="center"><input type="checkbox" name="is_required" value="1"></td>';
		print '<td class="center"><input type="number" name="field_position" class="flat" style="width:50px;" value="0" min="0"></td>';
		print '<td></td>';
		print '<td class="center"><button type="submit" class="button buttongen"><i class="fa fa-plus"></i> '.$langs->trans('Add').'</button></td>';
		print '</tr>';
		print '</table>';
		print '</form>';
		print '</div>';

		// Help box for field options
		print '<div class="info" style="margin-top:15px;">';
		print '<p><strong><i class="fa fa-info-circle"></i> Hilfe: Feld-Optionen nach Feldtyp</strong></p>';
		print '<table class="noborder" style="margin-top:10px;">';
		print '<tr><td style="width:200px;"><strong>Textfeld (einzeilig)</strong></td><td>Keine Optionen nötig</td></tr>';
		print '<tr><td><strong>Textfeld (mehrzeilig)</strong></td><td>Keine Optionen nötig</td></tr>';
		print '<tr><td><strong>Zahlenfeld</strong></td><td>Optional: <code>min:0|max:100|step:0.1</code></td></tr>';
		print '<tr><td><strong>Dropdown-Auswahl</strong></td><td><span style="color:#c00;">Pflicht!</span> Optionen mit <code>|</code> trennen, z.B.: <code>Option A|Option B|Option C</code></td></tr>';
		print '<tr><td><strong>Datumsfeld</strong></td><td>Keine Optionen nötig</td></tr>';
		print '<tr><td><strong>Checkbox (Ja/Nein)</strong></td><td>Keine Optionen nötig</td></tr>';
		print '</table>';
		print '</div>';
	}

} else {
	// System filter
	print '<form method="GET" action="'.$_SERVER['PHP_SELF'].'" style="margin-bottom:15px;">';
	print $langs->trans('FilterBySystem').': ';
	print '<select name="system" class="flat" onchange="this.form.submit();">';
	print '<option value="0">'.$langs->trans('All').'</option>';
	foreach ($systems as $sys) {
		if ($sys->code === 'GLOBAL') continue; // Gebaeude-Typen haben eigenen Tab
		$sel = ($systemFilter == $sys->rowid) ? ' selected' : '';
		print '<option value="'.$sys->rowid.'"'.$sel.'>'.dol_escape_htmltag($sys->label).'</option>';
	}
	print '</select>';
	print '</form>';

	// Add button
	print '<div style="margin-bottom:15px;">';
	print '<a class="button" href="'.$_SERVER['PHP_SELF'].'?action=create&system='.$systemFilter.'">';
	print '<i class="fa fa-plus"></i> '.$langs->trans('AddType');
	print '</a>';
	print '</div>';

	// List
	$types = $anlageType->fetchAllBySystem($systemFilter, 0, 1);

	print '<table class="noborder centpercent">';
	print '<tr class="liste_titre">';
	print '<th>'.$langs->trans('TypeRef').'</th>';
	print '<th>'.$langs->trans('TypeLabel').'</th>';
	print '<th>'.$langs->trans('System').'</th>';
	print '<th class="center">'.$langs->trans('CanHaveChildren').'</th>';
	print '<th class="center">'.$langs->trans('Position').'</th>';
	print '<th class="center">'.$langs->trans('Status').'</th>';
	print '<th class="right">'.$langs->trans('Actions').'</th>';
	print '</tr>';

	foreach ($types as $type) {
		print '<tr class="oddeven">';

		print '<td>';
		if ($type->picto) {
			print kundenkarte_render_icon($type->picto).' ';
		}
		print dol_escape_htmltag($type->ref).'</td>';

		print '<td>'.dol_escape_htmltag($type->label);
		if ($type->label_short) {
			print ' <span class="opacitymedium">('.$type->label_short.')</span>';
		}
		print '</td>';

		if (empty($type->fk_system)) {
			print '<td><span class="badge badge-info">'.$langs->trans('AllSystems').'</span></td>';
		} else {
			print '<td>'.dol_escape_htmltag($type->system_label).'</td>';
		}
		print '<td class="center">'.($type->can_have_children ? img_picto('', 'tick') : '').'</td>';
		print '<td class="center">'.$type->position.'</td>';

		print '<td class="center">';
		if ($type->active) {
			print '<a href="'.$_SERVER['PHP_SELF'].'?action=deactivate&typeid='.$type->id.'&system='.$systemFilter.'&token='.newToken().'">'.img_picto($langs->trans('Enabled'), 'switch_on').'</a>';
		} else {
			print '<a href="'.$_SERVER['PHP_SELF'].'?action=activate&typeid='.$type->id.'&system='.$systemFilter.'&token='.newToken().'">'.img_picto($langs->trans('Disabled'), 'switch_off').'</a>';
		}
		print '</td>';

		print '<td class="right nowraponall">';
		print '<div style="display:inline-flex;gap:8px;justify-content:flex-end;">';
		print '<a class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;" href="'.$_SERVER['PHP_SELF'].'?action=edit&typeid='.$type->id.'&system='.$systemFilter.'" title="'.$langs->trans('Edit').'"><i class="fas fa-pen"></i></a>';
		print '<a class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;" href="'.$_SERVER['PHP_SELF'].'?action=copy&typeid='.$type->id.'&system='.$systemFilter.'&token='.newToken().'" title="'.$langs->trans('Copy').'"><i class="fas fa-copy"></i></a>';
		if (!$type->is_system) {
			print '<a class="button buttongen" style="width:32px;height:32px;padding:0;display:inline-flex;align-items:center;justify-content:center;background:#dc3545;border-color:#dc3545;color:#fff;" href="'.$_SERVER['PHP_SELF'].'?action=delete&typeid='.$type->id.'&system='.$systemFilter.'" title="'.$langs->trans('Delete').'" onclick="return confirm(\''.$langs->trans('ConfirmDelete').'\');"><i class="fas fa-trash"></i></a>';
		}
		print '</div>';
		print '</td>';

		print '</tr>';
	}

	if (empty($types)) {
		print '<tr class="oddeven"><td colspan="7" class="opacitymedium">'.$langs->trans('NoRecords').'</td></tr>';
	}

	print '</table>';
}

print dol_get_fiche_end();

// JavaScript for parent type selector
print '<script>
$(document).ready(function() {
	var $hidden = $("#allowed_parent_types");
	var $select = $("#parent_type_select");
	var $container = $("#selected_parent_types");

	// Initialize from existing value
	function initSelected() {
		var val = $hidden.val();
		$container.empty();
		if (val) {
			var types = val.split(",");
			types.forEach(function(ref) {
				ref = ref.trim();
				if (ref) {
					var $opt = $select.find("option[value=\"" + ref + "\"]");
					var label = $opt.length ? $opt.data("label") : ref;
					addTag(ref, label);
				}
			});
		}
	}

	// Add a tag to the list
	function addTag(ref, label) {
		var $tag = $("<span class=\"kundenkarte-tag\">");
		$tag.text(ref + (label ? " (" + label + ")" : ""));
		var $remove = $("<span class=\"kundenkarte-tag-remove\">&times;</span>");
		$remove.on("click", function() {
			$tag.remove();
			updateHidden();
		});
		$tag.append($remove);
		$container.append($tag);
	}

	// Update hidden field from tags
	function updateHidden() {
		var refs = [];
		$container.find(".kundenkarte-tag").each(function() {
			var text = $(this).text();
			var ref = text.split(" (")[0].trim();
			refs.push(ref);
		});
		$hidden.val(refs.join(","));
	}

	// Add button click
	$("#add_parent_type_btn").on("click", function() {
		var ref = $select.val();
		if (!ref) return;

		// Check if already added
		var current = $hidden.val();
		if (current && current.split(",").indexOf(ref) >= 0) {
			return;
		}

		var label = $select.find("option:selected").data("label");
		addTag(ref, label);
		updateHidden();
		$select.val("");
	});

	// Filter parent type options when system changes
	$("select[name=fk_system]").on("change", function() {
		var selectedSystem = $(this).val();
		$select.find("option").each(function() {
			var optSystem = $(this).data("system");
			if ($(this).val() === "") {
				// Keep the placeholder option visible
				return;
			}

			// Show option if:
			// 1. Selected system is 0 (all systems) - show all options
			// 2. Option system is 0 (global type) - always show
			// 3. Option system matches selected system
			var show = false;
			if (selectedSystem == "0" || selectedSystem === "") {
				show = true;
			} else if (optSystem == 0 || optSystem === "" || optSystem === undefined) {
				show = true;
			} else if (optSystem == selectedSystem) {
				show = true;
			}

			if (show) {
				$(this).show();
			} else {
				$(this).hide();
				// Deselect if hidden
				if ($(this).is(":selected")) {
					$select.val("");
				}
			}
		});
	});

	initSelected();

	// Trigger initial filtering
	$("select[name=fk_system]").trigger("change");
});
</script>';

llxFooter();
$db->close();
