<?php

namespace KupShop\OrderDiscountBundle\Admin\lists;

use KupShop\AdminBundle\AdminList\BaseList;
use KupShop\KupShopBundle\Util\HtmlBuilder\HTML;
use Query\Operator;
use Query\QueryBuilder;

class OrderDiscountsGeneratedCouponsList extends BaseList
{
    protected $orderParam = [
        'sort' => 'id',
        'direction' => 'DESC',
    ];
    protected $template = 'list/generatedDiscountsCoupons.tpl';
    protected bool $useFiltersStorage = false;

    public function __construct()
    {
        $this->tableDef = [
            'id' => 'id',
            'fields' => [
                'id' => ['field' => 'id', 'visible' => 'N'],
                'Kód' => ['field' => 'code', 'render' => 'renderCode'],
                'Popis' => ['field' => 'data', 'render' => 'renderDescr', 'visible' => 'N', 'fieldType' => BaseList::TYPE_STRING],
                'Platnost' => ['field' => 'date_to', 'render' => 'renderDate', 'size' => 0.5],
                'Aktivovaný' => ['field' => 'date_activated', 'render' => 'renderActivated', 'size' => 0.6],
                'Použitý' => ['field' => 'used', 'render' => 'renderUsed', 'size' => 0.5],
                'Náhled' => ['field' => 'id', 'render' => 'renderViewPDF', 'size' => 0.5],
                'Koupený v obj.' => ['field' => 'order_purchased', 'type' => 'orders', 'type_id' => 'id_order_purchased'],
                'Uplatněný v obj.' => ['field' => 'ou_order_no', 'type' => 'orders', 'type_id' => 'id_order_used', 'spec' => 'ou_order_no', 'render' => 'renderOrdersUsed'],
                'Datum uplatnění' => ['field' => 'ou_date_accept', 'render' => 'renderDate', 'size' => 0.6],
                'Uživatel' => ['field' => 'username', 'type' => 'users', 'type_id' => 'id_user', 'visible' => 'N'],
                'Hodnota' => ['field' => 'price', 'render' => 'renderPrice', 'fieldType' => BaseList::TYPE_PRICE],
                'Akce' => ['field' => 'id', 'render' => 'renderActions', 'class' => 'hiddenTooltip', 'size' => 0.8],
            ],
        ];
    }

    public function customizeTableDef($tableDef)
    {
        $tableDef = parent::customizeTableDef($tableDef);

        $tableDef['fields']['Uplatněný v obj.']['spec'] = function (QueryBuilder $qb) {
            $qb->addSubselect(
                sqlQueryBuilder()
                    ->select('JSON_OBJECTAGG(o.id, o.order_no)')
                    ->from('discounts_coupons_orders', 'dco')
                    ->leftJoin('dco', 'orders', 'o', 'o.id = dco.id_order')
                    ->andWhere('dco.id_discount_coupon = dc.id'), 'orders_used'
            );
        };

        return $tableDef;
    }

    public function renderOrdersUsed($values, $column)
    {
        if ($orders_used = $values['orders_used'] ?? null) {
            $orders_used = json_decode($orders_used, true);
            $ret = [];
            foreach ($orders_used as $id_order => $order_no) {
                $ret[] = HTML::create('a')
                    ->attr('href', "javascript:nw('orders', '{$id_order}');")
                    ->text($order_no);
                $ret[] = HTML::create('span')->attr('style', 'white-space: pre;')->text(', ');
            }
            array_pop($ret); // remove last ', '

            return $ret;
        }

        return $this->renderCell($values, $column);
    }

    public function renderCode($values, $column)
    {
        $code = $this->renderCell($values, $column);

        $descr = [];
        if (!empty($values['data'])) {
            $data = json_decode($values['data'], true);
            foreach ($data as $key => $value) {
                if (!empty($value) && $translateKey = translate($key, 'OrderDiscountsCoupons', true)) {
                    $descr[] = "{$translateKey}: {$value}";
                }
            }
        }

        if (!empty($descr)) {
            return HTML::create('span')
                ->text($code)
                ->attr('title', join('; ', $descr))
                ->end();
        }

        return $code;
    }

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

        $data = json_decode($values['data'], true);

