<?php
declare(strict_types=1);

/*
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 AdminKontaktform extends DbConectionMaker
{
    private string $csrfToken = '';

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

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Content-Type: text/html; charset=utf-8');

        if (!isset($this->dbObj)) {
            die("Datenbankverbindung nicht vorhanden!");
        }

        // Rollencheck
        $userRole = $_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '';
        if ($userRole !== 'admin') {
            header("Location: ./");
            exit;
        }

        // CSRF
        if (empty($_SESSION['etchat_'.$this->_prefix.'csrf_token'])) {
            $_SESSION['etchat_'.$this->_prefix.'csrf_token'] = bin2hex(random_bytes(16));
        }
        $this->csrfToken = $_SESSION['etchat_'.$this->_prefix.'csrf_token'];

        $req = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

        if (isset($req['delete'])) {
            $this->deleteField((int)$req['delete'], $req['csrf_token'] ?? '');
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->saveChanges($req);
        } else {
            $this->showForm(isset($req['saved']));
        }
    }

    private function showForm(bool $saved): void
    {
        $felder = $this->dbObj->sqlGet(
            "SELECT * FROM {$this->_prefix}etchat_kontakt_fields ORDER BY etchat_sort_order ASC"
        );

        $csrfToken = $this->csrfToken;

        include "styles/admin_tpl/editKontaktform.tpl.html";
    }

    private function saveChanges(array $post): void
    {
        $requestToken = $post['csrf_token'] ?? '';
        if (!$requestToken || !hash_equals($this->csrfToken, $requestToken)) {
            die("Ungültiger Request (CSRF erkannt)");
        }

        $order = isset($post['order']) ? explode(',', $post['order']) : [];

        foreach ($post['label'] ?? [] as $id => $label) {
            $label = trim((string)$label);

            $sichtbar = isset($post['sichtbar'][$id]) ? 1 : 0;
            $pflicht  = isset($post['pflicht'][$id]) ? 1 : 0;

            $optionen = null;
            if (isset($post['optionen'][$id])) {
                $lines = array_filter(array_map('trim', explode("\n", $post['optionen'][$id])));
                if ($lines) {
                    $optionen = json_encode(array_values($lines), JSON_UNESCAPED_UNICODE);
                }
            }

            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_kontakt_fields
                 SET etchat_field_name=?, etchat_visible=?, etchat_required=?, etchat_options=?
                 WHERE etchat_id=?",
                [$label, $sichtbar, $pflicht, $optionen, (int)$id]
            );
        }

        foreach ($order as $sort => $id) {
            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_kontakt_fields
                 SET etchat_sort_order=? WHERE etchat_id=?",
                [(int)$sort, (int)$id]
            );
        }

        // Neues Feld
        if (!empty($post['new_label'])) {
            $label = trim((string)$post['new_label']);
            $label = preg_replace('/[^a-zA-Z0-9 äöüÄÖÜß_\-]/u', '', $label);

            $allowedTypes = ['text','textarea','email','date','select','checkbox'];
            $type = in_array($post['new_type'] ?? '', $allowedTypes, true)
                ? $post['new_type']
                : 'text';

            $sichtbar = isset($post['new_visible']) ? 1 : 0;
            $pflicht  = isset($post['new_required']) ? 1 : 0;

            $optionen = null;
            if (!empty($post['new_options'])) {
                $lines = array_filter(array_map('trim', explode("\n", $post['new_options'])));
                if ($lines) {
                    $optionen = json_encode(array_values($lines), JSON_UNESCAPED_UNICODE);
                }
            }

            $maxSort = $this->dbObj->sqlGet(
                "SELECT MAX(etchat_sort_order) AS max_sort FROM {$this->_prefix}etchat_kontakt_fields"
            );

            $sort = ((int)($maxSort[0]['max_sort'] ?? 0)) + 1;

            $this->dbObj->sqlSet(
                "INSERT INTO {$this->_prefix}etchat_kontakt_fields
                 (etchat_field_name, etchat_field_type, etchat_visible, etchat_required, etchat_options, etchat_sort_order, etchat_custom)
                 VALUES (?, ?, ?, ?, ?, ?, 1)",
                [$label, $type, $sichtbar, $pflicht, $optionen, $sort]
            );
        }

        header("Location: ./?AdminKontaktform&saved=1");
        exit;
    }

    private function deleteField(int $id, string $requestToken): void
    {
        if (!$requestToken || !hash_equals($this->csrfToken, $requestToken)) {
            die("Ungültiger Request (CSRF erkannt)");
        }

        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_kontakt_fields 
             WHERE etchat_id=? AND etchat_custom=1",
            [$id]
        );

        header("Location: ./?AdminKontaktform&saved=1");
        exit;
    }
}