<?php
namespace admin\Controllers;

use Domain\Coupon\CouponRepository;
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 ShopCouponController
{
    private CouponRepository $repository;

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

    public function list(): string
    {
        $sortableColumns = ['id', 'status', 'used_count', 'name', 'type', 'amount', 'one_time', 'send', 'used', 'date_used'];
        $filterDefinitions = [
            [
                'key' => 'name',
                'label' => 'Nazwa',
                'type' => 'text',
            ],
            [
                'key' => 'status',
                'label' => 'Aktywny',
                'type' => 'select',
                'options' => [
                    '' => '- aktywny -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
            [
                'key' => 'used',
                'label' => 'Uzyty',
                'type' => 'select',
                'options' => [
                    '' => '- uzyty -',
                    '1' => 'tak',
                    '0' => 'nie',
                ],
            ],
            [
                'key' => 'send',
                'label' => 'Wyslany',
                'type' => 'select',
                'options' => [
                    '' => '- wyslany -',
                    '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);
            $used = (int)($item['used'] ?? 0);
            $send = (int)($item['send'] ?? 0);
            $oneTime = (int)($item['one_time'] ?? 0);
            $type = (int)($item['type'] ?? 0);
            $amount = (string)($item['amount'] ?? '');
            $dateUsed = trim((string)($item['date_used'] ?? ''));

            $rows[] = [
                'lp' => $lp++ . '.',
                'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                'used_count' => (int)($item['used_count'] ?? 0),
                'name' => '<a href="/admin/shop_coupon/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'type' => htmlspecialchars((string)($type === 1 ? 'Rabat procentowy na koszyk' : '-'), ENT_QUOTES, 'UTF-8'),
                'amount' => $type === 1 && $amount !== '' ? htmlspecialchars($amount, ENT_QUOTES, 'UTF-8') . '%' : '-',
                'one_time' => $oneTime === 1 ? 'tak' : 'nie',
                'send' => $send === 1 ? 'tak' : 'nie',
                'used' => $used === 1 ? 'tak' : 'nie',
                'date_used' => $dateUsed !== '' ? htmlspecialchars($dateUsed, ENT_QUOTES, 'UTF-8') : '-',
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/shop_coupon/edit/id=' . $id,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                    [
                        'label' => 'Usun',
                        'url' => '/admin/shop_coupon/delete/id=' . $id,
                        'class' => 'btn btn-xs btn-danger',
                        'confirm' => 'Na pewno chcesz usunac wybrany kupon?',
                        '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' => 'used_count', 'sort_key' => 'used_count', 'label' => 'Uzyto X razy', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'type', 'sort_key' => 'type', 'label' => 'Typ kuponu', 'sortable' => true],
                ['key' => 'amount', 'sort_key' => 'amount', 'label' => 'Wartosc', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'one_time', 'sort_key' => 'one_time', 'label' => 'Kupon jednorazowy', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'send', 'sort_key' => 'send', 'label' => 'Wyslany', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'used', 'sort_key' => 'used', 'label' => 'Uzyty', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'date_used', 'sort_key' => 'date_used', 'label' => 'Data uzycia', '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_coupon/list/',
            'Brak danych w tabeli.',
            '/admin/shop_coupon/edit/',
            'Dodaj kupon'
        );

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

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

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

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

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

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

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

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

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

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

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

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

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

        $data = [
            'id' => $id,
            'name' => (string)($coupon['name'] ?? ''),
            'send' => (int)($coupon['send'] ?? 0),
            'status' => (int)($coupon['status'] ?? 1),
            'used' => (int)($coupon['used'] ?? 0),
            'type' => (int)($coupon['type'] ?? 1),
            'amount' => (string)($coupon['amount'] ?? ''),
            'one_time' => (int)($coupon['one_time'] ?? 1),
            'include_discounted_product' => (int)($coupon['include_discounted_product'] ?? 0),
        ];

        $fields = [
            FormField::hidden('id', $id),
            FormField::text('name', [
                'label' => 'Nazwa',
                'tab' => 'settings',
                'required' => true,
            ]),
            FormField::switch('send', [
                'label' => 'Wyslany',
                'tab' => 'settings',
            ]),
            FormField::switch('status', [
                'label' => 'Aktywny',
                'tab' => 'settings',
                'value' => true,
            ]),
            FormField::switch('used', [
                'label' => 'Uzyty',
                'tab' => 'settings',
            ]),
            FormField::select('type', [
                'label' => 'Typ kuponu',
                'tab' => 'settings',
                'options' => [
                    1 => 'Rabat procentowy na koszyk',
                ],
                'required' => true,
            ]),
            FormField::text('amount', [
                'label' => 'Wartosc',
                'tab' => 'settings',
                'attributes' => ['class' => 'number-format'],
            ]),
            FormField::switch('one_time', [
                'label' => 'Kupon jednorazowy',
                'tab' => 'settings',
                'value' => true,
            ]),
            FormField::switch('include_discounted_product', [
                'label' => 'Dotyczy rowniez produktow przecenionych',
                'tab' => 'settings',
            ]),
            FormField::custom('coupon_categories', \Shared\Tpl\Tpl::view('shop-coupon/coupon-categories-selector', [
                'label' => 'Ogranicz promocje do wybranych kategorii',
                'inputName' => 'categories[]',
                'categories' => $categories,
                'selectedIds' => is_array($coupon['categories'] ?? null) ? $coupon['categories'] : [],
            ]), [
                'tab' => 'categories',
            ]),
        ];

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

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

        return new FormEditViewModel(
            'shop-coupon-edit',
            $isNew ? 'Nowy kupon' : ('Edycja kuponu: ' . (string)($coupon['name'] ?? '')),
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/shop_coupon/list/',
            true,
            ['id' => $id]
        );
    }
}
