<?php
namespace admin\Controllers;

use Domain\Client\ClientRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;

class ShopClientsController
{
    private ClientRepository $repository;

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

    public function list(): string
    {
        $sortableColumns = [
            'client_name',
            'client_surname',
            'client_email',
            'client_phone',
            'client_city',
            'total_orders',
            'total_spent',
            'client_type',
        ];

        $filterDefinitions = [
            [
                'key' => 'name',
                'label' => 'Imie',
                'type' => 'text',
            ],
            [
                'key' => 'surname',
                'label' => 'Nazwisko',
                'type' => 'text',
            ],
            [
                'key' => 'email',
                'label' => 'E-mail',
                'type' => 'text',
            ],
            [
                'key' => 'client_type',
                'label' => 'Typ klienta',
                'type' => 'select',
                'options' => [
                    '' => '- typ klienta -',
                    'registered' => 'Zarejestrowany',
                    'guest' => 'Gosc',
                ],
            ],
        ];

        $listRequest = \admin\Support\TableListRequestFactory::fromRequest(
            $filterDefinitions,
            $sortableColumns,
            'client_surname'
        );

        $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) {
            $name = trim((string)($item['client_name'] ?? ''));
            $surname = trim((string)($item['client_surname'] ?? ''));
            $email = trim((string)($item['client_email'] ?? ''));
            $params = [
                'name' => $name,
                'surname' => $surname,
                'email' => $email,
            ];
            $detailsUrl = '/admin/shop_clients/details/?' . http_build_query($params);

            $rows[] = [
                'lp' => $lp++ . '.',
                'client_type' => ((int)($item['is_registered'] ?? 0) === 1) ? 'Zarejestrowany' : 'Gosc',
                'full_name' => htmlspecialchars($surname, ENT_QUOTES, 'UTF-8') . ' ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8'),
                'client_email' => $email,
                'client_phone' => (string)($item['client_phone'] ?? ''),
                'client_city' => (string)($item['client_city'] ?? ''),
                'total_spent' => number_format((float)($item['total_spent'] ?? 0), 2, '.', ' ') . ' zl',
                'total_orders' => '<a href="' . htmlspecialchars($detailsUrl, ENT_QUOTES, 'UTF-8') . '">' . (int)($item['total_orders'] ?? 0) . '</a>',
                '_actions' => [
                    [
                        'label' => 'Zobacz zamowienia',
                        'url' => $detailsUrl,
                        'class' => 'btn btn-xs btn-primary',
                    ],
                ],
            ];
        }

        $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' => 'client_type', 'sort_key' => 'client_type', 'label' => 'Typ klienta', 'class' => 'text-center', 'sortable' => true],
                ['key' => 'full_name', 'label' => 'Nazwisko, imie', 'sortable' => false, 'raw' => true],
                ['key' => 'client_email', 'sort_key' => 'client_email', 'label' => 'Email', 'sortable' => true],
                ['key' => 'client_phone', 'sort_key' => 'client_phone', 'label' => 'Telefon', 'sortable' => true],
                ['key' => 'client_city', 'sort_key' => 'client_city', 'label' => 'Miasto', 'sortable' => true],
                ['key' => 'total_spent', 'sort_key' => 'total_spent', 'label' => 'Wartosc zamowien', 'class' => 'text-right', 'sortable' => true],
                ['key' => 'total_orders', 'sort_key' => 'total_orders', 'label' => 'Ilosc zamowien', '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_clients/list/',
            'Brak danych w tabeli.'
        );

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

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

    public function details(): string
    {
        $name = (string)\Shared\Helpers\Helpers::get('name');
        $surname = (string)\Shared\Helpers\Helpers::get('surname');
        $email = (string)\Shared\Helpers\Helpers::get('email');

        $ordersInfo = $this->repository->ordersForClient($name, $surname, $email);
        $totals = $this->repository->totalsForClient($name, $surname, $email);

        $rows = [];
        $lp = 1;
        foreach ($ordersInfo as $order) {
            $rows[] = [
                'lp' => $lp++ . '.',
                'date_order' => (string)($order['date_order'] ?? ''),
                'summary' => number_format((float)($order['summary'] ?? 0), 2, '.', ' ') . ' zl',
                'payment_method' => (string)($order['payment_method'] ?? ''),
                'transport' => (string)($order['transport'] ?? ''),
                'message' => (string)($order['message'] ?? ''),
                '_actions' => [],
            ];
        }

        $ordersTable = new PaginatedTableViewModel(
            [
                ['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'date_order', 'label' => 'Data zamowienia', 'class' => 'text-center', 'sortable' => false],
                ['key' => 'summary', 'label' => 'Wartosc', 'class' => 'text-right', 'sortable' => false],
                ['key' => 'payment_method', 'label' => 'Typ platnosci', 'sortable' => false],
                ['key' => 'transport', 'label' => 'Rodzaj transportu', 'sortable' => false],
                ['key' => 'message', 'label' => 'Wiadomosc', 'sortable' => false],
            ],
            $rows,
            [],
            [],
            [
                'page' => 1,
                'per_page' => max(1, count($rows)),
                'total' => count($rows),
                'total_pages' => 1,
            ],
            [],
            [count($rows) > 0 ? count($rows) : 1],
            [],
            '/admin/shop_clients/details/?' . http_build_query([
                'name' => $name,
                'surname' => $surname,
                'email' => $email,
            ]),
            'Brak zamowien klienta.'
        );

        return \Shared\Tpl\Tpl::view('shop-clients/clients-details', [
            'name' => $name,
            'surname' => $surname,
            'email' => $email,
            'total_spent' => $totals['total_spent'],
            'ordersTable' => $ordersTable,
            'total_orders' => $totals['total_orders'],
        ]);
    }

    public function clients_details(): string
    {
        return $this->details();
    }
}
