<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonShippingCommon\Subscriber;

use Shopware\Bundle\AttributeBundle\Service\CrudService;
use Shopware\Plugins\ViisonCommon\Classes\ExceptionHandling\SubscriberExceptionHandling;
use Shopware\Plugins\ViisonCommon\Classes\Subscribers\Base;
use Shopware\Plugins\ViisonCommon\Classes\Util\Util;

class OrderAttributeSubscriber extends Base
{
    use SubscriberExceptionHandling;

    /**
     * @inheritdoc
     */
    public static function getSubscribedEvents()
    {
        return [
            'Shopware_Controllers_Backend_AttributeData::saveDataAction::before' => 'onBeforeSaveDataAction',
        ];
    }

    /**
     * Log once the `viison_transfer_customer_contact_data_allowed` is changed.
     *
     * @param \Enlight_Hook_HookArgs $args
     */
    public function onBeforeSaveDataAction(\Enlight_Hook_HookArgs $args)
    {
        try {
            $params = $args->getSubject()->Request()->getParams();
            $key = CrudService::EXT_JS_PREFIX . 'viison_transfer_customer_contact_data_allowed';
            if (!array_key_exists($key, $params)) {
                return;
            }

            $newIsCustomerContactDataTransferAllowed = boolval($params[$key]);
            $entityManager = $this->get('models');
            $order = $entityManager->getRepository(
                'Shopware\Models\Order\Order'
            )->findOneById($params['_foreignKey']);
            $orderAttributes = $order->getAttribute();
            if ($orderAttributes === null) {
                return;
            }

            $oldIsCustomerContactDataTransferAllowed = $orderAttributes->getViisonTransferCustomerContactDataAllowed();
            if ($newIsCustomerContactDataTransferAllowed === $oldIsCustomerContactDataTransferAllowed) {
                return;
            }

            $user = Util::getCurrentUser();
            $this->get('pluginlogger')->info(
                'The viison_transfer_customer_contact_data_allowed order attribute was changed',
                [
                    'orderNumber' => $order->getNumber(),
                    'user' => $user->getName(),
                    'date' => new \DateTime(),
                    'oldValue' => $oldIsCustomerContactDataTransferAllowed,
                    'newValue' => $newIsCustomerContactDataTransferAllowed,
                ]
            );
        } catch (\Exception $e) {
            $this->handleException($e, $args);
        }
    }
}
