<?php
/* Copyright (C) 2026 Alles Watt lauft
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 */

/**
 * Class AnlageType
 * Manages element type templates
 */
class AnlageType extends CommonObject
{
	public $element = 'anlagetype';
	public $table_element = 'kundenkarte_anlage_type';

	public $ref;
	public $label;
	public $label_short;
	public $description;
	public $fk_system;

	public $can_have_children;
	public $can_be_nested;
	public $allowed_parent_types;
	public $can_have_equipment;

	public $picto;
	public $color;
	public $is_system;
	public $position;
	public $active;

	public $date_creation;
	public $fk_user_creat;
	public $fk_user_modif;

	// Loaded objects
	public $system;
	public $fields = array();

	/**
	 * Constructor
	 *
	 * @param DoliDB $db Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}

	/**
	 * Create object in database
	 *
	 * @param User $user User that creates
	 * @return int Return integer <0 if KO, Id of created object if OK
	 */
	public function create($user)
	{
		global $conf;

		$error = 0;
		$now = dol_now();

		if (empty($this->ref) || empty($this->label) || empty($this->fk_system)) {
			$this->error = 'ErrorMissingParameters';
			return -1;
		}

		$this->db->begin();

		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
		$sql .= "entity, ref, label, label_short, description, fk_system,";
		$sql .= " can_have_children, can_be_nested, allowed_parent_types, can_have_equipment,";
		$sql .= " picto, color, is_system, position, active,";
		$sql .= " date_creation, fk_user_creat";
		$sql .= ") VALUES (";
		$sql .= "0"; // entity 0 = global
		$sql .= ", '".$this->db->escape($this->ref)."'";
		$sql .= ", '".$this->db->escape($this->label)."'";
		$sql .= ", ".($this->label_short ? "'".$this->db->escape($this->label_short)."'" : "NULL");
		$sql .= ", ".($this->description ? "'".$this->db->escape($this->description)."'" : "NULL");
		$sql .= ", ".((int) $this->fk_system);
		$sql .= ", ".((int) $this->can_have_children);
		$sql .= ", ".((int) $this->can_be_nested);
		$sql .= ", ".($this->allowed_parent_types ? "'".$this->db->escape($this->allowed_parent_types)."'" : "NULL");
		$sql .= ", ".((int) $this->can_have_equipment);
		$sql .= ", ".($this->picto ? "'".$this->db->escape($this->picto)."'" : "NULL");
		$sql .= ", ".($this->color ? "'".$this->db->escape($this->color)."'" : "NULL");
		$sql .= ", 0"; // is_system = 0 for user-created
		$sql .= ", ".((int) $this->position);
		$sql .= ", ".((int) ($this->active !== null ? $this->active : 1));
		$sql .= ", '".$this->db->idate($now)."'";
		$sql .= ", ".((int) $user->id);
		$sql .= ")";

		$resql = $this->db->query($sql);
		if (!$resql) {
			$error++;
			$this->errors[] = "Error ".$this->db->lasterror();
		}

		if (!$error) {
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
		}

		if ($error) {
			$this->db->rollback();
			return -1 * $error;
		} else {
			$this->db->commit();
			return $this->id;
		}
	}