        return $data['coupon_descr'] ?? '';
    }

    public function renderUsed($values, $column)
    {
        $used = $this->getListRowValue($values, $column['field']);

        return ($used == 'Y') ? 'Ano' : 'Ne';
    }

    public function renderActivated($values, $column)
    {
        $value = $this->renderCell($values, $column);

        if (empty($value)) {
            $id = $this->getListRowValue($values, 'id');
            $id_discount = $this->getListRowValue($values, 'id_discount');

            return HTML::create('a')
                    ->attr('href', 'launch.php?s=OrderDiscountsCoupons.php&acn=activateCoupon&couponID='.$id.'&ID='.$id_discount.'&flap=flapGeneratedCoupons')
                    ->attr('class', 'btn btn-warning btn-xs')
                    ->attr('title', ucfirst(translate('activate_coupon', 'OrderDiscountsCoupons')))
                    ->tag('span')
                    ->attr('class', 'bi bi-arrow-clockwise')
                    ->end();
        }

        return $this->renderDate($values, $column);
    }

    public function renderActions($values, $column)
    {
        $buttons = [];
        $id = $this->getListRowValue($values, $column['field']);
        $id_discount = $this->getListRowValue($values, 'id_discount');
        $id_order_purchased = $this->getListRowValue($values, 'id_order_purchased');
        $used = $this->getListRowValue($values, 'used');

        if ($id && $id_discount) {
            if ($id_order_purchased) {
                $buttons[] = HTML::create('a')
                    ->attr('target', '_parent')
                    ->attr('href', 'launch.php?s=OrderDiscountsCoupons.php&acn=sendEmail&couponID='.$id.'&ID='.$id_discount.'&flap=flapGeneratedCoupons')
                    ->attr('class', 'btn btn-xs btn-secondary')
                    ->attr('title', ucfirst(translate('sendEmail', 'orders')))
                        ->tag('span')
                            ->attr('class', 'bi bi-send')
                        ->end();
            } else {
                $buttons[] = HTML::create('a')
                    ->attr('class', 'btn btn-xs btn-secondary')
                    ->attr('title', ucfirst(translate('sendEmail', 'orders')))
                    ->attr('disabled')
                        ->tag('span')
                            ->attr('class', 'bi bi-send')
                        ->end();
            }

            $buttons[] = HTML::create('a')
                ->attr('href', 'launch.php?s=OrderDiscountsCoupons.php&acn=deleteCoupon&couponID='.$id.'&ID='.$id_discount.'&flap=flapGeneratedCoupons')
                ->attr('class', 'btn btn-danger btn-xs confirm')
                ->attr('title', translate('windowDelete', 'button'))
                    ->tag('i')
                        ->attr('class', 'bi bi-x-lg')
                    ->end();

            if ($used == 'N') {
                $buttons[] = HTML::create('a')
                    ->attr('href', 'launch.php?s=OrderDiscountsCoupons.php&acn=useCoupon&couponID='.$id.'&ID='.$id_discount.'&flap=flapGeneratedCoupons')
                    ->attr('class', 'btn btn-success btn-xs')
                    ->attr('title', ucfirst(translate('use_coupon', 'OrderDiscountsCoupons')))
                        ->tag('span')
                            ->attr('class', 'bi bi-check-lg')
                        ->end();
            } elseif (!empty($this->getListRowValue($values, 'ou_status_storno'))) {
                $buttons[] = HTML::create('a')
                    ->attr('href', 'launch.php?s=OrderDiscountsCoupons.php&acn=reactiveCoupon&couponID='.$id.'&ID='.$id_discount.'&flap=flapGeneratedCoupons')
                    ->attr('class', 'btn btn-warning btn-xs')
                    ->attr('title', ucfirst(translate('reactivate_coupon', 'OrderDiscountsCoupons')))
                        ->tag('span')
                            ->attr('class', 'bi bi-arrow-repeat')
                        ->end();
            }
        }

        return $buttons;
    }

    public function renderViewPDF($values, $column)
    {
        $id = $this->getListRowValue($values, $column['field']);
        $id_discount = $this->getListRowValue($values, 'id_discount');

        if ($id && $id_discount) {
            return HTML::create('a')
                ->attr('href', 'launch.php?s=OrderDiscountsCoupons.php&acn=viewPDF&autoclose=1&couponID='.$id.'&ID='.$id_discount)
                ->attr('target', '_blank')
                ->attr('class', 'btn-sm btn btn-default btn-xs')
                ->attr('title', 'Náhled')
                    ->tag('span')
                        ->attr('class', 'bi bi-image')
                    ->end();
        }

        return '';
    }

    public function getQuery()
    {
        $qb = sqlQueryBuilder()
            ->select('dc.*, o.order_no AS order_purchased, ou.order_no ou_order_no, ou.status_storno ou_status_storno,ou.date_accept ou_date_accept,
                CONCAT(u.name, " ", u.surname) as username')
            ->from('discounts_coupons', 'dc')
            ->leftJoin('dc', 'orders', 'o', 'dc.id_order_purchased = o.id')
            ->leftJoin('dc', 'orders', 'ou', 'dc.id_order_used=ou.id')
            ->leftJoin('dc', 'users', 'u', 'u.id = dc.id_user');
        $id_discount = getVal('id_discount');
        if ($id_discount) {
            $qb->andWhere(Operator::equals(['id_discount' => $id_discount]));
        }

        $id_order = getVal('id_order');
        if ($id_order) {
            $qb->andWhere(Operator::equals(['ou.order_no' => trim($id_order), 'o.order_no' => trim($id_order)], 'OR'));
        }

        $search_code = getVal('search_code');
        if ($search_code) {
            $qb->andWhere(Operator::like(['code' => '%'.trim($search_code).'%']));
        }

        return $qb;
    }
}

return OrderDiscountsGeneratedCouponsList::class;
