<?php

namespace KupShop\ReturnsElninoBundle\View;

use KupShop\KupShopBundle\Exception\RedirectException;
use KupShop\KupShopBundle\Util\Database\QueryHint;
use KupShop\ReturnsBundle\Util\ReturnsUtil;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class CreateReturnView extends \KupShop\ReturnsBundle\View\CreateReturnView
{
    /** @var SessionInterface */
    protected $session;

    protected $returnsUtil;
    protected $orderId;

    public function __construct(SessionInterface $session, ReturnsUtil $returnsUtil)
    {
        parent::__construct($session, $returnsUtil);
        $this->returnsUtil = $returnsUtil;
    }

    public function handleStep_summary($bankAccount, $note, $user_content, $delivery = null)
    {
        $returns = $this->load();

        // validate required address fields
        foreach ($this->returnsUtil->getAddressFields() as $field) {
            if (empty($delivery[$field])) {
                addUserMessage(translate('error_delivery_fields', 'reclamations'), 'danger');
                throw new RedirectException(path('kupshop_returns_returns_createreturnssummary'));
            }
        }

        $returns['form_data'] =
        [
            'bank_account' => $bankAccount,
            'note' => $note,
        ];

        $items = $returns['return_items'] ?? '';
        $items = array_filter($items, function ($x) {
            return !empty($x['item']) && !empty($x['pieces']);
        });

        $replacements = $returns['replacement_items'] ?? [];
        if (!empty($replacements)) {
            $replacements = array_filter($replacements, function ($x) {
                return !empty($x['pieces']);
            });

            $replacementList = $this->getReplacementProducts();
            foreach ($replacements as $key => &$value) {
                $price = $replacementList[$value['id_product'].(!empty($value['id_variation']) ? '/'.$value['id_variation'] : '')]->getProductPrice();
                $priceArray = PriceWrapper::wrap($price);
                $replacements[$key]['price'] = $priceArray['value_without_vat'];
            }
        }

        if (empty($items)) {
            $this->returnNoItemsError();
        }

        if (!empty($returns['delivery'])) {
            $delivery = $delivery + [
                'data' => json_encode(['id_delivery' => $returns['delivery']['replacement']['id'], 'delivery' => $returns['delivery']['replacement']['name']]),
                'return_delivery' => $returns['delivery']['return']['price'],
                'replacement_delivery' => $returns['delivery']['replacement']['price']->getPriceWithVat(),
                'total_price' => $returns['totalPrice'],
            ];
        }

        $returnId = QueryHint::withRouteToMaster(function () use ($bankAccount, $items, $replacements, $note, $delivery, $user_content) {
            // Nemůže být v transakci (obaluje odeslání async emailů, transakce je uvnitř)
            $returnId = $this->returnsUtil->createReturn($bankAccount, $items, $replacements, $note, true, $delivery, $user_content ?: []);

            try {
                $returnDelivery = false;
                $return = $this->returnsUtil->getReturn($returnId);
                foreach ($this->returnsUtil->getOrderIdsByReturn($returnId) as $order) {
                    if ($this->returnHasAllOrderItems($return, $order['id'])) {
                        $returnDelivery = true;
                    }
                }
                $return->setCustomDataValue('return_delivery', $returnDelivery);
            } catch (\Exception $e) {
                getRaven()->captureException($e);
            }

            return $returnId;
        });

        $returns['return_items'] = $returns['replacement_items'] = [];
        $this->save($returns);

        throw new RedirectException(path('kupshop_returns_returns_return', ['id' => $returnId, 'success' => 1]));
    }

    public function getSelectReclamation($products)
    {
        $qb = sqlQueryBuilder()
           ->select('id_item, COALESCE(SUM(pieces), 0) as pieces')
           ->from('reclamation_items_elnino');

        return $products
                ->addSelect('(oi.pieces - COALESCE(SUM(ri.pieces), 0) - COALESCE(rie.pieces, 0)) as returnable_pieces')
                ->leftJoin('oi', "({$qb})", 'rie', 'oi.id = rie.id_item');
    }

    /**
     * @required
     */
    public function setSession(SessionInterface $session)
    {
        $this->session = $session;
    }

    public function setOrderId($orderId)
    {
        $this->orderId = $orderId;

        return $this;
    }

    public function getOrderId()
    {
        return $this->orderId;
    }
}
