<?php

use KupShop\OrderingBundle\Util\Order\OrderItemEditTrait;

require_once $cfg['Path']['shared_version'].'admin/orders.items.php';

$main_class = 'KozaOrderItems';

class KozaOrderItems extends OrderItems
{
    use DatabaseCommunication;
    use OrderItemEditTrait;

    protected $template = 'window/orders.items.tpl';
    protected $price_level;

    public function get_vars()
    {
        $vars = parent::get_vars();

        if (!empty($vars['body']['pv'])) {
            foreach ($vars['body']['pv'] as &$item) {
                $item['set'] = '';
                if (!empty($item['id_product'])) {
                    if ($set = $this->selectSQL('products', ['id' => $item['id_product']], ['`set`'])->fetchColumn()) {
                        $item['set'] = 'Složení: '.$set;
                    }
                }
            }
        }

        return $vars;
    }

    protected function saveItems($data, $IDo): bool
    {
        $order = new Order($IDo);
        $order->createFromDB($order->id);

        if ($order->getData('enableEdit') === true) {
            $saved = $this->processOrderItemsInTransaction($order, $IDo, $data);
        } else {
            $saved = parent::saveItems($data, $IDo);
        }

        return $saved;
    }

    protected function processOrderItemsInTransaction(Order $order, $IDo, $data)
    {
        $db = sqlGetConnection();
        try {
            $db->beginTransaction();

            $ret = parent::saveItems($data, $IDo, $db);

            if ($ret) {
                // Recalculate order
                $order2 = new Order();
                $order2->createFromDB($order->id, true, true, true);
                $order2->recalculate();

                if ($order2->isModified()) {
                    $abra = new AbraElnino();
                    $ErrStr = getTextString('status', 'saved');
                    $abra->updateOrder($IDo, $order2->status, strip_tags($ErrStr));
                }
            }

            $db->commit();

            return $ret;
        } catch (AbraUpdateOrderException $e) {
            $db->rollBack();
            throw $e;
        }
    }

    public function returnError($ErrStr, $parentRefresh = '', $ID = null)
    {
        if (empty($ID)) {
            $ID = getVal('IDo');
        }
        if ($parentRefresh) {
            $parentRefresh = '&refresh=parent';
        }
        if (getVal('autoclose')) {
            $parentRefresh .= '&refresh=close';
        }
        redirect("launch.php?s={$this->getName()}.php&acn=edit{$parentRefresh}&flap=".getVal('flap')."&IDo={$ID}&ErrStr=".urlencode($ErrStr));
    }

    protected function savedPostProcess($saved, $IDo)
    {
        if ($saved) {
            $order = new Order($IDo);
            $order->createFromDB($order->id);

            if ($order->status > 0) {
                $remainingPayment = abs($order->getRemainingPayment());
                if ($remainingPayment > 0.1) {
                    $this->returnError(translate('remainingPayment', 'orders'), '', $IDo);
                }
            }
        }

        parent::savedPostProcess($saved, $IDo);
    }
}
