<?php
namespace admin\Controllers;

use Domain\ShopStatus\ShopStatusRepository;
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 ShopStatusesController
{
    private ShopStatusRepository $repository;

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

    public function list(): string
    {
        $sortableColumns = ['id', 'status', 'color', 'o', 'apilo_status_id'];
        $filterDefinitions = [
            [
                'key' => 'status',
                'label' => 'Status',
                'type' => 'text',
            ],
        ];

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

        $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']
        );

        $apiloStatusList = $this->getApiloStatusList();

        $rows = [];
        $lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
        foreach ($result['items'] as $item) {
            $id = (int)($item['id'] ?? 0);
            $statusName = trim((string)($item['status'] ?? ''));
            $color = trim((string)($item['color'] ?? ''));
            $apiloStatusId = $item['apilo_status_id'] ?? null;

            $apiloStatusLabel = '';
            if ($apiloStatusId !== null && isset($apiloStatusList[$apiloStatusId])) {
                $apiloStatusLabel = $apiloStatusList[$apiloStatusId];
            }

            $colorHtml = $color !== ''
                ? '<span style="display:inline-block;width:20px;height:20px;background:' . htmlspecialchars($color, ENT_QUOTES, 'UTF-8') . ';border:1px solid #ccc;vertical-align:middle;margin-right:5px;"></span> ' . htmlspecialchars($color, ENT_QUOTES, 'UTF-8')
                : '-';

            $rows[] = [
                'lp' => $lp++ . '.',
                'status' => '<a href="/admin/shop_statuses/edit/id=' . $id . '">' . htmlspecialchars($statusName, ENT_QUOTES, 'UTF-8') . '</a>',
                'color' => $colorHtml,
                'apilo_status' => htmlspecialchars($apiloStatusLabel, ENT_QUOTES, 'UTF-8'),
                '_actions' => [
                    [
                        'label' => 'Edytuj',
                        'url' => '/admin/shop_statuses/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' => 'status', 'sort_key' => 'status', 'label' => 'Status', 'sortable' => true, 'raw' => true],
                ['key' => 'color', 'sort_key' => 'color', 'label' => 'Kolor', 'sortable' => true, 'raw' => true],
                ['key' => 'apilo_status', 'sort_key' => 'apilo_status_id', 'label' => 'Status Apilo', 'sortable' => 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_statuses/list/',
            'Brak danych w tabeli.'
        );

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

    public function edit(): string
    {
        $status = $this->repository->find((int)\Shared\Helpers\Helpers::get('id'));
        if ($status === null) {
            \Shared\Helpers\Helpers::alert('Status nie zostal znaleziony.');
            header('Location: /admin/shop_statuses/list/');
            exit;
        }

        $apiloStatusList = $this->getApiloStatusList();

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

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

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

            if (is_array($values)) {
                $statusId = (int)($values['id'] ?? 0);
                $id = $this->repository->save($statusId, $values);
                if ($id !== null && $id >= 0) {
                    $response = [
                        'status' => 'ok',
                        'msg' => 'Status zostal zapisany.',
                        'id' => (int)$id,
                    ];
                }
            }

            echo json_encode($response);
            exit;
        }

        $payload = $_POST;
        $statusId = isset($payload['id']) && $payload['id'] !== '' ? (int)$payload['id'] : null;
        if ($statusId === null) {
            $statusId = (int)\Shared\Helpers\Helpers::get('id');
        }

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

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

    private function buildFormViewModel(array $status, array $apiloStatusList): FormEditViewModel
    {
        $id = (int)($status['id'] ?? 0);

        $apiloOptions = ['' => '--- wybierz status apilo.com ---'];
        foreach ($apiloStatusList as $apiloId => $apiloName) {
            $apiloOptions[$apiloId] = $apiloName;
        }

        $data = [
            'id' => $id,
            'status' => (string)($status['status'] ?? ''),
            'color' => (string)($status['color'] ?? ''),
            'apilo_status_id' => $status['apilo_status_id'] ?? '',
        ];

        $fields = [
            FormField::hidden('id', $id),
            FormField::text('status', [
                'label' => 'Status',
                'tab' => 'settings',
                'readonly' => true,
            ]),
            FormField::color('color', [
                'label' => 'Kolor',
                'tab' => 'settings',
            ]),
            FormField::select('apilo_status_id', [
                'label' => 'Status z Apilo',
                'tab' => 'settings',
                'options' => $apiloOptions,
            ]),
        ];

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

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

        return new FormEditViewModel(
            'status-edit',
            'Edycja statusu zamowienia',
            $data,
            $fields,
            $tabs,
            $actions,
            'POST',
            $actionUrl,
            '/admin/shop_statuses/list/',
            true,
            ['id' => $id]
        );
    }

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

        $integrationsRepository = new IntegrationsRepository( $mdb );

        $list = [];
        $raw = @unserialize( $integrationsRepository -> getSetting( 'apilo', 'status-types-list' ) );
        if (is_array($raw)) {
            foreach ($raw as $apiloStatus) {
                if (isset($apiloStatus['id'], $apiloStatus['name'])) {
                    $list[(int)$apiloStatus['id']] = (string)$apiloStatus['name'];
                }
            }
        }
        return $list;
    }
}
