<?php

declare(strict_types=1);

namespace External\HannahBundle\Admin\lists;

use External\HannahBundle\Util\OrderUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

require_once $cfg['Path']['shared_version'].'admin/lists/OrdersList.php';

class OrdersList extends \OrdersList
{
    public function customizeTableDef($tableDef)
    {
        $tableDef = parent::customizeTableDef($tableDef);

        $tableDef['fields']['SAP datum vychystávání'] = [
            'field' => 'sap_date_picking',
            'spec' => 'JSON_VALUE(o.note_admin, "$.sapDatePicking") as sap_date_picking',
            'render' => 'renderSAPDate',
            'visible' => 'Y',
        ];
        $tableDef['fields']['SAP datum vyřízení'] = [
            'field' => 'sap_date_handle',
            'spec' => 'COALESCE(JSON_VALUE(o.note_admin, "$.sapDatePrepared"), JSON_VALUE(o.note_admin, "$.sapDateSent")) as sap_date_handle',
            'render' => 'renderSAPDate',
            'visible' => 'Y',
        ];
        $tableDef['fields']['SAP vyřízeno faktura'] = [
            'field' => 'sap_date_invoice',
            'spec' => 'JSON_VALUE(o.note_admin, "$.sapDateInvoice") as sap_date_invoice',
            'render' => 'renderSAPDate',
            'visible' => 'Y',
        ];

        return $tableDef;
    }

    public function renderSAPDate(array $values, array $column): string
    {
        $timestamp = $values[$column['field']] ?? null;
        if (empty($timestamp)) {
            return '';
        }

        $format = \Settings::getDateFormat().' '.\Settings::getTimeFormat();

        $datetime = new \DateTime();
        $datetime->setTimestamp((int) $timestamp);

        return $datetime->format($format);
    }

    public function renderCode($values, $column)
    {
        $order = new \Order();
        $order->createFromArray($values);

        return $this->getOrderUtil()->getOrderNumberWithPrefix($order);
    }

    private function getOrderUtil(): OrderUtil
    {
        static $orderUtil;

        if (!$orderUtil) {
            $orderUtil = ServiceContainer::getService(OrderUtil::class);
        }

        return $orderUtil;
    }
}

return OrdersList::class;
