<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * AJAX endpoint for equipment carriers (Hutschienen)
 */

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

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

$action = GETPOST('action', 'aZ09');
$anlageId = GETPOSTINT('anlage_id');
$carrierId = GETPOSTINT('carrier_id');
$panelId = GETPOSTINT('panel_id');

$carrier = new EquipmentCarrier($db);

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

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

switch ($action) {
	case 'get':
		// Get single carrier data
		if ($carrierId > 0 && $carrier->fetch($carrierId) > 0) {
			$response['success'] = true;
			$response['carrier'] = array(
				'id' => $carrier->id,
				'fk_anlage' => $carrier->fk_anlage,
				'fk_panel' => $carrier->fk_panel,
				'label' => $carrier->label,
				'total_te' => $carrier->total_te,
				'position' => $carrier->position,
				'panel_label' => $carrier->panel_label
			);
		} else {
			$response['error'] = 'Carrier not found';
		}
		break;

	case 'list':
		// List all carriers for an Anlage
		if ($anlageId > 0) {
			$carriers = $carrier->fetchByAnlage($anlageId);
			$result = array();
			foreach ($carriers as $c) {
				$c->fetchEquipment();
				$equipment = array();
				foreach ($c->equipment as $eq) {
					$equipment[] = array(
						'id' => $eq->id,
						'type_id' => $eq->fk_equipment_type,
						'type_label' => $eq->type_label,
						'type_label_short' => $eq->type_label_short,
						'type_color' => $eq->type_color,
						'label' => $eq->label,
						'position_te' => $eq->position_te,
						'width_te' => $eq->width_te,
						'block_label' => $eq->getBlockLabel(),
						'block_color' => $eq->getBlockColor(),
						'field_values' => $eq->getFieldValues()
					);
				}
				$result[] = array(
					'id' => $c->id,
					'label' => $c->label,
					'total_te' => $c->total_te,
					'used_te' => $c->getUsedTE(),
					'free_te' => $c->getFreeTE(),
					'position' => $c->position,
					'equipment' => $equipment
				);
			}
			$response['success'] = true;
			$response['carriers'] = $result;
		} else {
			$response['error'] = 'Missing anlage_id';
		}
		break;

	case 'create':
		if (!$user->hasRight('kundenkarte', 'write')) {
			$response['error'] = 'Permission denied';
			break;
		}
		$carrier->fk_anlage = $anlageId;
		$carrier->fk_panel = $panelId > 0 ? $panelId : null;
		$carrier->label = GETPOST('label', 'alphanohtml');
		$carrier->total_te = GETPOSTINT('total_te') ?: 12;

		$result = $carrier->create($user);
		if ($result > 0) {
			$response['success'] = true;
			$response['carrier_id'] = $result;
		} else {
			$response['error'] = $carrier->error;
		}
		break;

	case 'update':
		if (!$user->hasRight('kundenkarte', 'write')) {
			$response['error'] = 'Permission denied';
			break;
		}
		if ($carrier->fetch($carrierId) > 0) {
			$carrier->label = GETPOST('label', 'alphanohtml');
			$carrier->total_te = GETPOSTINT('total_te') ?: $carrier->total_te;
			$carrier->position = GETPOSTINT('position');
			// Allow changing panel (0 or empty = no panel)
			$newPanelId = GETPOSTINT('panel_id');
			$carrier->fk_panel = $newPanelId > 0 ? $newPanelId : null;

			$result = $carrier->update($user);
			if ($result > 0) {
				$response['success'] = true;
			} else {
				$response['error'] = $carrier->error;
			}
		} else {
			$response['error'] = 'Carrier not found';
		}
		break;

	case 'delete':
		if (!$user->hasRight('kundenkarte', 'delete')) {
			$response['error'] = 'Permission denied';
			break;
		}
		if ($carrier->fetch($carrierId) > 0) {
			$result = $carrier->delete($user);
			if ($result > 0) {
				$response['success'] = true;
			} else {
				$response['error'] = $carrier->error;
			}
		} else {
			$response['error'] = 'Carrier not found';
		}
		break;

	case 'duplicate':
		if (!$user->hasRight('kundenkarte', 'write')) {
			$response['error'] = 'Permission denied';
			break;
		}
		if ($carrier->fetch($carrierId) > 0) {
			// Create a copy of the carrier
			$newCarrier = new EquipmentCarrier($db);
			$newCarrier->fk_anlage = $carrier->fk_anlage;
			$newCarrier->fk_panel = $carrier->fk_panel;
			$newCarrier->label = $carrier->label;
			$newCarrier->total_te = $carrier->total_te;
			$newCarrier->note_private = $carrier->note_private;

			$result = $newCarrier->create($user);
			if ($result > 0) {
				$response['success'] = true;
				$response['carrier_id'] = $result;
			} else {
				$response['error'] = $newCarrier->error;
			}
		} else {
			$response['error'] = 'Carrier not found';
		}
		break;

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

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