<?php
namespace admin\Controllers;

use Domain\Transport\TransportRepository;
use Domain\PaymentMethod\PaymentMethodRepository;
use Domain\Integrations\IntegrationsRepository;
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 ShopTransportController
{
    private TransportRepository $transportRepository;
    private PaymentMethodRepository $paymentMethodRepository;

    public function __construct(
        TransportRepository $transportRepository,
        PaymentMethodRepository $paymentMethodRepository
    ) {
        $this->transportRepository = $transportRepository;
        $this->paymentMethodRepository = $paymentMethodRepository;
    }

    public function list(): string
    {
        $sortableColumns = ['id', 'name', 'status', 'cost', 'max_wp', 'default', 'o'];
        $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->transportRepository->listForAdmin(
            $listRequest['filters'],
            $listRequest['sortColumn'],
            $sortDir,
            $listRequest['page'],
            $listRequest['perPage']
        );

        $apiloCarrierAccounts = $this->getApiloCarrierAccounts();

        $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);
            $cost = (float)($item['cost'] ?? 0.0);
            $maxWp = $item['max_wp'] ?? null;
            $default = (int)($item['default'] ?? 0);
            $apiloCarrierAccountId = $item['apilo_carrier_account_id'] ?? null;

            $apiloLabel = '-';
            if ($apiloCarrierAccountId !== null) {
                $apiloKey = (string)$apiloCarrierAccountId;
                if (isset($apiloCarrierAccounts[$apiloKey])) {
                    $apiloLabel = $apiloCarrierAccounts[$apiloKey];
                }
            }

            $rows[] = [
                'lp' => $lp++ . '.',
                'default' => $default === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
                'cost' => \Shared\Helpers\Helpers::decimal($cost) . ' zł',
                'max_wp' => $maxWp !== null ? (int)$maxWp : '-',
                'name' => '<a href="/admin/shop_transport/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
                'apilo_carrier' => htmlspecialchars((string)$apiloLabel, ENT_QUOTES, 'UTF-8'),
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/shop_transport/edit/id=' . $id,
                        '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' => 'default', 'sort_key' => 'default', 'label' => 'Domyślna FT', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'status', 'sort_key' => 'status', 'label' => 'Aktywny', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'cost', 'sort_key' => 'cost', 'label' => 'Koszt', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'max_wp', 'sort_key' => 'max_wp', 'label' => 'Maks. WP', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
                ['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
                ['key' => 'apilo_carrier', 'label' => 'Typ kuriera Apilo', 'class' => 'text-center', 'sortable' => false],
            ],
            $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_transport/list/',
            'Brak danych w tabeli.'
        );

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

    public function edit(): string
    {
        $transport = $this->transportRepository->find((int)\Shared\Helpers\Helpers::get('id'));
        if ($transport === null) {
            \Shared\Helpers\Helpers::alert('Rodzaj transportu nie został znaleziony.');
            header('Location: /admin/shop_transport/list/');
            exit;
        }

        $paymentMethods = $this->paymentMethodRepository->allForAdmin();
        $apiloCarrierAccounts = $this->getApiloCarrierAccounts();

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

    public function save(): void
    {
        $payload = $_POST;
        $transportId = isset($payload['id']) && $payload['id'] !== ''
            ? (int)$payload['id']
            : (int)\Shared\Helpers\Helpers::get('id');

        $payload['id'] = $transportId;

        $id = $this->transportRepository->save($payload);
        if ($id !== null) {
            \Shared\Helpers\Helpers::delete_dir('../temp/');
            echo json_encode([
                'success' => true,
                'id' => (int)$id,
                'message' => 'Rodzaj transportu został zapisany.',
            ]);
            exit;
        }

        echo json_encode([
            'success' => false,
            'errors' => ['general' => 'Podczas zapisywania rodzaju transportu wystąpił błąd.'],
        ]);
        exit;
    }

    private function buildFormViewModel(
        array $transport,
        array $paymentMethods,
        array $apiloCarrierAccounts
    ): FormEditViewModel {
        $id = (int)($transport['id'] ?? 0);
        $name = (string)($transport['name'] ?? '');

        $apiloOptions = ['' => '--- wybierz konto przewoźnika ---'];
        foreach ($apiloCarrierAccounts as $carrierId => $carrierName) {
            $apiloOptions[(string)$carrierId] = $carrierName;
        }

        $data = [
            'id' => $id,
            'name' => $name,
            'name_visible' => (string)($transport['name_visible'] ?? ''),
            'description' => (string)($transport['description'] ?? ''),
            'cost' => (float)($transport['cost'] ?? 0.0),
            'max_wp' => $transport['max_wp'] ?? '',
            'default' => (int)($transport['default'] ?? 0),
            'status' => (int)($transport['status'] ?? 0),
            'delivery_free' => (int)($transport['delivery_free'] ?? 0),
            'apilo_carrier_account_id' => $transport['apilo_carrier_account_id'] ?? '',
        ];

        $fields = [
            FormField::hidden('id', $id),
            FormField::text('name', [
                'label' => 'Nazwa',
                'tab' => 'general',
                'readonly' => true,
                'required' => true,
            ]),
            FormField::text('name_visible', [
                'label' => 'Nazwa widoczna',
                'tab' => 'general',
            ]),
            FormField::text('description', [
                'label' => 'Opis',
                'tab' => 'general',
            ]),
            FormField::number('cost', [
                'label' => 'Koszt (PLN)',
                'tab' => 'general',
                'step' => 0.01,
                'required' => true,
            ]),
            FormField::number('max_wp', [
                'label' => 'Maks. WP',
                'tab' => 'general',
                'required' => true,
            ]),
            FormField::switch('default', [
                'label' => 'Domyślna forma dostawy',
                'tab' => 'general',
            ]),
            FormField::switch('status', [
                'label' => 'Aktywny',
                'tab' => 'general',
            ]),
            FormField::switch('delivery_free', [
                'label' => 'Darmowa dostawa',
                'tab' => 'general',
            ]),
            FormField::select('apilo_carrier_account_id', [
                'label' => 'Kurier z Apilo',
                'tab' => 'general',
                'options' => $apiloOptions,
            ]),
        ];

        $transportPaymentMethods = $transport['payment_methods'] ?? [];

        $paymentMethodsHtml = '';
        if (is_array($paymentMethods) && !empty($paymentMethods)) {
            foreach ($paymentMethods as $paymentMethod) {
                $pmId = (int)($paymentMethod['id'] ?? 0);
                $pmName = htmlspecialchars((string)($paymentMethod['name'] ?? ''), ENT_QUOTES, 'UTF-8');
                $pmStatus = (int)($paymentMethod['status'] ?? 0);
                $checked = in_array($pmId, $transportPaymentMethods) ? 'checked="checked"' : '';
                $statusClass = $pmStatus === 0 ? 'text-muted' : '';

                $paymentMethodsHtml .= '<div class="form-group">';
                $paymentMethodsHtml .= '<div class="col-lg-12">';
                $paymentMethodsHtml .= '<div class="list">';
                $paymentMethodsHtml .= '<input type="checkbox" class="g-checkbox" name="payment_methods[]" value="' . $pmId . '" ' . $checked . ' />';
                $paymentMethodsHtml .= '<span class="bold ' . $statusClass . '">' . $pmName . '</span>';
                $paymentMethodsHtml .= '</div>';
                $paymentMethodsHtml .= '</div>';
                $paymentMethodsHtml .= '</div>';
            }
        }

        $fields[] = FormField::custom(
            'payment_methods_section',
            $paymentMethodsHtml,
            ['tab' => 'payment_methods']
        );

        $tabs = [
            new FormTab('general', 'Ogólne', 'fa-file'),
            new FormTab('payment_methods', 'Powiązane metody płatności', 'fa-wrench'),
        ];

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

        return new FormEditViewModel(
            'shop-transport-edit',
            'Edycja rodzaju transportu: ' . $name,
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/shop_transport/list/',
            true,
            ['id' => $id]
        );
    }

    private function getApiloCarrierAccounts(): array
    {
        global $mdb;

        $integrationsRepository = new IntegrationsRepository( $mdb );
        $rawSetting = $integrationsRepository -> getSetting( 'apilo', 'carrier-account-list' );
        $raw = null;

        if (is_array($rawSetting)) {
            $raw = $rawSetting;
        } elseif (is_string($rawSetting)) {
            $decoded = @unserialize($rawSetting);
            if (is_array($decoded)) {
                $raw = $decoded;
            }
        }

        if (!is_array($raw)) {
            return [];
        }

        $list = [];
        foreach ($raw as $carrier) {
            if (is_array($carrier) && isset($carrier['id'], $carrier['name'])) {
                $list[(string)$carrier['id']] = (string)$carrier['name'];
            }
        }

        return $list;
    }
}
