<?php
/**
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * Adyen Payment module (https://www.adyen.com/)
 *
 * Copyright (c) 2019 Adyen BV (https://www.adyen.com/)
 * See LICENSE.txt for license details.
 *
 * Author: Adyen <magento@adyen.com>
 */

namespace Adyen\Payment\Gateway\Response;

use Adyen\Payment\Helper\Vault;
use Magento\Payment\Gateway\Data\PaymentDataObject;
use Magento\Payment\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Response\HandlerInterface;

class VaultDetailsHandler implements HandlerInterface
{
    /**
     * @var Vault
     */
    private $vaultHelper;

    /**
     * VaultDetailsHandler constructor.
     * @param Vault $vaultHelper
     */
    public function __construct(Vault $vaultHelper)
    {
        $this->vaultHelper = $vaultHelper;
    }

    /**
     * @inheritdoc
     */
    public function handle(array $handlingSubject, array $response)
    {
        if (empty($response['additionalData'])) {
            return;
        }
        /** @var PaymentDataObject $orderPayment */
        $orderPayment = SubjectReader::readPayment($handlingSubject);
        $additionalData = $orderPayment->getPayment()->getAdditionalInformation();
        $tokenEnabler = array_key_exists("is_active_payment_token_enabler", $additionalData) ? $additionalData['is_active_payment_token_enabler']:false;
        if ($tokenEnabler) {
            $this->vaultHelper->saveRecurringDetails($orderPayment->getPayment(), $response['additionalData']);
        }
    }
}
