<?php

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

class WC_Verifone_Core_Generator extends WC_Verifone_Core
{
    const STORAGE_KEY = 'woocommerce_verifone_keys';


    public static function generateKeys( $type )
    {
        require_once WC_VERIFONE_PLUGIN_PATH . DIRECTORY_SEPARATOR . 'vendor/autoload.php';

        $success = true;
        $messages = array();

        if(empty($type)) {
            $success = false;
            $messages[] = esc_html__('Problem with generating new keys.', 'verifone-bluecommerce-for-woocommerce') . esc_html__('Please refresh the page and try again.', 'verifone-bluecommerce-for-woocommerce');
        }

        if (!$success) {
            return self::_returnJson($success, $messages);
        }

        $generator = new \Verifone\Core\DependencyInjection\CryptUtils\RsaKeyGenerator();
        $resultGenerate = $generator->generate();

        if ($resultGenerate) {
            $resultStoreKey = WC_Verifone_Keys::storeKeys($type, $generator->getPublicKey(), $generator->getPrivateKey());

            if($resultStoreKey === true) {
                $messages[] = esc_html__('Keys are generated correctly. Please refresh or save the configuration.', 'verifone-bluecommerce-for-woocommerce');
                return self::_returnJson($success, $messages);
            }

            $success = false;
            $messages[] = $resultStoreKey;

        } else {
            $success = false;
            $messages[] = esc_html__('Problem with generating new keys.', 'verifone-bluecommerce-for-woocommerce');
        }

        return self::_returnJson($success, $messages);

    }

    protected static function _returnJson($success, $messages)
    {
        return array('success' => $success, 'messages' => $messages);
    }
}
