<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX handler for tooltip data
 */

if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '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 && file_exists("../../../../main.inc.php")) $res = @include "../../../../main.inc.php";
if (!$res) die("Include of main fails");

dol_include_once('/kundenkarte/class/anlage.class.php');
dol_include_once('/kundenkarte/class/anlagetype.class.php');
dol_include_once('/kundenkarte/class/anlagefile.class.php');

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

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

$id = GETPOSTINT('id');

if (!$user->hasRight('kundenkarte', 'read')) {
	echo json_encode(array('success' => false, 'error' => 'Access denied'));
	exit;
}

if ($id <= 0) {
	echo json_encode(array('success' => false, 'error' => 'Invalid ID'));
	exit;
}

$anlage = new Anlage($db);
$result = $anlage->fetch($id);

if ($result <= 0) {
	echo json_encode(array('success' => false, 'error' => 'Element not found'));
	exit;
}

// Get type and fields
$type = new AnlageType($db);
$type->fetch($anlage->fk_anlage_type);
$typeFields = $type->fetchFields();

// Get field values
$fieldValues = $anlage->getFieldValues();
$fieldsData = array();

foreach ($typeFields as $field) {
	if ($field->show_in_hover) {
		// Handle header fields
		if ($field->field_type === 'header') {
			$fieldsData[$field->field_code] = array(
				'label' => $field->field_label,
				'value' => '',
				'type' => 'header'
			);
			continue;
		}

		$value = isset($fieldValues[$field->field_code]) ? $fieldValues[$field->field_code] : '';

		// Format date values
		$displayValue = $value;
		if ($field->field_type === 'date' && $value) {
			$displayValue = dol_print_date(strtotime($value), 'day');
		}

		$fieldsData[$field->field_code] = array(
			'label' => $field->field_label,
			'value' => $displayValue,
			'type' => $field->field_type
		);
	}
}

// Get images
$anlagefile = new AnlageFile($db);
$files = $anlagefile->fetchAllByAnlage($id, 'image');

$images = array();
foreach ($files as $file) {
	$images[] = array(
		'id' => $file->id,
		'filename' => $file->filename,
		'url' => $file->getUrl(),
		'thumb_url' => $file->getThumbUrl() ?: $file->getUrl()
	);
}

$data = array(
	'id' => $anlage->id,
	'label' => $anlage->label,
	'type_label' => $anlage->type_label,
	'picto' => $anlage->type_picto,
	'note_html' => $anlage->note_private ? nl2br(htmlspecialchars($anlage->note_private, ENT_QUOTES, 'UTF-8')) : '',
	'fields' => $fieldsData,
	'images' => $images
);

echo json_encode(array('success' => true, 'data' => $data));
