<?php
namespace admin\Controllers;

use Domain\Banner\BannerRepository;
use Domain\Languages\LanguagesRepository;
use admin\ViewModels\Forms\FormEditViewModel;
use admin\ViewModels\Forms\FormField;
use admin\ViewModels\Forms\FormTab;
use admin\ViewModels\Forms\FormAction;
use admin\Support\Forms\FormRequestHandler;

class BannerController
{
    private BannerRepository $repository;
    private LanguagesRepository $languagesRepository;
    private FormRequestHandler $formHandler;

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

    /**
     * Lista banerow
     */
    public function list(): string
    {
        $sortableColumns = ['name', 'status', 'home_page', 'date_start', 'date_end'];

        $filterDefinitions = [
            [
                'key' => 'name',
                'label' => 'Nazwa',
                'type' => 'text',
            ],
            [
                'key' => 'status',
                'label' => 'Aktywny',
                'type' => 'select',
                'options' => [
                    '' => '- aktywny -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
        ];

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

        // Historycznie lista banerow domyslnie byla sortowana rosnaco po nazwie.
        $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'];
            $name = (string)($item['name'] ?? '');
            $homePage = (int)($item['home_page'] ?? 0);
            $isActive = (int)($item['status'] ?? 0) === 1;
            $thumbnailSrc = trim((string)($item['thumbnail_src'] ?? ''));
            if ($thumbnailSrc !== '' && !preg_match('#^(https?:)?//#i', $thumbnailSrc) && strpos($thumbnailSrc, '/') !== 0) {
                $thumbnailSrc = '/' . ltrim($thumbnailSrc, '/');
            }

            $thumbnail = '<span class="text-muted">-</span>';
            if ($thumbnailSrc !== '') {
                $thumbnail = '<div class="banner-thumb-wrap">'
                    . '<img src="' . htmlspecialchars($thumbnailSrc, ENT_QUOTES, 'UTF-8') . '" alt="" '
                    . 'data-preview-src="' . htmlspecialchars($thumbnailSrc, ENT_QUOTES, 'UTF-8') . '" '
                    . 'class="banner-thumb-image js-banner-thumb-preview" '
                    . 'loading="lazy">'
                    . '</div>';
            }

            $rows[] = [
                'lp' => $lp++ . '.',
                'thumbnail' => $thumbnail,
                'name' => '<a href="/admin/banners/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'status' => $isActive ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                'home_page' => $homePage === 1 ? '<span class="text-system">tak</span>' : 'nie',
                'slider' => $homePage === 1 ? 'nie' : '<span class="text-system">tak</span>',
                'date_start' => !empty($item['date_start']) ? date('Y-m-d', strtotime((string)$item['date_start'])) : '-',
                'date_end' => !empty($item['date_end']) ? date('Y-m-d', strtotime((string)$item['date_end'])) : '-',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/banners/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/banners/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrany element?',
                    ],
                ],
            ];
        }

