<?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 TerminalBridge
 * Manages bridges between terminal blocks (Brücken zwischen Reihenklemmen)
 */
class TerminalBridge extends CommonObject
{
	public $element = 'terminalbridge';
	public $table_element = 'kundenkarte_terminal_bridge';

	public $fk_anlage;
	public $fk_carrier;
	public $start_te;
	public $end_te;
	public $terminal_side = 'top';
	public $terminal_row = 0;
	public $color = '#e74c3c';
	public $bridge_type = 'standard';
	public $label;
	public $status = 1;
	public $date_creation;
	public $fk_user_creat;
	public $fk_user_modif;

	/**
	 * 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) || empty($this->fk_carrier) || empty($this->start_te) || empty($this->end_te)) {
			$this->error = 'ErrorMissingParameters';
			return -1;
		}

		$this->db->begin();

		$sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
		$sql .= "entity, fk_anlage, fk_carrier, start_te, end_te,";
		$sql .= " terminal_side, terminal_row, color, bridge_type, label,";
		$sql .= " status, date_creation, fk_user_creat";
		$sql .= ") VALUES (";
		$sql .= ((int) ($conf->entity));
		$sql .= ", ".((int) $this->fk_anlage);
		$sql .= ", ".((int) $this->fk_carrier);
		$sql .= ", ".((int) $this->start_te);
		$sql .= ", ".((int) $this->end_te);
		$sql .= ", '".$this->db->escape($this->terminal_side ?: 'top')."'";
		$sql .= ", ".((int) $this->terminal_row);
		$sql .= ", '".$this->db->escape($this->color ?: '#e74c3c')."'";
		$sql .= ", '".$this->db->escape($this->bridge_type ?: 'standard')."'";
		$sql .= ", ".($this->label ? "'".$this->db->escape($this->label)."'" : "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 * FROM ".MAIN_DB_PREFIX.$this->table_element;
		$sql .= " WHERE 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->fk_carrier = $obj->fk_carrier;
				$this->start_te = $obj->start_te;
				$this->end_te = $obj->end_te;
				$this->terminal_side = $obj->terminal_side;
				$this->terminal_row = $obj->terminal_row;
				$this->color = $obj->color;
				$this->bridge_type = $obj->bridge_type;
				$this->label = $obj->label;
				$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->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 .= " fk_anlage = ".((int) $this->fk_anlage);
		$sql .= ", fk_carrier = ".((int) $this->fk_carrier);
		$sql .= ", start_te = ".((int) $this->start_te);
		$sql .= ", end_te = ".((int) $this->end_te);
		$sql .= ", terminal_side = '".$this->db->escape($this->terminal_side ?: 'top')."'";
		$sql .= ", terminal_row = ".((int) $this->terminal_row);
		$sql .= ", color = '".$this->db->escape($this->color ?: '#e74c3c')."'";
		$sql .= ", bridge_type = '".$this->db->escape($this->bridge_type ?: 'standard')."'";
		$sql .= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'" : "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();

		$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 bridges for an installation
	 *
	 * @param int $anlageId Installation ID
	 * @param int $carrierId Optional carrier ID filter
	 * @return array Array of TerminalBridge objects
	 */
	public function fetchAllByAnlage($anlageId, $carrierId = 0)
	{
		$results = array();

		$sql = "SELECT * FROM ".MAIN_DB_PREFIX.$this->table_element;
		$sql .= " WHERE fk_anlage = ".((int) $anlageId);
		$sql .= " AND status = 1";
		if ($carrierId > 0) {
			$sql .= " AND fk_carrier = ".((int) $carrierId);
		}
		$sql .= " ORDER BY fk_carrier ASC, terminal_side ASC, start_te ASC";

		$resql = $this->db->query($sql);
		if ($resql) {
			while ($obj = $this->db->fetch_object($resql)) {
				$bridge = new TerminalBridge($this->db);
				$bridge->id = $obj->rowid;
				$bridge->entity = $obj->entity;
				$bridge->fk_anlage = $obj->fk_anlage;
				$bridge->fk_carrier = $obj->fk_carrier;
				$bridge->start_te = $obj->start_te;
				$bridge->end_te = $obj->end_te;
				$bridge->terminal_side = $obj->terminal_side;
				$bridge->terminal_row = $obj->terminal_row;
				$bridge->color = $obj->color;
				$bridge->bridge_type = $obj->bridge_type;
				$bridge->label = $obj->label;
				$bridge->status = $obj->status;

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

		return $results;
	}
}
