<?php
namespace admin\Controllers;

use Domain\Layouts\LayoutsRepository;
use Domain\Languages\LanguagesRepository;

class LayoutsController
{
    private LayoutsRepository $repository;
    private LanguagesRepository $languagesRepository;

    public function __construct(LayoutsRepository $repository, LanguagesRepository $languagesRepository)
    {
        $this->repository = $repository;
        $this->languagesRepository = $languagesRepository;
    }

    public function list(): string
    {
        $sortableColumns = ['name', 'status', 'categories_default'];

        $filterDefinitions = [
            [
                'key' => 'name',
                'label' => 'Nazwa',
                'type' => 'text',
            ],
            [
                'key' => 'status',
                'label' => 'Szablon domyslny',
                'type' => 'select',
                'options' => [
                    '' => '- domyslny -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
            [
                'key' => 'categories_default',
                'label' => 'Domyslny (kategorie)',
                'type' => 'select',
                'options' => [
                    '' => '- kategorie -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
        ];

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

        $sortDir = $listRequest['sortDir'];
        if (trim((string)\Shared\Helpers\Helpers::get('sort')) === '') {
            $sortDir = 'ASC';
        }

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

        $rows = [];
        $lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
        foreach ($result['items'] as $item) {
            $id = (int)($item['id'] ?? 0);
            $name = trim((string)($item['name'] ?? ''));

            $rows[] = [
                'lp' => $lp++ . '.',
                'name' => '<a href="/admin/layouts/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'status' => ((int)($item['status'] ?? 0) === 1) ? '<span class="text-system">tak</span>' : 'nie',
                'categories_default' => ((int)($item['categories_default'] ?? 0) === 1) ? '<span class="text-system">tak</span>' : 'nie',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/layouts/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/layouts/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrany szablon?',
                    ],
                ],
            ];
        }

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

        $viewModel = new \admin\ViewModels\Common\PaginatedTableViewModel(
            [
                ['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'status', 'sort_key' => 'status', 'label' => 'Szablon domyslny', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'categories_default', 'sort_key' => 'categories_default', 'label' => 'Domyslny (kategorie)', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
            ],
            $rows,
            $listRequest['viewFilters'],
            [
                'column' => $listRequest['sortColumn'],
                'dir' => $sortDir,
            ],
            [
                'page' => $listRequest['page'],
                'per_page' => $listRequest['perPage'],
                'total' => $total,
                'total_pages' => $totalPages,
            ],
            array_merge($listRequest['queryFilters'], [
                'sort' => $listRequest['sortColumn'],
                'dir' => $sortDir,
                'per_page' => $listRequest['perPage'],
            ]),
            $listRequest['perPageOptions'],
            $sortableColumns,
            '/admin/layouts/list/',
            'Brak danych w tabeli.',
            '/admin/layouts/edit/',
            'Dodaj szablon'
        );

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

    public function edit(): string
    {
        return \Shared\Tpl\Tpl::view('layouts/layout-edit', [
            'layout' => $this->repository->find((int)\Shared\Helpers\Helpers::get('id')),
            'menus' => $this->repository->menusWithPages(),
            'categories' => $this->repository->categoriesTree(),
            'dlang' => $this->languagesRepository->defaultLanguageId(),
        ]);
    }

    public function save(): void
    {
        $response = ['status' => 'error', 'msg' => 'Podczas zapisywania szablonu wystapil blad. Prosze sprobowac ponownie.'];
        $values = json_decode((string)\Shared\Helpers\Helpers::get('values'), true);

        if (is_array($values)) {
            $id = $this->repository->save($values);
            if (!empty($id)) {
                $response = ['status' => 'ok', 'msg' => 'Szablon zostal zapisany.', 'id' => $id];
            }
        }

        echo json_encode($response);
        exit;
    }

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

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

}
