<?php

if (!defined('ABSPATH')) {
    exit;
}

class WC_Verifone_Settings {
    const DESC_TIP = false;
	const HIDEABLE_FIELDS = array(
		'remember_cc_info',
		'min_order_total',
		'max_order_total',
		'disable_rsa_blinding',
		'validate_url',
		'pay_page_url_1',
		'pay_page_url_2',
		'pay_page_url_3',
		'key_handling_mode',
	);

	const HIDEABLE_KEY_HANDLING_FIELDS = array(
		'keys_directory',
		'shop_private_keyfile',
		'shop_private_keyfile_test',
	);

    public function getSettings( $all = false ) {
		$reset_nonce = wp_create_nonce('verifone_wc_reset_settings');

		$payment_methods = WC_Verifone_System::getPaymentMethodsOptions();
		unset($payment_methods['all']); // Remove all in one method from the list as it has it's own setting
		$payment_method_names = array_values($payment_methods);
		$payment_methods_last_update = get_option(WC_Verifone_PaymentMethods::PAYMENT_METHODS_UPDATED_OPTION_KEY, null);
		$payment_methods_last_update_human = $payment_methods_last_update ? wp_date( get_option('date_format') . ' ' . get_option('time_format'), strtotime($payment_methods_last_update) ) : null;

		$all_is_lone_method = count($payment_methods) === 1 && isset($payment_methods['all']);

        $settings = array(
			// Basic settings
            'enabled' => array(
                'title' => esc_html__('Enable/Disable', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'checkbox',
                'label' => esc_html__('Enable Verifone eCommerce', 'verifone-bluecommerce-for-woocommerce'),
                'default' => 'no',
            ),
            'title' => array(
                'title' => esc_html__('Title on checkout', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'default' => esc_html__('Verifone Payment', 'verifone-bluecommerce-for-woocommerce'),
				'description' => esc_html__("This text will appear on the checkout page as the name of Verifone's payment method.", 'verifone-bluecommerce-for-woocommerce'),
				'desc_tip' => self::DESC_TIP
            ),
            'is_live_mode' => array(
                'title' => esc_html__('Environment (Test/Production)', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Select environment for the payment module. If you want access to the test environment or you do not yet have a contract, please contact Verifone sales (myynti@verifone.fi / 09 477 433 00).', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 1,
                'options' => array(
                    1 => esc_html__('Production', 'verifone-bluecommerce-for-woocommerce'),
					0 => esc_html__('Test', 'verifone-bluecommerce-for-woocommerce'),
                )
            ),
            'merchant_agreement_code' => array(
                'title' => esc_html__('Verifone EC ID (merchant code)', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('The EC code is a merchant code that you will receive from Verifone by email when you sign a contract. The code is in the form ECxxxxx.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => ''
            ),
            'merchant_agreement_code_test' => array(
                'title' => esc_html__('Verifone EC ID (merchant code) - test environment', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('The EC code is a merchant code that you will receive from Verifone by email. The format of the code is ECxxxxx.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 'demo-merchant-agreement'
            ),
			'method_selection_enabled' => array(
                'title' => esc_html__('Payment method selection', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Display payment method selection on the checkout page or in a separate page?', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => $all_is_lone_method ? 0 : 1,
                'options' => $this->_yesNoOptions()
            ),
			'display_method_logos' => array(
                'title' => esc_html__('Show payment methods as logos on the checkout page', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Display payment method logos on the checkout page?', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 1,
                'options' => $this->_yesNoOptions()
            ),
			'skip_confirmation_page' => array(
                'title' => esc_html__('Skip confirmation page', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Return the user directly back to the shop after payment?', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 1,
                'options' => $this->_yesNoOptions()
            ),
			'allow_to_save_cc' => array(
                'title' => esc_html__('Allow payment cards to be saved', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Allow users to save their payment card information? This improves the shopping experience.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 0,
                'options' => $this->_yesNoOptions()
            ),
			'remember_cc_info' => array(
                'title' => esc_html__('Remember me info', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'textarea',
				'css' => 'max-width:400px;',
                'description' => esc_html__('Optional. Note in checkout after Remember payment method checkbox - for cards only.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
            ),
            'payment_message' => array(
                'title' => esc_html__('Text below payment methods', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'textarea',
				'css' => 'max-width:400px;',
                'description' => esc_html__('Optional information. Message below the payment method selection on the checkout page.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
            ),

			// Payment service advanced settings
			'show_advanced_settings' => array(
                'title' => '',
                'type' => 'title',
				'description' => '<a href="#woocommerce_verifone_section_advanced_settings" id="verifone-section-advanced-settings-trigger" data-alt="' . esc_html__('Close advanced settings &uarr;', 'verifone-bluecommerce-for-woocommerce') . '">' . esc_html__('Open advanced settings &darr;', 'verifone-bluecommerce-for-woocommerce') . '</a>',
                'desc_tip' => true
            ),
			'section_advanced_settings' => array(
				'title' => esc_html__('Advanced settings', 'verifone-bluecommerce-for-woocommerce'),
				'type' => 'title',
				'description' => '<span class="woocommerce_verifone_section_advanced_settings_desc">' . esc_html__( 'With advanced settings you can modify the functionalities more in depth. Usually you don\'t need to change these settings and you should only do so if you know what you are doing.', 'verifone-bluecommerce-for-woocommerce' ) . '</span>',
				'desc_tip' => self::DESC_TIP
			),
			'payment_methods_list' => array(
                'title' => esc_html__('Payment methods', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' =>
					wp_sprintf( esc_html__( 'Available payment methods: %s.', 'verifone-bluecommerce-for-woocommerce' ), $payment_method_names ? '<span id="verifone-payment-methods-list">' . implode( ', ', $payment_method_names ) . '</span>' : esc_html__( 'none', 'verifone-bluecommerce-for-woocommerce' ) )
					. '<br><br>' . esc_html__( 'Change available payment methods by contacting the Verifone support (asiakaspalvelu@verifone.fi / 09 4774 3343). Changes are reflected daily to your store.', 'verifone-bluecommerce-for-woocommerce')
					. '<br><br>' . wp_sprintf( esc_html__( 'Last updated: %s.', 'verifone-bluecommerce-for-woocommerce' ), '<span id="verifone-payment-methods-last-updated">' . $payment_methods_last_update_human ) . '</span> <a href="#refresh" id="verifone-refresh-payment-methods-trigger">' . esc_html__('Update now', 'verifone-bluecommerce-for-woocommerce') . '.</a>',
                'desc_tip' => self::DESC_TIP,
                'options' => WC_Verifone_System::getPaymentMethodsOptions(),
            ),
			'payment_page_language' => array(
                'title' => esc_html__('Payment page language', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Select language which will be use on payment page', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 'fi_FI',
                'options' => WC_Verifone_System::getLocaleOptions()
            ),
			'basket_item_sending' => array(
                'title' => esc_html__('Basket Item Sending', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Select for which type of order should send items.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 1,
                'options' => WC_Verifone_System::getBasketItemsOptions()
            ),
            'combine_invoice_basket_items' => array(
                'title' => esc_html__('Combine Invoice Basket Items', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Currently only available for invoice payment methods', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 0,
                'options' => $this->_yesNoOptions()
            ),
            'external_customer_id_field' => array(
                'title' => esc_html__('Use external customer id', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('If you want to use other field to match user (for example billing_phone) in Verifone Payment service, please set this value. If you do not know what should be, please leave empty and contact with our service.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => ''
            ),
			'min_order_total' => array(
                'title' => esc_html__('Minimum Order Total', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Leave empty to disable limit.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
            ),
            'max_order_total' => array(
                'title' => esc_html__('Maximum Order Total', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Leave empty to disable limit.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
            ),
			'save_masked_pan_number' => array(
                'title' => esc_html__('Save the last four digits of your payment card', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => null,
                'desc_tip' => self::DESC_TIP,
                'default' => 0,
                'options' => $this->_yesNoOptions()
            ),
			'style_code' => array(
                'title' => esc_html__('Style code', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Use of custom payment page template needs first to be uploaded and to be approved by Verifone.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => ''
            ),
			'disable_rsa_blinding' => array(
                'title' => esc_html__('Disable rsa blinding', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Define CRYPT_RSA_DISABLE_BLINDING as true in case of custom PHP build or PHP7 (experimental).', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 0,
                'options' => $this->_yesNoOptions()
            ),
			'pay_page_url_1' => array(
                'title' => esc_html__('Pay page URL 1', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Required. URL to the payment system', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => WC_Verifone_Urls::PAY_PAGE_URL_1,
            ),
            'pay_page_url_2' => array(
                'title' => esc_html__('Pay page URL 2', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Optional. Second redundant URL to the payment system.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => WC_Verifone_Urls::PAY_PAGE_URL_2,
            ),
            'pay_page_url_3' => array(
                'title' => esc_html__('Pay page URL 3', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Optional. Third redundant URL to the payment system.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => WC_Verifone_Urls::PAY_PAGE_URL_3,
            ),
            'validate_url' => array(
                'title' => esc_html__('Check payment node availability', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
                'description' => esc_html__('Make a check that payment node is available.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 1,
                'options' => $this->_yesNoOptions()
            ),
			'key_handling_mode' => array(
                'title' => esc_html__('Payment service key handling', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'select',
				'description' => esc_html__('It is impossible to revert back to manual mode after selecting automatic. Manual mode is still supported for existing installations if it was configured.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => 0,
                'options' => array(
                    0 => esc_html__('Automatic (Simple)', 'verifone-bluecommerce-for-woocommerce'),
                    1 => esc_html__('Manual (Advanced)', 'verifone-bluecommerce-for-woocommerce')
                )
            ),
            'keys_directory' => array(
                'title' => esc_html__('Directory for store keys', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Required. A path to the directory for generated files.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => '',
            ),
            'shop_private_keyfile' => array(
                'title' => esc_html__('Shop private key filename (production)', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Filename of shop secret key file generated with Verifone key pair generator.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => '',
            ),
            'shop_private_keyfile_test' => array(
                'title' => esc_html__('Shop private key filename (test)', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => esc_html__('Filename of shop secret key file generated with Verifone key pair generator.', 'verifone-bluecommerce-for-woocommerce'),
                'desc_tip' => self::DESC_TIP,
                'default' => '',
            ),
			'shop_public_key_ro' => array(
                'title' => esc_html__('Public key', 'verifone-bluecommerce-for-woocommerce'),
                'type' => 'text',
                'description' => wp_sprintf( wp_kses_post('Public key is used to sign requests and verify responses. Key is automatically generated. Test and production environments have different keys. Find key in use from <a href="%s">Site Health Info</a>.', 'verifone-bluecommerce-for-woocommerce'), admin_url( 'site-health.php?tab=debug' ) ),
                'desc_tip' => self::DESC_TIP,
                'default' => '',
            ),
			'reset_settings' => array(
                'title' => esc_html__('Reset settings', 'verifone-bluecommerce-for-woocommerce'),
				'type' => 'text',
				'description' =>
					esc_html__('Reset all settings to default values.', 'verifone-bluecommerce-for-woocommerce') .
					' <b>' . esc_html__('Resetting will cause payments not to work until settings are reconfigured.', 'verifone-bluecommerce-for-woocommerce') . '</b> ' .
					esc_html__('All settings will be lost and not recoverable.', 'verifone-bluecommerce-for-woocommerce') .
					'<br/><a href="' . add_query_arg( 'woocommerce_verifone_reset_settings', $reset_nonce, 'admin.php' ) . '" id="verifone-reset-settings-trigger" data-confirm="' . esc_html__('Reset will cause payments not to work until settings are reconfigured. Are you sure you want to reset the settings?', 'verifone-bluecommerce-for-woocommerce' ) . '">' . esc_html__('Reset settings, I know what I\'m doing.', 'verifone-bluecommerce-for-woocommerce') . '</a>',
				'desc_tip' => self::DESC_TIP,
            ),
        );

		// Call config only after the fields to avoid infinite loop
		$config = WC_Verifone_Config::getInstance();

		// Maybe hide some fields that are either too technical or not needed
		if (! $all ) {
			foreach ( self::HIDEABLE_FIELDS as $field_key ) {
				$field_value = $config->getData( $field_key);

				// Remove the field from the settings if it's empty
				if ( empty( $field_value ) ) {
					unset( $settings[$field_key] );
					continue;
				}

				// Remove the field from settings if it has default value
				if ( isset( $settings[$field_key]['default'] ) && $settings[$field_key]['default'] === $field_value ) {
					unset( $settings[$field_key] );
					continue;
				}
			}
		}

		// Hide key handling fields if key handling mode is set to automatic / simple
		if ( $config->isKeySimpleMode() ) {
			foreach ( self::HIDEABLE_KEY_HANDLING_FIELDS as $field_key ) {
				unset( $settings[$field_key] );
			}
		}

        return apply_filters( 'wc_verifone_settings', $settings, $all );
    }

    public function getDefaultValue($key) {
        $settings = $this->getSettings( true );

        if(isset($settings[$key]) && isset($settings[$key]['default'])) {
            return $settings[$key]['default'];
        }

        return null;
    }

    protected function _yesNoOptions() {
        return [
            0 => esc_html__('No', 'verifone-bluecommerce-for-woocommerce'),
            1 => esc_html__('Yes', 'verifone-bluecommerce-for-woocommerce')
        ];
    }
}
