<?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.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

class AdminBewer extends DbConectionMaker
{
    private array $bewerbungen = [];
    private string $filter = '';
    private int $perPage = 10;
    private string $csrfToken = '';

    private array $statusLabels = [
        'neu' => 'Neu',
        'in Bearbeitung' => 'In Bearbeitung',
        'angenommen' => 'Angenommen',
        'abgelehnt' => 'Abgelehnt',
        'gegangen' => 'Gegangen'
    ];

    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');

        $allowedRoles = ['admin','co_admin','chatwache'];
        $userRole = $_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '';

        if (!in_array($userRole, $allowedRoles, true)) {
            header('Location: ./');
            exit;
        }

        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'];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $token = $_POST['csrf_token'] ?? '';
            if (!$token || !hash_equals($this->csrfToken, $token)) {
                http_response_code(403);
                exit('Ungültiger CSRF Token');
            }

            if (isset($_POST['save_bewerbung'])) {
                $this->saveStatus($_POST);
            } elseif (!empty($_POST['delete_bewerbung'])) {
                $this->deleteBewerbung($_POST);
            }
        } else {
            $this->showList($userRole);
        }
    }

    private function showList(string $userRole): void
    {
        $this->filter = $_GET['status_filter'] ?? '';
        $search = trim((string)($_GET['search'] ?? ''));
        $saved = isset($_GET['saved']);

        $page = max(1, (int)($_GET['page'] ?? 1));
        $offset = ($page - 1) * $this->perPage;

        $where = [];
        $params = [];

        if ($this->filter !== '') {
            $where[] = "status = ?";
            $params[] = $this->filter;
        }

        if ($search !== '') {
            $where[] = "bewerber_daten LIKE ?";
            $search = str_replace(['%','_'], ['\\%','\\_'], $search);
            $params[] = '%' . $search . '%';
        }

        $whereSql = $where ? 'WHERE '.implode(' AND ', $where) : '';

        $sql = "SELECT * FROM {$this->_prefix}etchat_bewerbungen
                $whereSql
                ORDER BY erstellt_am DESC
                LIMIT {$this->perPage} OFFSET {$offset}";

        $this->bewerbungen = $this->dbObj->sqlGet($sql, $params) ?: [];

        $countSql = "SELECT COUNT(*) as cnt FROM {$this->_prefix}etchat_bewerbungen $whereSql";
        $totalAll = (int)($this->dbObj->sqlGet($countSql, $params)[0]['cnt'] ?? 0);
        $totalPages = max(1, (int)ceil($totalAll / $this->perPage));

        $this->renderTemplate($userRole, $page, $totalPages, $totalAll, $saved, $search);
    }

    private function renderTemplate(
        string $userRole,
        int $currentPage,
        int $totalPages,
        int $totalAll,
        bool $saved,
        string $search
    ): void {
        $bewerbungen = $this->bewerbungen;
        $filter = $this->filter;
        $statusLabels = $this->statusLabels;
        $csrfToken = $this->csrfToken;

        $successHtml = $saved
            ? '<div class="success-banner" id="successBanner"><span>Änderungen wurden erfolgreich gespeichert.</span>
                <span class="close-btn" onclick="closeSuccessBanner()">✖</span></div>'
            : '';

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

    private function saveStatus(array $post): void
    {
        foreach ($post['status'] ?? [] as $id => $status) {
            if (!array_key_exists($status, $this->statusLabels)) continue;

            $kommentar = $post['kommentar'][$id] ?? '';

            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_bewerbungen 
                 SET status=?, kommentar=? 
                 WHERE id=?",
                [$status, $kommentar, (int)$id]
            );
        }

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

    private function deleteBewerbung(array $post): void
    {
        foreach ($post['delete_bewerbung'] ?? [] as $id => $v) {
            $this->dbObj->sqlSet(
                "DELETE FROM {$this->_prefix}etchat_bewerbungen WHERE id=?",
                [(int)$id]
            );
        }

        $params = [];
        if ($this->filter) $params[] = 'status_filter='.urlencode($this->filter);
        if (!empty($_GET['search'] ?? '')) $params[] = 'search='.urlencode($_GET['search']);

        header("Location: ./?AdminBewer" . ($params ? '&'.implode('&',$params) : ''));
        exit;
    }
}