<?php
namespace admin\Controllers;

use Domain\Product\ProductRepository;

class ProductArchiveController
{
    private ProductRepository $productRepository;

    public function __construct(ProductRepository $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function list(): string
    {
        $sortableColumns = ['id', 'name', 'price_brutto', 'price_brutto_promo', 'quantity'];

        $filterDefinitions = [
            [
                'key' => 'phrase',
                'label' => 'Nazwa / EAN / SKU',
                'type' => 'text',
            ],
        ];

        $listRequest = \admin\Support\TableListRequestFactory::fromRequest(
            $filterDefinitions,
            $sortableColumns,
            'id',
            [10, 15, 25, 50, 100],
            10
        );

        $result = $this->productRepository->listArchivedForAdmin(
            $listRequest['filters'],
            $listRequest['sortColumn'],
            $listRequest['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'] ?? ''));
            $sku = trim((string)($item['sku'] ?? ''));
            $ean = trim((string)($item['ean'] ?? ''));
            $imageSrc = trim((string)($item['image_src'] ?? ''));
            $imageAlt = trim((string)($item['image_alt'] ?? ''));
            $priceBrutto = (string)($item['price_brutto'] ?? '');
            $priceBruttoPromo = (string)($item['price_brutto_promo'] ?? '');
            $quantity = (int)($item['quantity'] ?? 0);
            $combinations = (int)($item['combinations'] ?? 0);

            if ($imageSrc === '') {
                $imageSrc = '/admin/layout/images/no-image.png';
            } elseif (!preg_match('#^(https?:)?//#i', $imageSrc) && strpos($imageSrc, '/') !== 0) {
                $imageSrc = '/' . ltrim($imageSrc, '/');
            }

            $categories = trim((string)$this->productRepository->productCategoriesText($id));
            $categoriesHtml = '';
            if ($categories !== '') {
                $categoriesHtml = '<small class="text-muted product-categories">'
                    . htmlspecialchars($categories, ENT_QUOTES, 'UTF-8')
                    . '</small>';
            }

            $skuEanParts = [];
            if ($sku !== '') {
                $skuEanParts[] = 'SKU: ' . htmlspecialchars($sku, ENT_QUOTES, 'UTF-8');
            }
            if ($ean !== '') {
                $skuEanParts[] = 'EAN: ' . htmlspecialchars($ean, ENT_QUOTES, 'UTF-8');
            }
            $skuEanHtml = '';
            if (!empty($skuEanParts)) {
                $skuEanHtml = '<small class="text-muted product-categories">' . implode(', ', $skuEanParts) . '</small>';
            }

            $productCell = '<div class="product-image product-archive-thumb-wrap">'
                . '<img src="' . htmlspecialchars($imageSrc, ENT_QUOTES, 'UTF-8') . '" alt="' . htmlspecialchars($imageAlt, ENT_QUOTES, 'UTF-8') . '" '
                . 'data-preview-src="' . htmlspecialchars($imageSrc, ENT_QUOTES, 'UTF-8') . '" '
                . 'class="img-responsive product-archive-thumb-image js-product-archive-thumb-preview" loading="lazy">'
                . '</div>'
                . '<div class="product-name">'
                . '<a href="/admin/shop_product/product_edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>'
                . '</div>'
                . $categoriesHtml
                . $skuEanHtml;

            $rows[] = [
                'lp' => $lp++ . '.',
                'product' => $productCell,
                'price_brutto' => $priceBrutto !== '' ? $priceBrutto : '-',
                'price_brutto_promo' => $priceBruttoPromo !== '' ? $priceBruttoPromo : '-',
                'quantity' => (string)$quantity,
                '_actions' => [
                    [
                        'label' => 'Przywroc',
                        'url' => '/admin/product_archive/unarchive/product_id=' . $id,
                        'class' => 'btn btn-xs btn-success',
                        'confirm' => 'Na pewno chcesz przywrocic wybrany produkt z archiwum?',
                        'confirm_ok' => 'Przywroc',
                        'confirm_cancel' => 'Anuluj',
                    ],
                    [
                        'label' => 'Usun trwale',
                        'url' => '/admin/product_archive/delete_permanent/product_id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'UWAGA! Operacja nieodwracalna!' . "\n\n" . 'Produkt "' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '" zostanie trwale usuniety razem ze wszystkimi zdjeciami i zalacznikami z serwera.' . "\n\n" . 'Czy na pewno chcesz usunac ten produkt?',
                        'confirm_ok' => 'Tak, usun trwale',
                        'confirm_cancel' => 'Anuluj',
                    ],
                ],
            ];
        }

        $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' => 'product', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'price_brutto', 'sort_key' => 'price_brutto', 'label' => 'Cena', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'price_brutto_promo', 'sort_key' => 'price_brutto_promo', 'label' => 'Cena promocyjna', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'quantity', 'sort_key' => 'quantity', 'label' => 'Stan MG', 'class' => 'text-center', 'sortable' => true]
            ],
            $rows,
            $listRequest['viewFilters'],
            [
                'column' => $listRequest['sortColumn'],
                'dir' => $listRequest['sortDir'],
            ],
            [
                'page' => $listRequest['page'],
                'per_page' => $listRequest['perPage'],
                'total' => $total,
                'total_pages' => $totalPages,
            ],
            array_merge($listRequest['queryFilters'], [
                'sort' => $listRequest['sortColumn'],
                'dir' => $listRequest['sortDir'],
                'per_page' => $listRequest['perPage'],
            ]),
            $listRequest['perPageOptions'],
            $sortableColumns,
            '/admin/product_archive/list/',
            'Brak danych w tabeli.',
            null,
            null,
            'product-archive/products-list-custom-script'
        );

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

    public function unarchive(): void
    {
        if ( $this->productRepository->unarchive( (int) \Shared\Helpers\Helpers::get( 'product_id' ) ) )
            \Shared\Helpers\Helpers::alert( 'Produkt został przywrócony z archiwum.' );
        else
            \Shared\Helpers\Helpers::alert( 'Podczas przywracania produktu z archiwum wystąpił błąd. Proszę spróbować ponownie' );

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

    public function delete_permanent(): void
    {
        $productId = (int) \Shared\Helpers\Helpers::get( 'product_id' );

        if ( $productId <= 0 ) {
            \Shared\Helpers\Helpers::alert( 'Nieprawidłowe ID produktu.' );
            header( 'Location: /admin/product_archive/list/' );
            exit;
        }

        if ( $this->productRepository->delete( $productId ) ) {
            \Shared\Helpers\Helpers::set_message( 'Produkt został trwale usunięty wraz ze zdjęciami i załącznikami.' );
        } else {
            \Shared\Helpers\Helpers::alert( 'Podczas usuwania produktu wystąpił błąd. Proszę spróbować ponownie.' );
        }

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