<?php
namespace admin\Controllers;

use Domain\Producer\ProducerRepository;
use Domain\Languages\LanguagesRepository;
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 ShopProducerController
{
    private ProducerRepository $repository;
    private LanguagesRepository $languagesRepository;
    private FormRequestHandler $formHandler;

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

    public function list(): string
    {
        $sortableColumns = ['id', 'name', 'status'];
        $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'
        );

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

            $imgHtml = '';
            if ($img !== '') {
                $imgHtml = '<img src="' . htmlspecialchars($img, ENT_QUOTES, 'UTF-8') . '" style="max-height:30px;" />';
            }

            $rows[] = [
                'lp' => $lp++ . '.',
                'name' => '<a href="/admin/shop_producer/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'img' => $imgHtml,
                'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/shop_producer/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/shop_producer/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybranego producenta?',
                        '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' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'img', 'label' => 'Logo', 'sortable' => false, 'raw' => true],
                ['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/shop_producer/list/',
            'Brak danych w tabeli.',
            '/admin/shop_producer/edit/',
            'Dodaj producenta'
        );

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

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

    public function edit(): string
    {
        $producer = $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('shop-producer/producer-edit', [
            'form' => $this->buildFormViewModel($producer, $languages, $validationErrors),
        ]);
    }

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

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

            if (is_array($values)) {
                $langs = $this->languagesRepository->languagesList(true);

                $id = $this->repository->save(
                    (int)($values['id'] ?? 0),
                    (string)($values['name'] ?? ''),
                    $this->toSwitchValue($values['status'] ?? 0),
                    $values['img'] ?? null,
                    $values['description'] ?? [],
                    $values['data'] ?? [],
                    $values['meta_title'] ?? [],
                    $langs
                );

                if (!empty($id)) {
                    \Shared\Helpers\Helpers::htacces();
                    \Shared\Helpers\Helpers::delete_dir('../temp/');
                    $response = [
                        'status' => 'ok',
                        'msg' => 'Producent zostal zapisany.',
                        'id' => (int)$id,
                    ];
                }
            }

            echo json_encode($response);
            exit;
        }

        // Nowy flow (form-edit)
        $producer = $this->repository->find((int)\Shared\Helpers\Helpers::get('id'));
        $languages = $this->languagesRepository->languagesList();
        $form = $this->buildFormViewModel($producer, $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'];
        $langs = $this->languagesRepository->languagesList(true);

        $translations = $data['translations'] ?? [];
        $description = [];
        $metaData = [];
        $metaTitle = [];
        foreach ($translations as $langId => $fields) {
            $description[$langId] = $fields['description'] ?? null;
            $metaData[$langId] = $fields['data'] ?? null;
            $metaTitle[$langId] = $fields['meta_title'] ?? null;
        }

        $savedId = $this->repository->save(
            (int)($data['id'] ?? 0),
            (string)($data['name'] ?? ''),
            $this->toSwitchValue($data['status'] ?? 0),
            $data['img'] ?? null,
            $description,
            $metaData,
            $metaTitle,
            $langs
        );

        if ($savedId) {
            \Shared\Helpers\Helpers::htacces();
            \Shared\Helpers\Helpers::delete_dir('../temp/');
            echo json_encode([
                'success' => true,
                'id' => $savedId,
                'message' => 'Producent zostal zapisany.',
            ]);
            exit;
        }

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

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

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

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

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

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

        $data = [
            'id' => $id,
            'name' => (string)($producer['name'] ?? ''),
            'status' => (int)($producer['status'] ?? 1),
            'img' => $producer['img'] ?? null,
            'languages' => is_array($producer['languages'] ?? null) ? $producer['languages'] : [],
        ];

        $fields = [
            FormField::hidden('id', $id),
            FormField::text('name', [
                'label' => 'Nazwa',
                'required' => true,
                'tab' => 'general',
            ]),
            FormField::switch('status', [
                'label' => 'Aktywny',
                'tab' => 'general',
                'value' => true,
            ]),
            FormField::image('img', [
                'label' => 'Logo',
                'tab' => 'general',
            ]),
            FormField::langSection('translations', 'description', [
                FormField::editor('description', [
                    'label' => 'Opis',
                    'height' => 250,
                ]),
                FormField::editor('data', [
                    'label' => 'Dane producenta',
                    'height' => 250,
                ]),
            ]),
            FormField::langSection('translations', 'seo', [
                FormField::text('meta_title', [
                    'label' => 'Meta title',
                ]),
            ]),
        ];

        $tabs = [
            new FormTab('general', 'Ogolne', 'fa-file'),
            new FormTab('description', 'Opis', 'fa-file'),
            new FormTab('seo', 'SEO', 'fa-globe'),
        ];

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

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

    private function formId(): string
    {
        return 'shop-producer-edit';
    }

    private function toSwitchValue($value): int
    {
        if (is_bool($value)) {
            return $value ? 1 : 0;
        }

        if (is_numeric($value)) {
            return ((int)$value) === 1 ? 1 : 0;
        }

        if (is_string($value)) {
            $normalized = strtolower(trim($value));
            return in_array($normalized, ['1', 'on', 'true', 'yes'], true) ? 1 : 0;
        }

        return 0;
    }
}
