<?php

namespace KupShop\ReclamationsElninoBundle\Admin;

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\ReclamationsBundle\Util\ReclamationsUtil;

class Reclamations extends \KupShop\ReclamationsBundle\Admin\Reclamations
{
    public function __construct()
    {
        parent::__construct();
    }

    public function get_vars()
    {
        if (empty($this->getID())) {
            $this->action = 'add';
        }

        $vars = \Window::get_vars();

        if ($this->getAction() == 'edit') {
            $order = $this->prepareOrder($vars['body']['data']['id_order']);

            $diff = 0;
            if ($order->date_handle) {
                $diff = $order->date_handle->diff(new \DateTime());
                $diff = abs($diff->days);
            }

            $vars['body']['order_date_diff'] = $diff;
            $vars['body']['order'] = $order;

            $this->contextManager->activateOrder($order, function () use (&$vars) {
                $vars['body']['emails'] = $this->reclamations->getEmails($this->getReclamation());
                $vars['body']['emailsInStatuses'] = $this->reclamations->getEmailsInStatuses($this->getReclamation());
            });

            $vars['body']['exchangeOrder'] = $this->getExchangeOrder();
            $vars['body']['selected_delivery'] = $this->getDeliveryId();
        }

        if ($this->getAction() == 'add') {
            $vars['body']['data']['id_order'] = getVal('id_order', null, '');
        }

        $vars['body']['statuses'] = $this->reclamations->getStatuses();
        $vars['body']['handle_statuses'] = $this->reclamations->getHandleStatuses();
        $vars['body']['handle_types'] = $this->reclamations->getHandleTypes();
        $vars['body']['preferred_handle_types'] = $this->reclamations->getPrefHandleTypes();
        $vars['body']['address_fields'] = $this->reclamations->getAddressFields();

        $vars['body']['deliveries'] = \Delivery::getAll();

        if (findModule(\Modules::PRODUCTS_SUPPLIERS) && $this->getAction() != 'add') {
            $item = $this->getReclamation()->getItem();

            $suppliersCodes = sqlQueryBuilder()->select('s.id, s.name, pos.code')
                ->from('products_of_suppliers', 'pos')
                ->leftJoin('pos', 'suppliers', 's', 's.id = pos.id_supplier')
                ->where(\Query\Operator::equalsNullable(['id_product' => $item['id_product'], 'id_variation' => $item['id_variation']]))
                ->execute()->fetchAll();

            $vars['body']['suppliers_codes'] = $suppliersCodes;
        }

        return $vars;
    }

    public function handleConvertToReturn($comment, bool $isReclamation = true)
    {
        /** @var \KupShop\ReturnsBundle\Util\ReturnsUtil $returnsUtil */
        $returnsUtil = ServiceContainer::getService(\KupShop\ReturnsBundle\Util\ReturnsUtil::class);

        $reasons = array_keys($returnsUtil->getReasons());
        $reasonId = end($reasons);

        $items = [];
        foreach ($this->getReclamation()->getItem() as $item) {
            $item['return_reason'] = $reasonId;
            $items[$item['id_item']] = $item;
        }

        $returnId = $returnsUtil->createReturn(
            $this->getReclamation()->getBankAccount() ?: '',
            $items,
            [],
            null,
            false
        );

        $this->updateSQL('reclamations', ['handle_type' => 3], ['id' => $this->getID()]);

        $return = $returnsUtil->getReturn($returnId);
        $returnsUtil->logHistory($returnId, "Vratka byla vytvořena pro vyřízení reklamace č. <a href=\"javascript:nw('Reclamations', {$this->getReclamation()->getId()})\">{$this->getReclamation()->getCode()}");

        $comment = 'Vaše reklamace č. '.$this->getReclamation()->getCode().' bude vyřízena vratkou č. <a href="'.path('kupshop_returns_returns_returns').'">'.$return->getCode().'</a>';

        $this->reclamations->changeStatus($this->getReclamation()->getId(), ReclamationsUtil::STATUS_HANDLED, $comment, true);
        $this->reclamations->logHistory($this->getReclamation()->getId(), 'Pro vyřízení reklamace byla vytvořena vratka č. <a href="javascript:nw(\'Returns\', '.$returnId.')">'.$return->getCode().'</a>');

        $order = new \Order($this->getReclamation()->getIdOrder());
        $order->createFromDB($this->getReclamation()->getIdOrder());
        $order->logHistory('Pro vyřízení reklamace č. '.$this->getReclamation()->getId().' byla vytvořena vratka č. <a href="javascript:nw(\'Returns\', '.$returnId.')">'.$return->getCode().'</a>');

        $params = [
            's' => 'Returns.php',
            'acn' => 'edit',
            'ID' => $returnId,
        ];
        $this->redirect($params);
    }
}

return Reclamations::class;
