<?php
namespace admin\Controllers;

use Domain\ProductSet\ProductSetRepository;
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;

class ShopProductSetsController
{
    private ProductSetRepository $repository;

    public function __construct(ProductSetRepository $repository)
    {
        $this->repository = $repository;
    }

    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);

            $rows[] = [
                'lp' => $lp++ . '.',
                'name' => '<a href="/admin/shop_product_sets/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/shop_product_sets/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/shop_product_sets/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrany komplet produktow?',
                        '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' => '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_product_sets/list/',
            'Brak danych w tabeli.',
            '/admin/shop_product_sets/edit/',
            'Dodaj komplet produktow'
        );

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

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

    public function edit(): string
    {
        $set = $this->repository->find((int)\Shared\Helpers\Helpers::get('id'));
        $products = $this->repository->allProductsMap();

        return \Shared\Tpl\Tpl::view('shop-product-sets/product-set-edit', [
            'form' => $this->buildFormViewModel($set, $products),
        ]);
    }

    public function set_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 kompletu produktow wystapil blad. Prosze sprobowac ponownie.',
            ];

            if (is_array($values)) {
                $productIds = $values['set_products_id'] ?? [];
                if (!is_array($productIds)) {
                    $productIds = $productIds ? [$productIds] : [];
                }

                $id = $this->repository->save(
                    (int)($values['id'] ?? 0),
                    (string)($values['name'] ?? ''),
                    $this->toSwitchValue($values['status'] ?? 0),
                    $productIds
                );

                if (!empty($id)) {
                    $response = [
                        'status' => 'ok',
                        'msg' => 'Komplet produktow zostal zapisany.',
                        'id' => (int)$id,
                    ];
                }
            }

            echo json_encode($response);
            exit;
        }

        $payload = $_POST;
        if (empty($payload['id'])) {
            $routeId = (int)\Shared\Helpers\Helpers::get('id');
            if ($routeId > 0) {
                $payload['id'] = $routeId;
            }
        }

        $productIds = $payload['set_products_id'] ?? [];
        if (!is_array($productIds)) {
            $productIds = $productIds ? [$productIds] : [];
        }

        $id = $this->repository->save(
            (int)($payload['id'] ?? 0),
            (string)($payload['name'] ?? ''),
            $this->toSwitchValue($payload['status'] ?? 0),
            $productIds
        );

        if (!empty($id)) {
            echo json_encode([
                'success' => true,
                'id' => (int)$id,
                'message' => 'Komplet produktow zostal zapisany.',
            ]);
            exit;
        }

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

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

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

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

    private function buildFormViewModel(array $set, array $products = []): FormEditViewModel
    {
        $id = (int)($set['id'] ?? 0);
        $isNew = $id <= 0;
        $selectedProducts = $set['products'] ?? [];

        $data = [
            'id' => $id,
            'name' => (string)($set['name'] ?? ''),
            'status' => (int)($set['status'] ?? 1),
        ];

        $productsSelectHtml = $this->renderProductsSelect($products, $selectedProducts);

        $fields = [
            FormField::hidden('id', $id),
            FormField::text('name', [
                'label' => 'Nazwa',
                'tab' => 'settings',
                'required' => true,
            ]),
            FormField::switch('status', [
                'label' => 'Aktywny',
                'tab' => 'settings',
                'value' => true,
            ]),
            FormField::custom('set_products', $productsSelectHtml, [
                'tab' => 'settings',
            ]),
        ];

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

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

        return new FormEditViewModel(
            'shop-product-set-edit',
            $isNew ? 'Nowy komplet produktow' : ('Edycja kompletu produktow: ' . (string)($set['name'] ?? '')),
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/shop_product_sets/list/',
            true,
            ['id' => $id]
        );
    }

    private function toSwitchValue($value): int
    {
        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;
    }

    private function renderProductsSelect(array $products, array $selectedProducts): string
    {
        $html = '<div class="form-group row">';
        $html .= '<label class="col-lg-4 control-label">Produkty do kompletu:</label>';
        $html .= '<div class="col-lg-8">';
        $html .= '<select id="set_products_id" multiple name="set_products_id[]" placeholder="produkty do kompletu">';
        $html .= '<option value="">wybierz produkt...</option>';

        foreach ($products as $productId => $productName) {
            $pid = (int)$productId;
            $selected = in_array($pid, $selectedProducts, true) ? ' selected' : '';
            $html .= '<option value="' . $pid . '"' . $selected . '>'
                . htmlspecialchars((string)$productName, ENT_QUOTES, 'UTF-8')
                . '</option>';
        }

        $html .= '</select>';
        $html .= '</div>';
        $html .= '</div>';

        return $html;
    }
}
