<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use \Verifone\Core\ServiceFactory;
use \Verifone\Core\ExecutorContainer;
use \Verifone\Core\Service\Backend\GetAvailablePaymentMethodsService;
use \Verifone\Core\Executor\BackendServiceExecutor;
use \Verifone\Core\DependencyInjection\Transporter\CoreResponse;
use \Verifone\Core\DependencyInjection\CoreResponse\Interfaces\PaymentMethod;


class WC_Verifone_Core_PaymentMethods extends WC_Verifone_Core
{

    const PAYMENT_METHODS_OPTION_KEY = WC_Verifone_PaymentMethods::PAYMENT_METHODS_OPTION_KEY;
	const PAYMENT_METHODS_UPDATED_OPTION_KEY = WC_Verifone_PaymentMethods::PAYMENT_METHODS_UPDATED_OPTION_KEY;

    /**
     * Refresh payment methods from Verifone
     *
     * @return array|null
     */
    public static function refreshAvailablePaymentMethods()
    {
        require_once WC_VERIFONE_PLUGIN_PATH . DIRECTORY_SEPARATOR . 'vendor/autoload.php';

        $config = WC_Verifone_Config::getInstance();
        $configObject = self::getAvailablePaymentMethodsConfigObject();

        /** @var GetAvailablePaymentMethodsService $service */
        $service = ServiceFactory::createService($configObject, 'Backend\GetAvailablePaymentMethodsService');
        $container = new ExecutorContainer();

        /** @var BackendServiceExecutor $exec */
        $exec = $container->getExecutor('backend');

        /** @var CoreResponse $response */
        $keyFile = $config->getPaymentPublicKeyFile();
        $response = $exec->executeService($service, $keyFile);

        if (!$response->getStatusCode()) {
            return null;
        }

        $body = $response->getBody();
        $methods = ['all'];

        /** @var PaymentMethod $item */
        foreach ($body as $item) {
            $methods[] = $item->getCode();
        }

        self::_savePaymentMethods($methods);

        return $methods;
    }

    /**
     * Save fetched payment methods properly ordered and filtered
     *
     * @param $methods
     */
    protected static function _savePaymentMethods($methods)
    {
        $encoded = json_encode($methods);
        update_option(self::PAYMENT_METHODS_OPTION_KEY, $encoded);
		update_option(self::PAYMENT_METHODS_UPDATED_OPTION_KEY, wp_date('Y-m-d H:i:s'));
    }
}
