<?php
namespace EasyChat\View;

use EasyChat\KnowledgeSection;

class KnowledgeStorageFragments {

    private const STATUS_LABELS = [
        'pending'  => 'Ожидает',
        'indexing' => 'Индексируется',
        'active'   => 'Активен',
        'disabled' => 'Отключен',
        'failed'   => 'Ошибка',
    ];

    private const SECTION_LABELS = [
        KnowledgeSection::DOCUMENT => 'Документ',
        KnowledgeSection::PRODUCT  => 'Товар',
        KnowledgeSection::PAGE     => 'Страница',
    ];

    public static function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }

    public function editorShell(array $article = [], string $mode = 'create', string $error = ''): string {
        $is_edit = $mode === 'edit' && (int)($article['id'] ?? 0) > 0;
        $id = $is_edit ? (int)($article['id'] ?? 0) : 0;
        $title = (string)($article['title'] ?? '');
        $content = (string)($article['content'] ?? '');
        $heading = $is_edit ? 'Редактировать статью' : 'Добавить статью';
        $button = 'Сохранить статью';
        $description = $is_edit
            ? 'Измените текст статьи. После сохранения EasyChat обновит материал, чтобы ИИ использовал свежую версию.'
            : 'Добавьте заголовок и текст. EasyChat подготовит статью для ИИ автоматически.';
        $hint = $is_edit
            ? 'После сохранения статья временно перейдёт в обработку и обновится в базе знаний.'
            : 'Пишите обычным человеческим текстом: правила доставки, оплаты, гарантий и ответы на частые вопросы.';
        $word_count = $this->wordCount($content);
        $character_count = $this->utf8Length($content);

        $html = '<div id="knowledge-document-editor-shell" class="' . self::e(HtmxFragmentRenderer::motionClass('knowledge-editor')) . '" data-editor-mode="' . ($is_edit ? 'edit' : 'create') . '">'
            . '<div class="modal-header border-0 pb-0 px-4 pt-4">'
            . '<h5 class="modal-title fw-bold knowledge-editor-title" id="addDocumentModalLabel">'
            . '<i class="fa fa-file-text me-2 knowledge-editor-title-icon" aria-hidden="true"></i> <span id="docEditorTitle">' . self::e($heading) . '</span>'
            . '</h5>'
            . '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>'
            . '</div>'
            . '<form id="knowledge-document-form"'
            . ' hx-post="index.php?route=knowledge_storage/saveDocument"'
            . ' hx-target="#knowledge-storage-list"'
            . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
            . ' hx-sync="#knowledge-storage-list:replace"'
            . ' hx-include="#knowledge-document-form, #knowledge-filter-form, #knowledge-selection-fields, #knowledge-bulk-form input[name=&quot;page&quot;]"'
            . ' data-csrf-field="csrf_token">'
            . '<input type="hidden" name="csrf_token" value="">'
            . '<input type="hidden" name="id" id="docId" value="' . $id . '">'
            . '<div class="modal-body px-4 py-3">'
            . '<p class="text-muted small mb-3" id="docEditorDescription">' . self::e($description) . '</p>';

        if ($error !== '') {
            $html .= '<div class="alert alert-danger knowledge-editor-error mb-3" role="alert">'
                . '<i class="fa fa-exclamation-triangle me-2" aria-hidden="true"></i><span>' . self::e($error) . '</span>'
                . '</div>';
        }

        $html .= '<div class="knowledge-editor-note mb-3" id="docEditorHint">'
            . '<i class="fa fa-magic" aria-hidden="true"></i>'
            . '<span>' . self::e($hint) . '</span>'
            . '</div>'
            . '<div class="mb-3">'
            . '<label class="form-label fw-semibold knowledge-editor-label" for="docTitle">Заголовок <span class="text-danger">*</span></label>'
            . '<input type="text" name="title" id="docTitle" class="form-control knowledge-editor-control"'
            . ' placeholder="Например: Условия доставки и оплаты" maxlength="512" required value="' . self::e($title) . '">'
            . '</div>'
            . '<div class="mb-1">'
            . '<label class="form-label fw-semibold knowledge-editor-label" for="docContent">Текст документа <span class="text-danger">*</span></label>'
            . '<textarea name="content" id="docContent" class="form-control knowledge-editor-control knowledge-editor-textarea" rows="10"'
            . ' placeholder="Вставьте или введите текст, который ИИ должен знать..."'
            . ' aria-describedby="docWordCount docCharCount" required>' . self::e($content) . '</textarea>'
            . '<div class="knowledge-editor-counters mt-1" aria-label="Объём статьи">'
            . '<small class="text-muted" id="docWordCount">' . $word_count . ' ' . self::e($this->pluralRu($word_count, 'слово', 'слова', 'слов')) . '</small>'
            . '<small class="text-muted" id="docCharCount">' . $character_count . ' ' . self::e($this->pluralRu($character_count, 'символ', 'символа', 'символов')) . '</small>'
            . '</div>'
            . '</div>'
            . '</div>'
            . '<div class="modal-footer border-0 px-4 pb-4 pt-2 gap-2">'
            . '<button type="button" class="btn btn-light px-4 knowledge-editor-cancel" data-bs-dismiss="modal">Отмена</button>'
            . '<button type="submit" id="btnSaveDoc" class="btn btn-primary px-4 knowledge-editor-save">'
            . '<span id="btnSaveDocText"><i class="fa fa-save me-2" aria-hidden="true"></i><span id="btnSaveDocLabel">' . self::e($button) . '</span></span>'
            . '<span id="btnSaveDocSpinner" class="htmx-indicator">'
            . '<span class="spinner-border spinner-border-sm me-2" aria-hidden="true"></span>Сохранение...'
            . '</span>'
            . '</button>'
            . '</div>'
            . '</form>'
            . '</div>';

        return $html;
    }

    



    private function wordCount(string $value): int {
        $trimmed = trim($value);
        if ($trimmed === '') {
            return 0;
        }

        $parts = preg_split('/\s+/u', $trimmed, -1, PREG_SPLIT_NO_EMPTY);
        return is_array($parts) ? count($parts) : 0;
    }

    private function utf8Length(string $value): int {
        if (function_exists('mb_strlen')) {
            return (int)mb_strlen($value, 'UTF-8');
        }

        $matches = [];
        $count = preg_match_all('/./us', $value, $matches);
        return $count === false ? strlen($value) : (int)$count;
    }

    private function pluralRu(int $value, string $one, string $few, string $many): string {
        $number = abs($value) % 100;
        $last = $number % 10;
        if ($number > 10 && $number < 20) {
            return $many;
        }
        if ($last > 1 && $last < 5) {
            return $few;
        }
        return $last === 1 ? $one : $many;
    }

    public function filters(array $filters, int $total): string {
        $q = (string)($filters['q'] ?? '');
        $status = (string)($filters['status'] ?? '');
        $section_id = (int)($filters['section_id'] ?? 0);
        $selected_section = $section_id > 0 ? (string)$section_id : '';

        return '<form id="knowledge-filter-form" class="knowledge-filter-panel"'
            . ' hx-get="index.php?route=knowledge_storage/list"'
            . ' hx-target="#knowledge-storage-list"'
            . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
            . ' hx-trigger="submit, input changed delay:420ms from:#knowledge-filter-search, change delay:120ms from:.knowledge-filter-control"'
            . ' hx-sync="#knowledge-storage-list:replace"'
            . ' hx-push-url="true"'
            . ' hx-include="#knowledge-filter-form, #knowledge-selection-fields">'
            . '<div class="knowledge-filter-search">'
            . '<i class="fa fa-search" aria-hidden="true"></i>'
            . '<input id="knowledge-filter-search" type="search" name="q" class="form-control" value="' . self::e($q) . '"'
            . ' maxlength="120" autocomplete="off" placeholder="Найти статью, товар или страницу">'
            . '</div>'
            . '<select name="status" class="form-select knowledge-filter-control" aria-label="Статус">'
            . $this->option('', 'Все статусы', $status)
            . $this->option('active', 'Активные', $status)
            . $this->option('pending', 'Ожидают', $status)
            . $this->option('indexing', 'Индексируются', $status)
            . $this->option('disabled', 'Отключенные', $status)
            . $this->option('failed', 'С ошибкой', $status)
            . '</select>'
            . '<select name="section_id" class="form-select knowledge-filter-control" aria-label="Раздел">'
            . $this->option('', 'Все разделы', $selected_section)
            . $this->option((string)KnowledgeSection::DOCUMENT, 'Документы', $selected_section)
            . $this->option((string)KnowledgeSection::PRODUCT, 'Товары', $selected_section)
            . $this->option((string)KnowledgeSection::PAGE, 'Страницы', $selected_section)
            . '</select>'
            . '<button type="submit" class="btn btn-light knowledge-filter-submit" title="Применить фильтры">'
            . '<i class="fa fa-filter" aria-hidden="true"></i>'
            . '<span class="visually-hidden">Применить фильтры</span>'
            . '</button>'
            . '<span id="knowledge-storage-indicator" class="htmx-indicator knowledge-filter-indicator">'
            . '<span class="spinner-border spinner-border-sm" aria-hidden="true"></span>'
            . '</span>'
            . '<span class="knowledge-total-chip">' . (int)$total . ' записей</span>'
            . '</form>';
    }

    public function listPanel(array $items, int $total, int $page, int $limit, array $filters, array $selected_ids = []): string {
        $selected_ids = $this->normalizeSelectedIds($selected_ids);
        $page = max(1, $page);
        $limit = max(1, $limit);
        $total_pages = max(1, (int)ceil($total / $limit));
        if ($page > $total_pages) {
            $page = $total_pages;
        }

        $html = '<div id="knowledge-storage-list" class="' . self::e(HtmxFragmentRenderer::motionClass('knowledge-list')) . '"'
            . ' data-selected-count="' . count($selected_ids) . '">';
        $html .= '<form id="knowledge-bulk-form" class="knowledge-bulk-bar"'
            . ' hx-post="index.php?route=knowledge_storage/bulkAction"'
            . ' data-csrf-field="csrf_token"'
            . ' hx-target="#knowledge-storage-list"'
            . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
            . ' hx-sync="#knowledge-storage-list:replace"'
            . ' hx-include="#knowledge-bulk-form, #knowledge-filter-form">'
            . '<input type="hidden" name="csrf_token" value="">'
            . '<div id="knowledge-selection-fields">'
            . $this->selectedInputs($selected_ids)
            . '</div>'
            . '<input type="hidden" name="page" value="' . (int)$page . '">'
            . '<div class="knowledge-bulk-summary">'
            . '<span class="knowledge-selection-pill"><i class="fa fa-check-square-o" aria-hidden="true"></i> '
            . '<span id="knowledge-selected-count">' . count($selected_ids) . '</span> выбрано</span>'
            . '<label class="knowledge-select-page-inline"><input class="form-check-input kb-select-page-toggle" type="checkbox"> Выбрать страницу</label>'
            . '<span class="text-muted small">Массовые действия применяются только к выбранным строкам.</span>'
            . '</div>'
            . '<div class="knowledge-bulk-actions" role="group" aria-label="Массовые действия">'
            . $this->bulkButton('enable', 'fa-play', 'Включить')
            . $this->bulkButton('disable', 'fa-pause', 'Отключить')
            . $this->bulkButton('retry', 'fa-refresh', 'Повторить')
            . $this->bulkButton('delete', 'fa-trash', 'Удалить', true)
            . '</div>'
            . '</form>';

        if (!$items) {
            $html .= $this->emptyState($filters);
            $html .= '</div>';
            return $html;
        }

        $html .= '<div class="table-responsive kb-table-wrap">'
            . '<table class="table kb-table mb-0">'
            . '<thead><tr>'
            . '<th class="knowledge-select-col"><input id="kb-select-page" class="form-check-input kb-select-page-toggle" type="checkbox" aria-label="Выбрать записи на странице"></th>'
            . '<th style="width:38%;">Заголовок</th>'
            . '<th>Раздел</th>'
            . '<th>Статус</th>'
            . '<th>Добавлен</th>'
            . '<th class="text-end">Действия</th>'
            . '</tr></thead><tbody>';

        foreach ($items as $item) {
            $html .= $this->row($item, in_array((int)($item['id'] ?? 0), $selected_ids, true));
        }

        $html .= '</tbody></table></div>';
        $html .= $this->pagination($page, $total_pages, $filters, $selected_ids);
        $html .= '</div>';

        return $html;
    }

    private function row(array $item, bool $selected): string {
        $id = (int)($item['id'] ?? 0);
        $status = (string)($item['status'] ?? '');
        $label = self::STATUS_LABELS[$status] ?? $status;
        $section_id = (int)($item['section_id'] ?? 0);
        $section = self::SECTION_LABELS[$section_id] ?? 'Документ';
        $date = $this->formatDate((string)($item['date_added'] ?? ''));
        $toggleable = in_array($status, ['active', 'disabled'], true);
        $editable = $section_id === KnowledgeSection::DOCUMENT;

        $html = '<tr id="kb-row-' . $id . '" data-knowledge-id="' . $id . '" class="' . ($selected ? 'is-selected' : '') . '">';
        $html .= '<td class="knowledge-select-col" data-label="Выбор">'
            . '<input class="form-check-input kb-row-check" type="checkbox" value="' . $id . '"'
            . ($selected ? ' checked' : '') . ' aria-label="Выбрать запись «' . self::e($item['title'] ?? '') . '»">'
            . '</td>';
        $html .= '<td data-label="Заголовок">'
            . '<span class="kb-title" title="' . self::e($item['title'] ?? '') . '">' . self::e($item['title'] ?? '') . '</span>';
        if ($status === 'failed' && !empty($item['error'])) {
            $html .= '<br><small class="kb-error-detail text-danger" data-error="' . self::e($item['error']) . '">'
                . '<i class="fa fa-exclamation-circle me-1" aria-hidden="true"></i>Подробнее об ошибке</small>';
        }
        $html .= '</td>';
        $html .= '<td data-label="Раздел"><span class="kb-section-badge">' . self::e($section) . '</span></td>';
        $html .= '<td data-label="Статус">' . $this->statusBadge($id, $status, $label) . '</td>';
        $html .= '<td class="text-muted" style="font-size:13px;" data-label="Добавлен">' . self::e($date) . '</td>';
        $html .= '<td class="text-end" style="white-space:nowrap;" data-label="Действия"><div class="d-inline-flex align-items-center gap-2">';
        if ($editable) {
            $html .= '<button type="button" class="btn btn-sm btn-edit-entry" data-id="' . $id . '" title="Редактировать статью"'
                . ' hx-post="index.php?route=knowledge_storage/editor"'
                . ' hx-target="#knowledge-document-editor-shell"'
                . ' hx-swap="outerHTML"'
                . ' data-csrf-field="csrf_token"'
                . ' hx-vals=\'' . self::e(json_encode(['id' => $id], JSON_UNESCAPED_SLASHES)) . '\''
                . ' hx-sync="#knowledge-document-editor-shell:replace">'
                . '<i class="fa fa-pencil" aria-hidden="true"></i></button>';
        }
        if ($status === 'failed') {
            $html .= '<button type="button" class="btn btn-sm btn-retry-entry" data-id="' . $id . '" title="Повторить индексирование"'
                . ' hx-post="index.php?route=knowledge_storage/rowAction"'
                . ' hx-target="#knowledge-storage-list"'
                . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
                . ' hx-include="#knowledge-filter-form, #knowledge-selection-fields, #knowledge-bulk-form input[name=&quot;page&quot;]"'
                . ' data-csrf-field="csrf_token"'
                . ' hx-vals=\'' . self::e(json_encode(['id' => $id, 'action' => 'retry'], JSON_UNESCAPED_SLASHES)) . '\''
                . ' hx-sync="#knowledge-storage-list:replace">'
                . '<i class="fa fa-refresh" aria-hidden="true"></i></button>';
        }
        $html .= '<div class="form-check form-switch m-0" title="' . self::e($toggleable ? ($status === 'active' ? 'Отключить запись' : 'Включить запись') : 'Недоступно в статусе «' . $label . '»') . '">'
            . '<input class="form-check-input kb-toggle-switch" type="checkbox" data-id="' . $id . '"'
            . ($status === 'active' ? ' checked' : '')
            . (!$toggleable ? ' disabled' : '')
            . ($toggleable
                ? ' hx-post="index.php?route=knowledge_storage/rowAction"'
                    . ' hx-target="#knowledge-storage-list"'
                    . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
                    . ' hx-trigger="change"'
                    . ' hx-include="#knowledge-filter-form, #knowledge-selection-fields, #knowledge-bulk-form input[name=&quot;page&quot;]"'
                    . ' data-csrf-field="csrf_token"'
                    . ' hx-vals=\'' . self::e(json_encode(['id' => $id, 'action' => 'toggle'], JSON_UNESCAPED_SLASHES)) . '\''
                    . ' hx-sync="#knowledge-storage-list:replace"'
                : '')
            . '></div>';
        $html .= '<button type="button" class="btn btn-sm btn-delete-entry" data-id="' . $id . '" title="Удалить"'
            . ' hx-post="index.php?route=knowledge_storage/rowAction"'
            . ' hx-target="#knowledge-storage-list"'
            . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
            . ' hx-include="#knowledge-filter-form, #knowledge-selection-fields, #knowledge-bulk-form input[name=&quot;page&quot;]"'
            . ' data-csrf-field="csrf_token"'
            . ' hx-vals=\'' . self::e(json_encode(['id' => $id, 'action' => 'delete'], JSON_UNESCAPED_SLASHES)) . '\''
            . ' hx-confirm="Удалить запись и её вектор безвозвратно?"'
            . ' hx-sync="#knowledge-storage-list:replace">'
            . '<i class="fa fa-trash" aria-hidden="true"></i></button>';
        $html .= '</div></td></tr>';

        return $html;
    }

    private function statusBadge(int $id, string $status, string $label): string {
        $icon = '';
        if ($status === 'indexing') {
            $icon = '<span class="spinner-border" style="width:10px;height:10px;border-width:1.5px;" aria-hidden="true"></span>';
        } elseif ($status === 'active') {
            $icon = '<i class="fa fa-check-circle" style="font-size:11px;" aria-hidden="true"></i>';
        } elseif ($status === 'disabled') {
            $icon = '<i class="fa fa-eye-slash" style="font-size:11px;" aria-hidden="true"></i>';
        } elseif ($status === 'failed') {
            $icon = '<i class="fa fa-times-circle" style="font-size:11px;" aria-hidden="true"></i>';
        }

        return '<span class="kb-badge kb-status-' . self::e($status) . '" id="kb-badge-' . $id . '">'
            . $icon . self::e($label) . '</span>';
    }

    private function pagination(int $page, int $total_pages, array $filters, array $selected_ids): string {
        if ($total_pages <= 1) {
            return '';
        }

        $start = max(1, $page - 1);
        $end = min($total_pages, $page + 1);
        if ($end - $start < 2) {
            $start = max(1, min($start, $end - 2));
            $end = min($total_pages, max($end, $start + 2));
        }

        $html = '<div class="card-footer bg-white border-0 pt-0 pb-3 px-3 easychat-pagination"><ul class="pagination pagination-sm mb-0 justify-content-center">';
        $html .= $this->pageLink(1, '|<', $page <= 1, $filters, $selected_ids);
        $html .= $this->pageLink(max(1, $page - 1), '<', $page <= 1, $filters, $selected_ids);
        for ($i = $start; $i <= $end; $i++) {
            if ($i === $page) {
                $html .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
            } else {
                $html .= $this->pageLink($i, (string)$i, false, $filters, $selected_ids);
            }
        }
        $html .= $this->pageLink(min($total_pages, $page + 1), '>', $page >= $total_pages, $filters, $selected_ids);
        $html .= $this->pageLink($total_pages, '>|', $page >= $total_pages, $filters, $selected_ids);
        $html .= '</ul></div>';

        return $html;
    }

    private function pageLink(int $page, string $label, bool $disabled, array $filters, array $selected_ids): string {
        if ($disabled) {
            return '<li class="page-item disabled"><span class="page-link">' . self::e($label) . '</span></li>';
        }

        $url = 'index.php?route=knowledge_storage/list&page=' . $page . $this->filterQuery($filters);
        return '<li class="page-item"><a class="page-link" href="' . self::e($url) . '"'
            . ' hx-get="' . self::e($url) . '"'
            . ' hx-target="#knowledge-storage-list"'
            . ' hx-swap="' . self::e(HtmxFragmentRenderer::knowledgeListSwap()) . '"'
            . ' hx-sync="#knowledge-storage-list:replace"'
            . ' hx-include="#knowledge-filter-form, #knowledge-selection-fields"'
            . ' hx-push-url="true"'
            . ' data-page="' . $page . '">' . self::e($label) . '</a></li>';
    }

    private function emptyState(array $filters): string {
        $has_filters = trim((string)($filters['q'] ?? '')) !== ''
            || (string)($filters['status'] ?? '') !== ''
            || (int)($filters['section_id'] ?? 0) > 0;

        if ($has_filters) {
            return '<div class="card-body p-5 text-center knowledge-empty-state">'
                . '<div class="knowledge-empty-icon"><i class="fa fa-search" aria-hidden="true"></i></div>'
                . '<h5 class="fw-bold mb-2">Ничего не найдено</h5>'
                . '<p class="text-muted small mb-0">Смягчите фильтр или очистите поиск, чтобы снова увидеть материалы базы знаний.</p>'
                . '</div>';
        }

        return '<div class="card-body p-5 text-center knowledge-empty-state">'
            . '<div class="knowledge-empty-icon"><i class="fa fa-database" aria-hidden="true"></i></div>'
            . '<h5 class="fw-bold mb-2">База знаний пуста</h5>'
            . '<p class="text-muted small mb-4">Добавьте статьи, инструкции или описания товаров — ИИ будет использовать их для точных ответов посетителям.</p>'
            . '<button type="button" class="btn btn-primary easychat-admin-primary-action px-4 btn-open-document-editor"'
            . ' hx-post="index.php?route=knowledge_storage/editor"'
            . ' hx-target="#knowledge-document-editor-shell"'
            . ' hx-swap="outerHTML"'
            . ' data-csrf-field="csrf_token"'
            . ' hx-sync="#knowledge-document-editor-shell:replace">'
            . '<i class="fa fa-plus me-2" aria-hidden="true"></i>Добавить первую статью</button>'
            . '</div>';
    }

    private function bulkButton(string $action, string $icon, string $label, bool $danger = false): string {
        $class = $danger ? 'btn-outline-danger' : 'btn-light';
        $confirm = $danger
            ? ' hx-confirm="Удалить выбранные записи и их векторы безвозвратно?"'
            : '';

        return '<button type="submit" name="action" value="' . self::e($action) . '"'
            . ' class="btn btn-sm ' . $class . ' knowledge-bulk-button" data-bulk-action="' . self::e($action) . '" disabled' . $confirm . '>'
            . '<i class="fa ' . self::e($icon) . ' me-1" aria-hidden="true"></i>' . self::e($label)
            . '</button>';
    }

    private function selectedInputs(array $selected_ids): string {
        $html = '';
        foreach ($selected_ids as $id) {
            $html .= '<input type="hidden" name="selected_ids[]" value="' . (int)$id . '">';
        }
        return $html;
    }

    private function option(string $value, string $label, string $selected): string {
        return '<option value="' . self::e($value) . '"' . ($value === $selected ? ' selected' : '') . '>' . self::e($label) . '</option>';
    }

    private function filterQuery(array $filters): string {
        $query = [];
        foreach (['q', 'status', 'section_id'] as $key) {
            $value = (string)($filters[$key] ?? '');
            if ($value !== '' && $value !== '0') {
                $query[$key] = $value;
            }
        }
        return $query ? '&' . http_build_query($query) : '';
    }

    private function normalizeSelectedIds(array $selected_ids): array {
        $normalized = [];
        foreach ($selected_ids as $id) {
            $id = (int)$id;
            if ($id > 0) {
                $normalized[$id] = $id;
            }
            if (count($normalized) >= 100) {
                break;
            }
        }
        return array_values($normalized);
    }

    private function formatDate(string $value): string {
        $timestamp = strtotime($value);
        return $timestamp ? date('d.m.Y H:i', $timestamp) : '-';
    }
}
