<?php
namespace admin\Controllers;

use Domain\Languages\LanguagesRepository;
use Domain\Scontainers\ScontainersRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;
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 ScontainersController
{
    private ScontainersRepository $repository;
    private LanguagesRepository $languagesRepository;
    private FormRequestHandler $formHandler;

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

    public function list(): string
    {
        $sortableColumns = ['id', 'title', 'status'];
        $filterDefinitions = [
            [
                'key' => 'title',
                'label' => 'Tytul',
                'type' => 'text',
            ],
            [
                'key' => 'status',
                'label' => 'Aktywny',
                'type' => 'select',
                'options' => [
                    '' => '- aktywny -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
        ];

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

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

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

            $rows[] = [
                'lp' => $lp++ . '.',
                'title' => '<a href="/admin/scontainers/edit/id=' . $id . '">' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</a>',
                'code' => '[KONTENER:' . $id . ']',
                'status' => ((int)($item['status'] ?? 0) === 1) ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/scontainers/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/scontainers/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrany kontener?',
                    ],
                ],
            ];
        }

        $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' => 'code', 'label' => 'Kod', 'sortable' => false],
                ['key' => 'status', 'sort_key' => 'status', 'label' => 'Aktywny', '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/scontainers/list/',
            'Brak danych w tabeli.',
            '/admin/scontainers/edit/',
            'Dodaj kontener'
        );

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

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

    public function edit(): string
    {
        $container = $this->repository->find((int)\Shared\Helpers\Helpers::get('id'));
        $languages = $this->languagesRepository->languagesList();
        $validationErrors = $_SESSION['form_errors'][$this->formId()] ?? null;
        if ($validationErrors) {
            unset($_SESSION['form_errors'][$this->formId()]);
        }

        return \Shared\Tpl\Tpl::view('scontainers/container-edit', [
            'form' => $this->buildFormViewModel($container, $languages, $validationErrors),
        ]);
    }

    public function container_edit(): string
    {
        return $this->edit();
    }

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

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

            echo json_encode($response);
            exit;
        }

        $container = $this->repository->find((int)\Shared\Helpers\Helpers::get('id'));
        $languages = $this->languagesRepository->languagesList();
        $form = $this->buildFormViewModel($container, $languages);

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

        $data = $result['data'];
        $savedId = $this->repository->save([
            'id' => (int)($data['id'] ?? 0),
            'status' => $data['status'] ?? 0,
            'show_title' => $data['show_title'] ?? 0,
            'translations' => $data['translations'] ?? [],
        ]);

        if ($savedId) {
            echo json_encode([
                'success' => true,
                'id' => $savedId,
                'message' => 'Kontener zostal zapisany.',
            ]);
            exit;
        }

        echo json_encode([
            'success' => false,
            'errors' => ['general' => 'Podczas zapisywania kontenera wystapil blad.'],
        ]);
        exit;
    }

    public function container_save(): void
    {
        $this->save();
    }

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

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

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

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

        $data = [
            'id' => $id,
            'status' => (int)($container['status'] ?? 1),
            'show_title' => (int)($container['show_title'] ?? 0),
            'languages' => is_array($container['languages'] ?? null) ? $container['languages'] : [],
        ];

        $fields = [
            FormField::hidden('id', $id),
            FormField::langSection('translations', 'content', [
                FormField::text('title', [
                    'label' => 'Tytul',
                ]),
                FormField::editor('text', [
                    'label' => 'Tresc',
                    'height' => 300,
                ]),
            ]),
            FormField::switch('status', [
                'label' => 'Aktywny',
                'tab' => 'settings',
                'value' => true,
            ]),
            FormField::switch('show_title', [
                'label' => 'Pokaz tytul',
                'tab' => 'settings',
            ]),
        ];

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

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

        return new FormEditViewModel(
            $this->formId(),
            'Edycja kontenera statycznego',
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/scontainers/list/',
            true,
            [],
            $languages,
            $errors
        );
    }

    private function formId(): string
    {
        return 'scontainers-container-edit';
    }
}

