<?php
namespace admin\Controllers;

use Domain\Article\ArticleRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;

class ArticlesArchiveController
{
    private ArticleRepository $repository;

    public function __construct(ArticleRepository $repository)
    {
        $this->repository = $repository;
    }

    public function list(): string
    {
        $sortableColumns = ['title', 'date_add', 'date_modify'];

        $filterDefinitions = [
            [
                'key' => 'title',
                'label' => 'Tytul',
                'type' => 'text',
            ],
        ];

        $listRequest = \admin\Support\TableListRequestFactory::fromRequest(
            $filterDefinitions,
            $sortableColumns,
            'date_add'
        );

        $result = $this->repository->listArchivedForAdmin(
            $listRequest['filters'],
            $listRequest['sortColumn'],
            $listRequest['sortDir'],
            $listRequest['page'],
            $listRequest['perPage']
        );

        $rows = [];
        $lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;

        foreach ($result['items'] as $item) {
            $id = (int)($item['id'] ?? 0);
            $title = trim((string)($item['title'] ?? ''));

            $rows[] = [
                'lp' => $lp++ . '.',
                'title' => '<a href="/admin/articles/edit/id=' . $id . '">' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</a>',
                'date_add' => !empty($item['date_add']) ? date('Y-m-d H:i', strtotime((string)$item['date_add'])) : '-',
                'date_modify' => !empty($item['date_modify']) ? date('Y-m-d H:i', strtotime((string)$item['date_modify'])) : '-',
                '_actions' => [
                    [
                        'label' => 'Przywroc',
                        'url' => '/admin/articles_archive/restore/id=' . $id,
                        'class' => 'btn btn-xs btn-success',
                        'confirm' => 'Na pewno chcesz przywrocic wybrany artykul?',
                        'confirm_ok' => 'Przywroc',
                        'confirm_cancel' => 'Anuluj',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/articles_archive/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz trwale usunac wybrany artykul?',
                        'confirm_ok' => 'Usun',
                        'confirm_cancel' => 'Anuluj',
                    ],
                ],
            ];
        }

        $total = (int)$result['total'];
        $totalPages = max(1, (int)ceil($total / $listRequest['perPage']));

        $viewModel = new PaginatedTableViewModel(
            [
                ['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'title', 'sort_key' => 'title', 'label' => 'Tytul', 'sortable' => true, 'raw' => true],
                ['key' => 'date_add', 'sort_key' => 'date_add', 'label' => 'Data dodania', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'date_modify', 'sort_key' => 'date_modify', 'label' => 'Data modyfikacji', 'class' => 'text-center', 'sortable' => true],
            ],
            $rows,
            $listRequest['viewFilters'],
            [
                'column' => $listRequest['sortColumn'],
                'dir' => $listRequest['sortDir'],
            ],
            [
                'page' => $listRequest['page'],
                'per_page' => $listRequest['perPage'],
                'total' => $total,
                'total_pages' => $totalPages,
            ],
            array_merge($listRequest['queryFilters'], [
                'sort' => $listRequest['sortColumn'],
                'dir' => $listRequest['sortDir'],
                'per_page' => $listRequest['perPage'],
            ]),
            $listRequest['perPageOptions'],
            $sortableColumns,
            '/admin/articles_archive/list/',
            'Brak danych w tabeli.'
        );

        return \Shared\Tpl\Tpl::view('articles/articles-archive-list', [
            'viewModel' => $viewModel,
        ]);
    }

    public function view_list(): string
    {
        return $this->list();
    }

    public function restore(): void
    {
        if ($this->repository->restore((int)\Shared\Helpers\Helpers::get('id'))) {
            \Shared\Helpers\Helpers::alert('Artykul zostal przywrocony.');
        }

        header('Location: /admin/articles_archive/list/');
        exit;
    }

    public function article_restore(): void
    {
        $this->restore();
    }

    public function delete(): void
    {
        if ($this->repository->deletePermanently((int)\Shared\Helpers\Helpers::get('id'))) {
            \Shared\Helpers\Helpers::alert('Artykul zostal trwale usuniety.');
        }

        header('Location: /admin/articles_archive/list/');
        exit;
    }

    public function article_delete(): void
    {
        $this->delete();
    }
}
