<?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.
*/

declare(strict_types=1);

class AdminBewerform 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!");
        }

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

        // CSRF Token setzen
        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'];

        // Aktionen prüfen
        if (isset($_GET['delete'])) {
            $this->deleteField((int)$_GET['delete']);
        } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->saveChanges($_POST);
        } else {
            $this->showForm();
        }
    }

    private function showForm(): void
    {
        $felder = $this->dbObj->sqlGet("SELECT * FROM {$this->_prefix}etchat_bewerbung_fields ORDER BY etchat_sort_order ASC");
        $saved  = isset($_GET['saved']);
        $csrfToken = $this->csrfToken;

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

    private function saveChanges(array $post): void
    {
        if (!isset($post['csrf_token']) || $post['csrf_token'] !== $this->csrfToken) {
            die("Ungültiger CSRF Token!");
        }

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

        foreach ($post['label'] as $id => $label) {
            $id = (int)$id;
            $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_bewerbung_fields
                 SET etchat_field_name = :label,
                     etchat_visible = :sichtbar,
                     etchat_required = :pflicht,
                     etchat_options = :optionen
                 WHERE etchat_id = :id",
                [
                    ':label' => $label,
                    ':sichtbar' => $sichtbar,
                    ':pflicht' => $pflicht,
                    ':optionen' => $optionen,
                    ':id' => $id
                ]
            );
        }

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

        if (!empty($post['new_label'])) {
            $label = trim($post['new_label']);
            $type  = $post['new_type'];
            $allowedTypes = ['text','textarea','email','date','select','checkbox'];
            if (!in_array($type, $allowedTypes, true)) $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_bewerbung_fields");
            $sort = ($maxSort[0]['max_sort'] ?? 0) + 1;

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

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

    private function deleteField(int $id): void
    {
        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_bewerbung_fields
             WHERE etchat_id = :id AND etchat_custom = 1",
            [':id' => $id]
        );

        header("Location: ./?AdminBewerform");
        exit;
    }
}