<?php

namespace KupShop\ElninoBundle\Admin\lists;

global $cfg;

use KupShop\KupShopBundle\Util\HtmlBuilder\HTML;

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

class OrdersList extends \OrdersList
{
    public function __construct()
    {
        parent::__construct();

        $this->tableDef['fields']['package'] = ['translate' => true, 'field' => 'package_id', 'render' => 'renderPackage'];
        $this->tableDef['fields']['ExternalOrder'] = [
            'translate' => true, 'field' => 'external_order',
            'spec' => function (\Query\QueryBuilder $qb) {
                $qb->addSelect("JSON_VALUE(o.note_admin, '$.Abra_ExternalOrder') AS external_order");
            },
        ];
    }

    public function renderPackage($values, $column)
    {
        if (empty($values['package_id'])) {
            return '';
        }

        $delivery = \Delivery::getClass($values['class']);

        $link = $delivery->getTrackAndTraceLink($values['package_id']) ?? '';

        return HTML::create('a')
            ->attr('href', $link)
            ->attr('target', '_blank')
            ->text($values['package_id']);
    }

    public function renderName($values, $column)
    {
        $parts = [];

        $name = $this->getListRowValue($values, $column['field']);
        $surname = $this->getListRowValue($values, 'invoice_surname');
        $company = $this->getListRowValue($values, 'invoice_firm');

        if ($name || $surname) {
            $parts[] = join(' ', [$name, $surname]);
        }

        if ($company) {
            $parts[] = $company;
        }

        return join(', ', $parts);
    }

    public function getQuery()
    {
        $qb = parent::getQuery();

        $qb->addSelect('o.package_id, dtd.class');

        return $qb;
    }
}

return OrdersList::class;