        $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' => 'thumbnail', 'label' => 'Miniatura', 'class' => 'text-center', 'sortable' => false, 'raw' => true],
                ['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'status', 'sort_key' => 'status', 'label' => 'Aktywny', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'home_page', 'sort_key' => 'home_page', 'label' => 'Strona glowna', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'slider', 'label' => 'Slajder', 'class' => 'text-center', 'sortable' => false, 'raw' => true],
                ['key' => 'date_start', 'sort_key' => 'date_start', 'label' => 'Data rozpoczecia', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'date_end', 'sort_key' => 'date_end', 'label' => 'Data zakonczenia', 'class' => 'text-center', 'sortable' => 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/banners/list/',
            'Brak danych w tabeli.',
            '/admin/banners/edit/',
            'Dodaj baner',
            'banners/banners-list-custom-script'
        );

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

    /**
     * Edycja banera
     */
    public function edit(): string
    {
        $bannerId = (int)\Shared\Helpers\Helpers::get('id');
        $banner = $this->repository->find($bannerId);
        $languages = $this->languagesRepository->languagesList();

        // Sprawdź czy są błędy walidacji z poprzedniego requestu
        $validationErrors = $_SESSION['form_errors'][$this->getFormId()] ?? null;
        if ($validationErrors) {
            unset($_SESSION['form_errors'][$this->getFormId()]);
        }

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

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

    /**
     * Zapisanie banera (AJAX)
     */
    public function save(): void
    {
        $response = ['success' => false, 'errors' => []];

        $bannerId = (int)\Shared\Helpers\Helpers::get('id');
        $banner = $this->repository->find($bannerId);
        $languages = $this->languagesRepository->languagesList();
        
        $viewModel = $this->buildFormViewModel($banner, $languages);
        
        // Przetwórz dane z POST
        $result = $this->formHandler->handleSubmit($viewModel, $_POST);
        
        if (!$result['success']) {
            // Zapisz błędy w sesji i zwróć jako JSON
            $_SESSION['form_errors'][$this->getFormId()] = $result['errors'];
            $response['errors'] = $result['errors'];
            echo json_encode($response);
            exit;
        }
        
        // Zapisz dane
        $data = $result['data'];
        $data['id'] = $bannerId ?: null;
        
        $savedId = $this->repository->save($data);
        
        if ($savedId) {
            $response = [
                'success' => true, 
                'id' => $savedId,
                'message' => 'Baner został zapisany.'
            ];
        } else {
            $response['errors'] = ['general' => 'Błąd podczas zapisywania do bazy.'];
        }

        echo json_encode($response);
        exit;
    }

    /**
     * Usuniecie banera
     */
    public function delete(): void
    {
        $bannerId = (int)\Shared\Helpers\Helpers::get('id');
        if ($this->repository->delete($bannerId)) {
            \Shared\Helpers\Helpers::delete_dir('../temp/');
            \Shared\Helpers\Helpers::alert('Baner zostal usuniety.');
        }

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

    /**
     * Buduje model widoku formularza
     */
    private function buildFormViewModel(array $banner, array $languages, ?array $errors = null): FormEditViewModel
    {
        $bannerId = $banner['id'] ?? 0;
        $isNew = empty($bannerId);
        
        // Domyślne wartości dla nowego banera
        if ($isNew) {
            $banner['status'] = 1;
            $banner['home_page'] = 0;
        }

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

        $fields = [
            // Zakładka Ustawienia
            FormField::text('name', [
                'label' => 'Nazwa',
                'tab' => 'settings',
                'required' => true,
            ]),
            FormField::switch('status', [
                'label' => 'Aktywny',
                'tab' => 'settings',
                'value' => ($banner['status'] ?? 1) == 1,
            ]),
            FormField::date('date_start', [
                'label' => 'Data rozpoczęcia',
                'tab' => 'settings',
            ]),
            FormField::date('date_end', [
                'label' => 'Data zakończenia',
                'tab' => 'settings',
            ]),
            FormField::switch('home_page', [
                'label' => 'Slajder / Strona główna',
                'tab' => 'settings',
                'value' => ($banner['home_page'] ?? 0) == 1,
            ]),

            // Sekcja językowa w zakładce Zawartość
            FormField::langSection('translations', 'content', [
                FormField::image('src', [
                    'label' => 'Obraz',
                    'filemanager' => true,
                ]),
                FormField::text('url', [
                    'label' => 'Url',
                ]),
                FormField::textarea('html', [
                    'label' => 'Kod HTML',
                    'rows' => 6,
                ]),
                FormField::editor('text', [
                    'label' => 'Treść',
                    'toolbar' => 'MyTool',
                    'height' => 300,
                ]),
            ]),
        ];

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

        return new FormEditViewModel(
            $this->getFormId(),
            $isNew ? 'Nowy baner' : 'Edycja banera',
            $banner,
            $fields,
            $tabs,
            $actions,
            'POST',
            '/admin/banners/save/' . ($isNew ? '' : 'id=' . $bannerId),
            '/admin/banners/list/',
            true,
            ['id' => $bannerId],
            $languages,
            $errors
        );
    }

    /**
     * Zwraca identyfikator formularza
     */
    private function getFormId(): string
    {
        return 'banner-edit';
    }
}
