<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX endpoint to get fields for an anlage type
 */

$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/class/html.form.class.php';
dol_include_once('/kundenkarte/class/anlagetype.class.php');
dol_include_once('/kundenkarte/class/anlage.class.php');

header('Content-Type: application/json');

$typeId = GETPOSTINT('type_id');
$anlageId = GETPOSTINT('anlage_id');

if (empty($typeId)) {
	echo json_encode(array('fields' => array()));
	exit;
}

$type = new AnlageType($db);
if ($type->fetch($typeId) <= 0) {
	echo json_encode(array('fields' => array()));
	exit;
}

$fields = $type->fetchFields();

// Get existing values if editing
$existingValues = array();
if ($anlageId > 0) {
	$anlage = new Anlage($db);
	if ($anlage->fetch($anlageId) > 0) {
		$existingValues = $anlage->getFieldValues();
	}
}

$result = array('fields' => array());

foreach ($fields as $field) {
	$fieldData = array(
		'code' => $field->field_code,
		'label' => $field->field_label,
		'type' => $field->field_type,
		'options' => $field->field_options,
		'required' => (int)$field->required === 1,
		'autocomplete' => (int)$field->enable_autocomplete === 1,
		'value' => isset($existingValues[$field->field_code]) ? $existingValues[$field->field_code] : ''
	);
	$result['fields'][] = $fieldData;
}

// Also include type_id for autocomplete
$result['type_id'] = $typeId;

echo json_encode($result);
