<?php

namespace KupShop\UserBundle\EventListener;

use KupShop\OrderingBundle\Event\OrderEvent;
use Query\Operator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class OrderCreatedListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            OrderEvent::ORDER_FINISHED => [
                ['saveUserPreferences', 200],
            ],
            OrderEvent::ORDER_HANDLED => [
                ['setDueDate', 100], // Potřebuju se spustit až po nastavení date_handle v InvoicesBundle\OrderEventListener::orderHandled
            ],
        ];
    }

    public function saveUserPreferences(OrderEvent $event)
    {
        $order = $event->getOrder();
        $requiresDeliveryAddress = $order->getDeliveryType()->getDelivery()->requiresDeliveryAddress();

        if (!$order->id_user) {
            return;
        }

        $user = sqlGetConnection()->transactional(function () use ($order) {
            $user = \User::createFromId($order->id_user);
            $user->fetchAddresses();

            return $user;
        });

        $save = false;

        if ($order->getData('save_address')) {
            foreach (\User::getFields() as $field) {
                $user->invoice[$field] = $order->{"invoice_{$field}"};
                if ($requiresDeliveryAddress) {
                    $user->delivery[$field] = $order->{"delivery_{$field}"};
                }
            }
            $save = true;
        }

        if (findModule(\Modules::USERS, 'remember_user_delivery_type')) {
            $user->invoice['transport'] = $order->id_delivery;
            $save = true;
        }

        if ($save) {
            $user->update();
        }
    }

    public function setDueDate(OrderEvent $event)
    {
        $order = $event->getOrder();
        if (isset($order->date_due)) {
            return;
        }
        if (!$order->id_user) {
            return;
        }

        $due_days = sqlQueryBuilder()
            ->select('due_days')->from('users')
            ->andWhere(Operator::equals(['id' => $order->id_user]))
            ->execute()->fetchOne();
        if ($due_days > 0) {
            $date = $order->date_handle->add(\DateInterval::createFromDateString($due_days.' days'));
            sqlQueryBuilder()->update('orders')
                ->directValues(['date_due' => $date->format('Y-m-d H:i:s')])
                ->andWhere(Operator::equals(['id' => $order->id]))
                ->execute();
            $order->date_due = $date;
        }
    }
}
