<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX endpoint for Anlage operations
 */

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

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

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

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

$action = GETPOST('action', 'aZ09');
$socId = GETPOSTINT('socid');
$contactId = GETPOSTINT('contactid');
$systemId = GETPOSTINT('system_id');
$anlageId = GETPOSTINT('anlage_id');

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

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

$anlage = new Anlage($db);

// Helper function to convert tree objects to clean arrays
function treeToArray($nodes) {
	$result = array();
	foreach ($nodes as $node) {
		$item = array(
			'id' => $node->id,
			'ref' => $node->ref,
			'label' => $node->label,
			'fk_parent' => $node->fk_parent,
			'fk_system' => $node->fk_system,
			'type_label' => $node->type_label,
			'status' => $node->status
		);
		if (!empty($node->children)) {
			$item['children'] = treeToArray($node->children);
		} else {
			$item['children'] = array();
		}
		$result[] = $item;
	}
	return $result;
}

switch ($action) {
	case 'tree':
		// Get tree structure for a customer/system
		if ($socId > 0) {
			if ($contactId > 0) {
				$tree = $anlage->fetchTreeByContact($socId, $contactId, $systemId);
			} else {
				$tree = $anlage->fetchTree($socId, $systemId);
			}

			// Convert to clean array (removes db connection and other internal data)
			$response['success'] = true;
			$response['tree'] = treeToArray($tree);
		} else {
			$response['error'] = 'Missing socid';
		}
		break;

	case 'list':
		// Get flat list of anlagen for a customer/system (derived from tree)
		if ($socId > 0) {
			$tree = $anlage->fetchTree($socId, $systemId);

			// Flatten tree to list
			$result = array();
			$flattenTree = function($nodes, $prefix = '') use (&$flattenTree, &$result) {
				foreach ($nodes as $node) {
					$result[] = array(
						'id' => $node->id,
						'ref' => $node->ref,
						'label' => $node->label,
						'display_label' => $prefix . $node->label,
						'fk_parent' => $node->fk_parent,
						'type_label' => $node->type_label,
						'status' => $node->status
					);
					if (!empty($node->children)) {
						$flattenTree($node->children, $prefix . '  ');
					}
				}
			};
			$flattenTree($tree);

			$response['success'] = true;
			$response['anlagen'] = $result;
		} else {
			$response['error'] = 'Missing socid';
		}
		break;

	case 'get':
		// Get single anlage
		if ($anlageId > 0 && $anlage->fetch($anlageId) > 0) {
			$response['success'] = true;
			$response['anlage'] = array(
				'id' => $anlage->id,
				'ref' => $anlage->ref,
				'label' => $anlage->label,
				'fk_parent' => $anlage->fk_parent,
				'fk_anlage_type' => $anlage->fk_anlage_type,
				'type_label' => $anlage->type_label,
				'fk_system' => $anlage->fk_system,
				'status' => $anlage->status,
				'field_values' => $anlage->getFieldValues()
			);
		} else {
			$response['error'] = $langs->trans('ErrorRecordNotFound');
		}
		break;

	case 'reorder':
		// Reihenfolge der Elemente aktualisieren
		if (!$user->hasRight('kundenkarte', 'write')) {
			$response['error'] = $langs->trans('ErrorPermissionDenied');
			break;
		}

		$idsRaw = GETPOST('ids', 'array');
		if (!empty($idsRaw) && is_array($idsRaw)) {
			$ids = array_map('intval', $idsRaw);
			$result = $anlage->updateRangs($ids);
			if ($result > 0) {
				$response['success'] = true;
			} else {
				$response['error'] = 'Fehler beim Speichern der Reihenfolge';
			}
		} else {
			$response['error'] = 'Keine IDs übergeben';
		}
		break;

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

echo json_encode($response);
