<?php

namespace KupShop\ArticlesBundle\Twig\Components\Articles;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Twig\BaseComponent;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Articles/components/Articles/ArticleInfo/ArticleInfo.1.html.twig')]
#[Component(1, [
    new Version(1, newJs: null),
])]
class ArticleInfo extends BaseComponent
{
    public array $article;
    private ?array $sections = null;
    public bool $showDate = true;
    public bool $showSeen = true;
    public bool $showTags = true;
    public bool $showSeparator = true;
    public bool $showAuthor = true;
    public bool $showSection = true;
    public string $dateFormat = 'd. m.';

    public function getSectionName(): string
    {
        return $this->article['section']['name'] ?? '';
    }

    public function getSectionUrl(): string
    {
        return path('kupshop_content_articles_articles_1', ['IDb' => $this->article['section']['id']]);
    }

    public function getDate(): string
    {
        $date = $this->article['date'];

        if ($date instanceof \DateTime) {
            return $date->format(\Settings::getDateFormat());
        } else {
            return $date;
        }
    }

    public function getSeen(): int
    {
        return $this->article['seen'] ?? 0;
    }

    public function getAuthor(): ?string
    {
        if (empty($this->article['authors'])) {
            return null;
        }

        $firstAuthor = reset($this->article['authors']);

        if (!empty($firstAuthor['nick'])) {
            return $firstAuthor['nick'];
        }

        return $firstAuthor['name'].' '.$firstAuthor['surname'];
    }

    public function getAuthorUrl(): ?string
    {
        if (!empty($this->article['authors'])) {
            $firstAuthor = reset($this->article['authors']);

            return path('kupshop_content_articles_articlesauthor', [
                'authorId' => $firstAuthor['id'],
            ]);
        }

        return null;
    }

    public function getTags(): ?array
    {
        if (!empty($this->article['tags'])) {
            return $this->article['tags'];
        }

        return null;
    }

    public function getTagUrl(int $id, $idKey = 'ID', $absolute = null): ?string
    {
        $params = [
            's' => 'articles_tags',
            $idKey => $id,
            'TITLE' => $this->article['tags'][$id]['tag'],
        ];

        if ($absolute) {
            $params['absolute'] = 1;
        }

        return htmlspecialchars(createScriptURL($params), ENT_QUOTES);
    }
}
