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

if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1');
if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1');
if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1');

$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.'/custom/kundenkarte/class/equipmenttype.class.php';
require_once DOL_DOCUMENT_ROOT.'/custom/kundenkarte/class/equipment.class.php';

header('Content-Type: application/json; charset=UTF-8');

$typeId = GETPOSTINT('type_id');
$equipmentId = GETPOSTINT('equipment_id');

$response = array('success' => false, 'fields' => array());

if (!$user->hasRight('kundenkarte', 'read')) {
	$response['error'] = 'Permission denied';
	echo json_encode($response);
	exit;
}

if ($typeId > 0) {
	$type = new EquipmentType($db);
	if ($type->fetch($typeId) > 0) {
		$fields = $type->fetchFields(1);

		// Get existing values if editing
		$existingValues = array();
		if ($equipmentId > 0) {
			$equipment = new Equipment($db);
			if ($equipment->fetch($equipmentId) > 0) {
				$existingValues = $equipment->getFieldValues();
			}
		}

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

		$response['success'] = true;
		$response['fields'] = $result;
		$response['type'] = array(
			'id' => $type->id,
			'label' => $type->label,
			'label_short' => $type->label_short,
			'width_te' => $type->width_te,
			'color' => $type->color
		);
	}
}

echo json_encode($response);
$db->close();
