<?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 EquipmentPanel
 * Manages equipment panels (Schaltschrankfelder)
 * Physical sections in distribution boards containing carriers
 */
class EquipmentPanel extends CommonObject
{
	public $element = 'equipmentpanel';
	public $table_element = 'kundenkarte_equipment_panel';

	public $fk_anlage;
	public $label;
	public $position;
	public $note_private;
	public $status;

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

	// Loaded objects
	public $carriers = array();
	public $anlage_label;

	/**
	 * 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->fk_anlage)) {
			$this->error = 'ErrorMissingParameters';
			return -1;
		}

		// Get next position
		if (empty($this->position)) {
			$sql = "SELECT MAX(position) as maxpos FROM ".MAIN_DB_PREFIX.$this->table_element;
			$sql .= " WHERE fk_anlage = ".((int) $this->fk_anlage);
			$resql = $this->db->query($sql);
			if ($resql) {
				$obj = $this->db->fetch_object($resql);
				$this->position = ($obj->maxpos !== null) ? $obj->maxpos + 1 : 0;
			}
		}

		// Default label if not set
		if (empty($this->label)) {
			$this->label = 'Feld '.($this->position + 1);
		}

		$this->db->begin();

		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
		$sql .= "entity, fk_anlage, label, position, note_private, status,";
		$sql .= " date_creation, fk_user_creat";
		$sql .= ") VALUES (";
		$sql .= ((int) $conf->entity);
		$sql .= ", ".((int) $this->fk_anlage);
		$sql .= ", '".$this->db->escape($this->label)."'";
		$sql .= ", ".((int) $this->position);
		$sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "NULL");
		$sql .= ", ".((int) ($this->status !== null ? $this->status : 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 p.*, a.label as anlage_label";
		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as p";
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."kundenkarte_anlage as a ON p.fk_anlage = a.rowid";
		$sql .= " WHERE p.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->fk_anlage = $obj->fk_anlage;
				$this->label = $obj->label;
				$this->position = $obj->position;
				$this->note_private = $obj->note_private;
				$this->status = $obj->status;
				$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->anlage_label = $obj->anlage_label;

				$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 .= " label = '".$this->db->escape($this->label)."'";
		$sql .= ", position = ".((int) $this->position);
		$sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "NULL");
		$sql .= ", status = ".((int) $this->status);
		$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)
	{
		$error = 0;
		$this->db->begin();

		// Carriers are deleted via CASCADE or need to be reassigned

		$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 panels for an Anlage
	 *
	 * @param int $anlageId Anlage ID
	 * @param int $activeOnly Only active panels
	 * @return array Array of EquipmentPanel objects
	 */
	public function fetchByAnlage($anlageId, $activeOnly = 1)
	{
		$results = array();

		$sql = "SELECT * FROM ".MAIN_DB_PREFIX.$this->table_element;
		$sql .= " WHERE fk_anlage = ".((int) $anlageId);
		if ($activeOnly) {
			$sql .= " AND status = 1";
		}
		$sql .= " ORDER BY position ASC";

		$resql = $this->db->query($sql);
		if ($resql) {
			while ($obj = $this->db->fetch_object($resql)) {
				$panel = new EquipmentPanel($this->db);
				$panel->id = $obj->rowid;
				$panel->entity = $obj->entity;
				$panel->fk_anlage = $obj->fk_anlage;
				$panel->label = $obj->label;
				$panel->position = $obj->position;
				$panel->note_private = $obj->note_private;
				$panel->status = $obj->status;

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

		return $results;
	}

	/**
	 * Fetch all carriers in this panel
	 *
	 * @return array Array of EquipmentCarrier objects
	 */
	public function fetchCarriers()
	{
		require_once DOL_DOCUMENT_ROOT.'/custom/kundenkarte/class/equipmentcarrier.class.php';

		$carrier = new EquipmentCarrier($this->db);
		$this->carriers = $carrier->fetchByPanel($this->id);

		return $this->carriers;
	}

	/**
	 * Get total carriers count
	 *
	 * @return int Number of carriers
	 */
	public function getCarrierCount()
	{
		if (empty($this->carriers)) {
			$this->fetchCarriers();
		}
		return count($this->carriers);
	}
}
