<?php
namespace admin\Controllers;

use Domain\Promotion\PromotionRepository;
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 ShopPromotionController
{
    private PromotionRepository $repository;

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

    public function list(): string
    {
        $sortableColumns = ['id', 'name', 'status', 'condition_type', 'date_from', 'date_to'];
        $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,
            '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);
            $name = trim((string)($item['name'] ?? ''));
            $status = (int)($item['status'] ?? 0);
            $conditionType = (int)($item['condition_type'] ?? 0);
            $dateFrom = trim((string)($item['date_from'] ?? ''));
            $dateTo = trim((string)($item['date_to'] ?? ''));

            $rows[] = [
                'lp' => $lp++ . '.',
                'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                'name' => '<a href="/admin/shop_promotion/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'condition_type' => htmlspecialchars((string)(\Domain\Promotion\PromotionRepository::$condition_type[$conditionType] ?? '-'), ENT_QUOTES, 'UTF-8'),
                'date_from' => $dateFrom !== '' ? htmlspecialchars($dateFrom, ENT_QUOTES, 'UTF-8') : '-',
                'date_to' => $dateTo !== '' ? htmlspecialchars($dateTo, ENT_QUOTES, 'UTF-8') : '-',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/shop_promotion/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/shop_promotion/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrana promocje?',
                        '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' => 'status', 'sort_key' => 'status', 'label' => 'Aktywny', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'condition_type', 'sort_key' => 'condition_type', 'label' => 'Typ kuponu', 'sortable' => true],
                ['key' => 'date_from', 'sort_key' => 'date_from', 'label' => 'Data od', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'date_to', 'sort_key' => 'date_to', 'label' => 'Data do', '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_promotion/list/',
            'Brak danych w tabeli.',
            '/admin/shop_promotion/edit/',
            'Dodaj promocje'
        );

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

    public function edit(): string
    {
        $promotion = $this->repository->find((int)\Shared\Helpers\Helpers::get('id')) ?: [];
        $categories = $this->repository->categoriesTree(null);

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

    public function save(): void
    {
        $legacyValues = \Shared\Helpers\Helpers::get('values');

        if ($legacyValues) {
            $values = json_decode((string)$legacyValues, true);
            $response = [
                'status' => 'error',
                'msg' => 'Podczas zapisywania promocji wystapil blad. Prosze sprobowac ponownie.',
            ];

            if (is_array($values)) {
                $id = $this->repository->save($values);
                if (!empty($id)) {
                    $response = [
                        'status' => 'ok',
                        'msg' => 'Promocja zostala zapisana.',
                        '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;
            }
        }

        $id = $this->repository->save($payload);
        if (!empty($id)) {
            echo json_encode([
                'success' => true,
                'id' => (int)$id,
                'message' => 'Promocja zostala zapisana.',
            ]);
            exit;
        }

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

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

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

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

        $data = [
            'id' => $id,
            'name' => (string)($promotion['name'] ?? ''),
            'status' => (int)($promotion['status'] ?? 1),
            'include_coupon' => (int)($promotion['include_coupon'] ?? 0),
            'include_product_promo' => (int)($promotion['include_product_promo'] ?? 0),
            'condition_type' => (int)($promotion['condition_type'] ?? 1),
            'discount_type' => (int)($promotion['discount_type'] ?? 1),
            'min_product_count' => $promotion['min_product_count'] ?? '',
            'price_cheapest_product' => $promotion['price_cheapest_product'] ?? '',
            'amount' => $promotion['amount'] ?? '',
            'date_from' => (string)($promotion['date_from'] ?? ''),
            'date_to' => (string)($promotion['date_to'] ?? ''),
        ];

        $fields = [
            FormField::hidden('id', $id),
            FormField::text('name', [
                'label' => 'Nazwa',
                'tab' => 'settings',
                'required' => true,
            ]),
            FormField::switch('status', [
                'label' => 'Aktywna',
                'tab' => 'settings',
                'value' => true,
            ]),
            FormField::switch('include_coupon', [
                'label' => 'Lacz z kuponami rabatowymi',
                'tab' => 'settings',
            ]),
            FormField::switch('include_product_promo', [
                'label' => 'Uwzglednij produkty przecenione',
                'tab' => 'settings',
            ]),
            FormField::select('condition_type', [
                'label' => 'Warunki promocji',
                'tab' => 'settings',
                'options' => \Domain\Promotion\PromotionRepository::$condition_type,
                'required' => true,
            ]),
            FormField::select('discount_type', [
                'label' => 'Typ rabatu',
                'tab' => 'settings',
                'options' => \Domain\Promotion\PromotionRepository::$discount_type,
                'required' => true,
            ]),
            FormField::text('min_product_count', [
                'label' => 'Min. ilosc produktow z danej kategorii',
                'tab' => 'settings',
                'attributes' => ['class' => 'int-format'],
            ]),
            FormField::text('price_cheapest_product', [
                'label' => 'Cena najtanszego produktu',
                'tab' => 'settings',
                'attributes' => ['class' => 'number-format'],
            ]),
            FormField::text('amount', [
                'label' => 'Wartosc',
                'tab' => 'settings',
                'attributes' => ['class' => 'number-format'],
            ]),
            FormField::date('date_from', [
                'label' => 'Data od',
                'tab' => 'settings',
            ]),
            FormField::date('date_to', [
                'label' => 'Data do',
                'tab' => 'settings',
            ]),
            FormField::custom('categories_group_1', \Shared\Tpl\Tpl::view('shop-promotion/promotion-categories-selector', [
                'label' => 'Kategorie grupa I',
                'inputName' => 'categories[]',
                'categories' => $categories,
                'selectedIds' => is_array($promotion['categories'] ?? null) ? $promotion['categories'] : [],
            ]), [
                'tab' => 'categories',
            ]),
            FormField::custom('categories_group_2', \Shared\Tpl\Tpl::view('shop-promotion/promotion-categories-selector', [
                'label' => 'Kategorie grupa II',
                'inputName' => 'condition_categories[]',
                'categories' => $categories,
                'selectedIds' => is_array($promotion['condition_categories'] ?? null) ? $promotion['condition_categories'] : [],
            ]), [
                'tab' => 'categories',
            ]),
        ];

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

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

        return new FormEditViewModel(
            'shop-promotion-edit',
            $isNew ? 'Nowa promocja' : ('Edycja promocji: ' . (string)($promotion['name'] ?? '')),
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/shop_promotion/list/',
            true,
            ['id' => $id]
        );
    }
}

