<?php

/*
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.) 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
*/

class ConnectDB extends EtChatConfig
{
    protected ?PDO $_connid = null;

    public $lastId = 0;

    public function __construct()
    {
        parent::__construct();

        try {

            $dsn = "{$this->_usedDatabase}:host={$this->_sqlhost};dbname={$this->_database};charset=utf8mb4";

            $this->_connid = new PDO(
                $dsn,
                $this->_sqluser,
                $this->_sqlpass,
                [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_BOTH,
                    PDO::ATTR_EMULATE_PREPARES   => false
                ]
            );

        } catch (PDOException $e) {

            echo "Datenbankverbindung fehlgeschlagen.";
            exit;
        }
    }

    public function escape($value)
    {
        return substr($this->_connid->quote($value), 1, -1);
    }

    public function sqlGet(string $sql, array $params = [])
		{
			if ($sql === '') {
				return false;
			}

			try {

				if (!empty($params)) {
					$stmt = $this->_connid->prepare($sql);
					$stmt->execute($params);
				} else {
					$stmt = $this->_connid->query($sql);
				}

				if (!$stmt) {
					return false;
				}

				$result = $stmt->fetchAll(PDO::FETCH_BOTH);

				if (empty($result)) {
					return false;   // WICHTIG für alten ET-Chat Code
				}

				return $result;

			} catch (PDOException $e) {
				return false;
			}
		}

    public function sqlSet(string $sql, $params = [])
	{
		try {

			// Alte ET-Chat Aufrufe kompatibel halten
			if (!is_array($params)) {
				$params = [];
			}

			if (!empty($params)) {

				$stmt = $this->_connid->prepare($sql);
				$stmt->execute($params);

				$this->lastId = $this->_connid->lastInsertId();
				return true;
			}

			$affected = $this->_connid->exec($sql);

			$this->lastId = $this->_connid->lastInsertId();

			return $affected;

		} catch (PDOException $e) {

			return false;
		}
	}
	
	public function getConnection(): ?PDO
	{
		return $this->_connid;
	}

    public function close()
    {
        $this->_connid = null;
    }
}