<?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 BusbarType
 * Manages busbar type templates (Sammelschienen-Typen)
 */
class BusbarType extends CommonObject
{
	public $element = 'busbartype';
	public $table_element = 'kundenkarte_busbar_type';

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

	// Busbar-spezifische Felder
	public $phases;           // Channel configuration (A, B, AB, ABC, or legacy L1, L2, L3, N, PE, etc.)
	public $num_lines = 1;    // Anzahl der Linien
	public $color;            // Kommagetrennte Farben
	public $default_color;    // Standard-Einzelfarbe
	public $line_height = 3;
	public $line_spacing = 4;
	public $position_default = 'below';

	public $fk_product;
	public $picto;
	public $icon_file;
	public $is_system;
	public $position;
	public $active;

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

	// Loaded objects
	public $system_label;
	public $system_code;
	public $product_ref;
	public $product_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->ref) || empty($this->label) || empty($this->phases)) {
			$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 .= " phases, num_lines, color, default_color, line_height, line_spacing, position_default,";
		$sql .= " fk_product, picto, icon_file, 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 .= ", '".$this->db->escape($this->phases)."'";
		$sql .= ", ".((int) ($this->num_lines > 0 ? $this->num_lines : 1));
		$sql .= ", ".($this->color ? "'".$this->db->escape($this->color)."'" : "NULL");
		$sql .= ", ".($this->default_color ? "'".$this->db->escape($this->default_color)."'" : "NULL");
		$sql .= ", ".((int) ($this->line_height > 0 ? $this->line_height : 3));
		$sql .= ", ".((int) ($this->line_spacing > 0 ? $this->line_spacing : 4));
		$sql .= ", '".$this->db->escape($this->position_default ?: 'below')."'";
		$sql .= ", ".($this->fk_product > 0 ? ((int) $this->fk_product) : "NULL");
		$sql .= ", ".($this->picto ? "'".$this->db->escape($this->picto)."'" : "NULL");
		$sql .= ", ".($this->icon_file ? "'".$this->db->escape($this->icon_file)."'" : "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 .= " p.ref as product_ref, p.label as product_label";
		$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 .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON t.fk_product = p.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->phases = $obj->phases;
				$this->num_lines = $obj->num_lines;
				$this->color = $obj->color;
				$this->default_color = $obj->default_color;
				$this->line_height = $obj->line_height;
				$this->line_spacing = $obj->line_spacing;
				$this->position_default = $obj->position_default ?: 'below';
				$this->fk_product = $obj->fk_product;
				$this->picto = $obj->picto;
				$this->icon_file = $obj->icon_file;
				$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->product_ref = $obj->product_ref;
				$this->product_label = $obj->product_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 .= " 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 .= ", phases = '".$this->db->escape($this->phases)."'";
		$sql .= ", num_lines = ".((int) ($this->num_lines > 0 ? $this->num_lines : 1));
		$sql .= ", color = ".($this->color ? "'".$this->db->escape($this->color)."'" : "NULL");
		$sql .= ", default_color = ".($this->default_color ? "'".$this->db->escape($this->default_color)."'" : "NULL");
		$sql .= ", line_height = ".((int) ($this->line_height > 0 ? $this->line_height : 3));
		$sql .= ", line_spacing = ".((int) ($this->line_spacing > 0 ? $this->line_spacing : 4));
		$sql .= ", position_default = '".$this->db->escape($this->position_default ?: 'below')."'";
		$sql .= ", fk_product = ".($this->fk_product > 0 ? ((int) $this->fk_product) : "NULL");
		$sql .= ", picto = ".($this->picto ? "'".$this->db->escape($this->picto)."'" : "NULL");
		$sql .= ", icon_file = ".($this->icon_file ? "'".$this->db->escape($this->icon_file)."'" : "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 (connections referencing this type)
		$sql = "SELECT COUNT(*) as cnt FROM ".MAIN_DB_PREFIX."kundenkarte_equipment_connection";
		$sql .= " WHERE fk_busbar_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();

		$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 busbar types for a system
	 *
	 * @param int $systemId System ID (0 = all)
	 * @param int $activeOnly Only active types
	 * @return array Array of BusbarType objects
	 */
	public function fetchAllBySystem($systemId = 0, $activeOnly = 1)
	{
		$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 ($systemId > 0) {
			// Show types for this system AND global types (fk_system = 0 or NULL)
			$sql .= " AND (t.fk_system = ".((int) $systemId)." OR t.fk_system = 0 OR t.fk_system IS NULL)";
		}
		if ($activeOnly) {
			$sql .= " AND t.active = 1";
		}
		$sql .= " ORDER BY t.fk_system ASC, t.position ASC, t.label ASC";

		$resql = $this->db->query($sql);
		if ($resql) {
			while ($obj = $this->db->fetch_object($resql)) {
				$type = new BusbarType($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->phases = $obj->phases;
				$type->num_lines = $obj->num_lines;
				$type->color = $obj->color;
				$type->default_color = $obj->default_color;
				$type->line_height = $obj->line_height;
				$type->line_spacing = $obj->line_spacing;
				$type->position_default = $obj->position_default;
				$type->fk_product = $obj->fk_product;
				$type->picto = $obj->picto;
				$type->icon_file = $obj->icon_file;
				$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;
	}

	/**
	 * Get color array from comma-separated string
	 *
	 * @return array Array of color codes
	 */
	public function getColors()
	{
		if (empty($this->color)) {
			return array($this->default_color ?: '#e74c3c');
		}
		return explode(',', $this->color);
	}

	/**
	 * Get phase labels array from phases string
	 *
	 * @return array Array of phase labels
	 */
	public function getPhaseLabels()
	{
		$phases = $this->phases;

		// Parse common phase configurations
		switch (strtoupper($phases)) {
			case 'L1':
				return array('L1');
			case 'L2':
				return array('L2');
			case 'L3':
				return array('L3');
			case 'N':
				return array('N');
			case 'PE':
				return array('PE');
			case 'L1N':
				return array('L1', 'N');
			case '3P':
				return array('L1', 'L2', 'L3');
			case '3P+N':
			case '3PN':
				return array('L1', 'L2', 'L3', 'N');
			case '3P+N+PE':
			case '3PNPE':
				return array('L1', 'L2', 'L3', 'N', 'PE');
			default:
				// Try to split by comma or +
				return preg_split('/[,+]/', $phases);
		}
	}
}