	/**
	 * Load object from database
	 *
	 * @param int $id ID of record
	 * @return int Return integer <0 if KO, 0 if not found, >0 if OK
	 */
	public function fetch($id)
	{
		$sql = "SELECT t.*, s.label as system_label, s.code as system_code";
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_kundenkarte_anlage_system as s ON t.fk_system = s.rowid";
		$sql .= " WHERE t.rowid = ".((int) $id);

		$resql = $this->db->query($sql);
		if ($resql) {
			if ($this->db->num_rows($resql)) {
				$obj = $this->db->fetch_object($resql);

				$this->id = $obj->rowid;
				$this->entity = $obj->entity;
				$this->ref = $obj->ref;
				$this->label = $obj->label;
				$this->label_short = $obj->label_short;
				$this->description = $obj->description;
				$this->fk_system = $obj->fk_system;
				$this->can_have_children = $obj->can_have_children;
				$this->can_be_nested = $obj->can_be_nested;
				$this->allowed_parent_types = $obj->allowed_parent_types;
				$this->can_have_equipment = $obj->can_have_equipment ?? 0;
				$this->picto = $obj->picto;
				$this->color = $obj->color;
				$this->is_system = $obj->is_system;
				$this->position = $obj->position;
				$this->active = $obj->active;
				$this->date_creation = $this->db->jdate($obj->date_creation);
				$this->fk_user_creat = $obj->fk_user_creat;
				$this->fk_user_modif = $obj->fk_user_modif;

				$this->system_label = $obj->system_label;
				$this->system_code = $obj->system_code;

				$this->db->free($resql);
				return 1;
			} else {
				$this->db->free($resql);
				return 0;
			}
		} else {
			$this->error = $this->db->lasterror();
			return -1;
		}
	}

	/**
	 * Update object in database
	 *
	 * @param User $user User that modifies
	 * @return int Return integer <0 if KO, >0 if OK
	 */
	public function update($user)
	{
		$error = 0;

		$this->db->begin();

		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
		$sql .= " ref = '".$this->db->escape($this->ref)."'";
		$sql .= ", label = '".$this->db->escape($this->label)."'";
		$sql .= ", label_short = ".($this->label_short ? "'".$this->db->escape($this->label_short)."'" : "NULL");
		$sql .= ", description = ".($this->description ? "'".$this->db->escape($this->description)."'" : "NULL");
		$sql .= ", fk_system = ".((int) $this->fk_system);
		$sql .= ", can_have_children = ".((int) $this->can_have_children);
		$sql .= ", can_be_nested = ".((int) $this->can_be_nested);
		$sql .= ", allowed_parent_types = ".($this->allowed_parent_types ? "'".$this->db->escape($this->allowed_parent_types)."'" : "NULL");
		$sql .= ", can_have_equipment = ".((int) $this->can_have_equipment);
		$sql .= ", picto = ".($this->picto ? "'".$this->db->escape($this->picto)."'" : "NULL");
		$sql .= ", color = ".($this->color ? "'".$this->db->escape($this->color)."'" : "NULL");
		$sql .= ", position = ".((int) $this->position);
		$sql .= ", active = ".((int) $this->active);
		$sql .= ", fk_user_modif = ".((int) $user->id);
		$sql .= " WHERE rowid = ".((int) $this->id);

		$resql = $this->db->query($sql);
		if (!$resql) {
			$error++;
			$this->errors[] = "Error ".$this->db->lasterror();
		}

		if ($error) {
			$this->db->rollback();
			return -1 * $error;
		} else {
			$this->db->commit();
			return 1;
		}
	}

	/**
	 * Delete object in database
	 *
	 * @param User $user User that deletes
	 * @return int Return integer <0 if KO, >0 if OK
	 */
	public function delete($user)
	{
		global $conf;

		// Check if type is in use
		$sql = "SELECT COUNT(*) as cnt FROM ".MAIN_DB_PREFIX."kundenkarte_anlage";
		$sql .= " WHERE fk_anlage_type = ".((int) $this->id);
		$resql = $this->db->query($sql);
		if ($resql) {
			$obj = $this->db->fetch_object($resql);
			if ($obj->cnt > 0) {
				$this->error = 'ErrorTypeInUse';
				return -1;
			}
		}

		// Cannot delete system types
		if ($this->is_system) {
			$this->error = 'ErrorCannotDeleteSystemType';
			return -2;
		}

		$error = 0;
		$this->db->begin();

		// Delete fields first
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field WHERE fk_anlage_type = ".((int) $this->id);
		$this->db->query($sql);

		// Delete type
		$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
		$resql = $this->db->query($sql);
		if (!$resql) {
			$error++;
			$this->errors[] = "Error ".$this->db->lasterror();
		}

		if ($error) {
			$this->db->rollback();
			return -1 * $error;
		} else {
			$this->db->commit();
			return 1;
		}
	}

