<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX endpoint for tree display configuration
 */

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");

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

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

$action = GETPOST('action', 'aZ09');
$systemId = GETPOSTINT('system_id');

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

// Security check
if (!$user->hasRight('kundenkarte', 'read')) {
	$response['error'] = $langs->trans('ErrorPermissionDenied');
	echo json_encode($response);
	exit;
}

switch ($action) {
	case 'get':
		// Get tree config for a system
		$defaultConfig = array(
			'show_ref' => true,
			'show_label' => true,
			'show_type' => true,
			'show_icon' => true,
			'show_status' => true,
			'show_fields' => false,
			'expand_default' => true,
			'indent_style' => 'lines'
		);

		if ($systemId > 0) {
			$sql = "SELECT tree_display_config FROM ".MAIN_DB_PREFIX."c_kundenkarte_anlage_system WHERE rowid = ".(int)$systemId;
			$resql = $db->query($sql);
			if ($resql && $obj = $db->fetch_object($resql)) {
				if (!empty($obj->tree_display_config)) {
					$savedConfig = json_decode($obj->tree_display_config, true);
					if (is_array($savedConfig)) {
						$defaultConfig = array_merge($defaultConfig, $savedConfig);
					}
				}
			}
		}

		$response['success'] = true;
		$response['config'] = $defaultConfig;
		break;

	case 'list':
		// Get all system configs
		$sql = "SELECT rowid, code, label, tree_display_config FROM ".MAIN_DB_PREFIX."c_kundenkarte_anlage_system WHERE active = 1 ORDER BY position";
		$resql = $db->query($sql);

		$configs = array();
		if ($resql) {
			while ($obj = $db->fetch_object($resql)) {
				$config = array(
					'show_ref' => true,
					'show_label' => true,
					'show_type' => true,
					'show_icon' => true,
					'show_status' => true,
					'show_fields' => false,
					'expand_default' => true,
					'indent_style' => 'lines'
				);

				if (!empty($obj->tree_display_config)) {
					$savedConfig = json_decode($obj->tree_display_config, true);
					if (is_array($savedConfig)) {
						$config = array_merge($config, $savedConfig);
					}
				}

				$configs[$obj->rowid] = array(
					'id' => $obj->rowid,
					'code' => $obj->code,
					'label' => $obj->label,
					'config' => $config
				);
			}
		}

		$response['success'] = true;
		$response['systems'] = $configs;
		break;

	default:
		$response['error'] = 'Unknown action';
}

echo json_encode($response);
