<?php

namespace KupShop\ReclamationsBundle\Admin\lists;

use Query\Operator;

class ReclamationsMassModificationList extends ReclamationsList
{
    protected $template = 'list/ReclamationsMassModificationList.tpl';

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

        $tableDef['id'] = '';

        $field = [
            'Vybrat' => [
                'field' => 'r.code',
                'size' => '55px',
                'render' => 'renderCheckbox',
                'label' => 'check',
                'type' => '',
                'class' => 'hiddenTooltip overflow-visible hidden-label',
            ],
            'Číslo' => [
                'field' => 'r.code',
                'type_id' => 'r.id',
                'type' => 'Reclamations',
            ],
        ];

        $tableDef['fields'] = $field + $tableDef['fields'];

        return $tableDef;
    }

    public function renderCheckbox($values)
    {
        return $this->getCheckbox('reclamation_ids', $values['id']);
    }

    public function handleBankCommand()
    {
        $dbcfg = \Settings::getDefault();
        $reclamationIds = getVal('reclamation_ids', getVal('data'), []);

        $abo = new \snoblucha\Abo\Abo();
        $abo->setComittentNumer(0);
        $abo->setOrganization($dbcfg->shop_firm_name);
        $abo->setDate();

        $account = $abo->addAccountFile(\snoblucha\Abo\Account\File::UHRADA);
        //        $account->setBank('2010'); // banka prikazce
        $account->setBankDepartment(0);
        $group = $account->addGroup();

        //        $group->setAccount(2900217845); // cislo uctu prikazce
        $group->setDate();

        foreach ($reclamationIds as $reclamationId) {
            $reclamation = $this->reclamations->getReclamation($reclamationId);

            if ($orderId = $reclamation->getIdOrder()) {
                $orderObj = new \Order();
                $orderObj->createFromDB($orderId);

                $price = toDecimal($reclamation->getItem()['total_price'])->addVat($reclamation->getItem()['tax']);
                $accountNo = $reclamation->getBankAccount();
                if (!empty($accountNo)) {
                    $group->addItem($accountNo, $price->abs()->asFloat(), $orderObj->order_no);
                }
            }
        }

        header('Content-type: application/txt');
        header('Content-Disposition: attachment; filename="ABO-'.date('Y-m-d_H-i').'_'.time().'.txt"');
        echo $abo->generate();
        exit;
    }

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

        $qb->andWhere(Operator::not(Operator::inIntArray($this->reclamations->getHandleStatuses(), 'r.status')));

        return $qb;
    }
}