	/**
	 * Fetch all types for a system
	 *
	 * @param int $systemId System ID (0 = all)
	 * @param int $activeOnly Only active types
	 * @param int $excludeGlobal 1 = GLOBAL-Typen ausschliessen (fuer Admin-Ansicht)
	 * @return array Array of AnlageType objects
	 */
	public function fetchAllBySystem($systemId = 0, $activeOnly = 1, $excludeGlobal = 0)
	{
		$results = array();

		$sql = "SELECT t.*, s.label as system_label, s.code as system_code";
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_kundenkarte_anlage_system as s ON t.fk_system = s.rowid";
		$sql .= " WHERE 1 = 1";
		if ($excludeGlobal) {
			// GLOBAL-Typen (Gebaeude) ausschliessen (Admin-Ansicht)
			$sql .= " AND (s.code IS NULL OR s.code != 'GLOBAL')";
		}
		if ($systemId > 0) {
			if (!$excludeGlobal) {
				// Typen dieses Systems UND GLOBAL-Typen (fuer Tabs-Ansicht)
				$sql .= " AND (t.fk_system = ".((int) $systemId)." OR s.code = 'GLOBAL')";
			} else {
				// Nur Typen dieses Systems (fuer Admin-Ansicht)
				$sql .= " AND t.fk_system = ".((int) $systemId);
			}
		}
		if ($activeOnly) {
			$sql .= " AND t.active = 1";
		}
		// Sort: GLOBAL types first (position 0), then by position, then by label
		$sql .= " ORDER BY s.position ASC, t.position ASC, t.label ASC";

		$resql = $this->db->query($sql);
		if ($resql) {
			while ($obj = $this->db->fetch_object($resql)) {
				$type = new AnlageType($this->db);
				$type->id = $obj->rowid;
				$type->ref = $obj->ref;
				$type->label = $obj->label;
				$type->label_short = $obj->label_short;
				$type->fk_system = $obj->fk_system;
				$type->can_have_children = $obj->can_have_children;
				$type->can_be_nested = $obj->can_be_nested;
				$type->allowed_parent_types = $obj->allowed_parent_types;
				$type->can_have_equipment = $obj->can_have_equipment ?? 0;
				$type->picto = $obj->picto;
				$type->is_system = $obj->is_system;
				$type->position = $obj->position;
				$type->active = $obj->active;
				$type->system_label = $obj->system_label;
				$type->system_code = $obj->system_code;

				$results[] = $type;
			}
			$this->db->free($resql);
		}

		return $results;
	}

	/**
	 * Fetch fields for this type
	 *
	 * @param int $activeOnly Only active fields
	 * @return array Array of field objects
	 */
	public function fetchFields($activeOnly = 1)
	{
		$results = array();

		$sql = "SELECT * FROM ".MAIN_DB_PREFIX."kundenkarte_anlage_type_field";
		$sql .= " WHERE fk_anlage_type = ".((int) $this->id);
		if ($activeOnly) {
			$sql .= " AND active = 1";
		}
		$sql .= " ORDER BY position ASC";

		$resql = $this->db->query($sql);
		if ($resql) {
			while ($obj = $this->db->fetch_object($resql)) {
				$results[] = $obj;
			}
			$this->db->free($resql);
		}

		$this->fields = $results;
		return $results;
	}

	/**
	 * Get allowed parent types as array
	 *
	 * @return array
	 */
	public function getAllowedParentTypesArray()
	{
		if (empty($this->allowed_parent_types)) {
			return array();
		}
		return array_map('trim', explode(',', $this->allowed_parent_types));
	}

	/**
	 * Check if this type can be child of another type
	 *
	 * @param string $parentTypeRef Parent type reference
	 * @return bool
	 */
	public function canBeChildOf($parentTypeRef)
	{
		if (empty($this->allowed_parent_types)) {
			return true; // No restriction = can be anywhere
		}
		$allowed = $this->getAllowedParentTypesArray();
		return in_array($parentTypeRef, $allowed);
	}
}
