<?php
namespace admin\Controllers;

use Domain\Dictionaries\DictionariesRepository;
use Domain\Languages\LanguagesRepository;
use admin\ViewModels\Forms\FormAction;
use admin\ViewModels\Forms\FormEditViewModel;
use admin\ViewModels\Forms\FormField;
use admin\ViewModels\Forms\FormTab;
use admin\Support\Forms\FormRequestHandler;

class DictionariesController
{
    private DictionariesRepository $repository;
    private LanguagesRepository $languagesRepository;
    private FormRequestHandler $formHandler;

    public function __construct(DictionariesRepository $repository, LanguagesRepository $languagesRepository)
    {
        $this->repository = $repository;
        $this->languagesRepository = $languagesRepository;
        $this->formHandler = new FormRequestHandler();
    }

    public function list(): string
    {
        $sortableColumns = ['id', 'text'];

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

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

        $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'];
            $text = trim((string)($item['text'] ?? ''));

            $rows[] = [
                'lp' => $lp++ . '.',
                'text' => '<a href="/admin/dictionaries/edit/id=' . $id . '">' . htmlspecialchars($text, ENT_QUOTES, 'UTF-8') . '</a>',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/dictionaries/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/dictionaries/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrana jednostke miary?',
                    ],
                ],
            ];
        }

        $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' => 'text', 'sort_key' => 'text', 'label' => 'Tekst', '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/dictionaries/list/',
            'Brak danych w tabeli.',
            '/admin/dictionaries/edit/',
            'Dodaj jednostke miary'
        );

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

    public function edit(): string
    {
        $unitId = (int)\Shared\Helpers\Helpers::get('id');
        $unit = $this->repository->find($unitId) ?? ['id' => 0, 'languages' => []];
        $languages = $this->languagesRepository->languagesList();

        $validationErrors = $_SESSION['form_errors'][$this->getFormId()] ?? null;
        if ($validationErrors) {
            unset($_SESSION['form_errors'][$this->getFormId()]);
        }

        $viewModel = $this->buildFormViewModel($unit, $languages, $validationErrors);

        return \Shared\Tpl\Tpl::view('dictionaries/unit-edit', ['form' => $viewModel]);
    }

    public function save(): void
    {
        $legacyValues = \Shared\Helpers\Helpers::get('values');
        if ($legacyValues) {
            $values = json_decode($legacyValues, true);
            $response = ['status' => 'error', 'msg' => 'Podczas zapisywania jednostki miary wystapil blad.'];

            if (is_array($values)) {
                $savedId = $this->repository->save([
                    'id' => (int)($values['id'] ?? 0),
                    'text' => (array)($values['text'] ?? []),
                ]);
                if ($savedId) {
                    $response = ['status' => 'ok', 'msg' => 'Jednostka miary zostala zapisana.', 'id' => $savedId];
                }
            }

            echo json_encode($response);
            exit;
        }

        $unitId = (int)\Shared\Helpers\Helpers::get('id');
        $unit = $this->repository->find($unitId) ?? ['id' => 0, 'languages' => []];
        $languages = $this->languagesRepository->languagesList();
        $viewModel = $this->buildFormViewModel($unit, $languages);

        $result = $this->formHandler->handleSubmit($viewModel, $_POST);
        if (!$result['success']) {
            $_SESSION['form_errors'][$this->getFormId()] = $result['errors'];
            echo json_encode(['success' => false, 'errors' => $result['errors']]);
            exit;
        }

        $data = $result['data'];
        $data['id'] = $unitId ?: null;

        $savedId = $this->repository->save($data);
        if ($savedId) {
            echo json_encode([
                'success' => true,
                'id' => $savedId,
                'message' => 'Jednostka miary zostala zapisana.',
            ]);
            exit;
        }

        echo json_encode([
            'success' => false,
            'errors' => ['general' => 'Blad podczas zapisywania do bazy.'],
        ]);
        exit;
    }

    public function delete(): void
    {
        $unitId = (int)\Shared\Helpers\Helpers::get('id');
        if ($this->repository->delete($unitId)) {
            \Shared\Helpers\Helpers::alert('Jednostka miary zostala usunieta.');
        }

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

    private function buildFormViewModel(array $unit, array $languages, ?array $errors = null): FormEditViewModel
    {
        $unitId = (int)($unit['id'] ?? 0);
        $isNew = $unitId <= 0;

        $data = [
            'id' => $unitId,
            'languages' => [],
        ];

        if (isset($unit['languages']) && is_array($unit['languages'])) {
            foreach ($unit['languages'] as $langId => $translation) {
                $data['languages'][(string)$langId] = [
                    'text' => (string)($translation['text'] ?? ''),
                ];
            }
        }

        $tabs = [
            new FormTab('content', 'Tresc', 'fa-file'),
        ];

        $fields = [
            FormField::langSection('translations', 'content', [
                FormField::text('text', [
                    'label' => 'Tekst',
                ]),
            ]),
        ];

        $actionUrl = '/admin/dictionaries/save/' . ($isNew ? '' : ('id=' . $unitId));
        $actions = [
            FormAction::save($actionUrl, '/admin/dictionaries/list/'),
            FormAction::cancel('/admin/dictionaries/list/'),
        ];

        return new FormEditViewModel(
            $this->getFormId(),
            $isNew ? 'Nowa jednostka miary' : 'Edycja jednostki miary',
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/dictionaries/list/',
            true,
            ['id' => $unitId],
            $languages,
            $errors
        );
    }

    private function getFormId(): string
    {
        return 'dictionaries-unit-edit';
    }
}
