<?php
/**
 * Fluent Forms payment method registration.
 *
 * @package SHC4WC
 */

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

class SHC4WC_FluentForms_Gateway extends \FluentForm\App\Modules\Payments\PaymentMethods\BasePaymentMethod {
	public function __construct() {
		parent::__construct( SHC4WC_FluentForms::GATEWAY_KEY );
	}

	public function init() {
		add_filter( 'fluentform/payment_method_settings_validation_' . $this->key, array( $this, 'validateSettings' ), 10, 2 );
		add_filter( 'fluentform/payment_method_settings_save_' . $this->key, array( $this, 'sanitizeGlobalSettings' ), 10, 1 );
		add_filter( 'fluentform/payment_methods_global_settings', array( $this, 'register_global_settings' ) );
		add_filter( 'fluentform/payment_settings_' . $this->key, array( $this, 'filter_payment_settings' ) );
		add_filter( 'fluentform/transaction_data_' . $this->key, array( $this, 'modifyTransaction' ), 10, 1 );
		add_filter( 'fluentform/payment_method_public_name_' . $this->key, array( $this, 'publicName' ) );
		add_action( 'shc4wc_square_disconnected', array( $this, 'disable_on_square_disconnect' ) );

		if ( ! $this->isEnabled() ) {
			return;
		}

		add_filter( 'fluentform/available_payment_methods', array( $this, 'pushPaymentMethodToForm' ) );
		add_filter( 'fluentform/payment_method_contents_' . $this->key, array( $this, 'renderHostedCheckoutNotice' ), 10, 4 );
		add_action( 'fluentform/rendering_payment_method_' . $this->key, array( $this, 'enqueueFormStyles' ) );

		$processor = new SHC4WC_FluentForms_Processor();
		$processor->init();
	}

	/**
	 * @param array<string, mixed> $settings Global payment settings.
	 * @return array<string, mixed>
	 */
	public function register_global_settings( $settings ) {
		$settings[ $this->key ] = $this->getGlobalFields();
		return $settings;
	}

	/**
	 * @param array<string, mixed> $settings Saved settings.
	 * @return array<string, mixed>
	 */
	public function filter_payment_settings( $settings ) {
		return $this->getGlobalSettings();
	}

	/**
	 * @param array<string, mixed> $methods Payment methods.
	 * @return array<string, mixed>
	 */
	public function pushPaymentMethodToForm( $methods ) {
		$methods[ $this->key ] = array(
			'title'        => SHC4WC_FluentForms::GATEWAY_NAME,
			'enabled'      => 'yes',
			'method_value' => $this->key,
			'settings'     => array(
				'option_label' => array(
					'type'     => 'text',
					'template' => 'inputText',
					'value'    => __( 'Pay with Square', 'payments-connect-square' ),
					'label'    => __( 'Method label', 'payments-connect-square' ),
				),
			),
		);

		return $methods;
	}

	/**
	 * @param object $transaction Transaction row.
	 * @return object
	 */
	public function modifyTransaction( $transaction ) {
		$transaction->payment_method = SHC4WC_FluentForms::GATEWAY_NAME; // phpcs:ignore WordPress.NamingConventions.ValidVariableName
		return $transaction;
	}

	public function publicName() {
		return __( 'Square Hosted Checkout', 'payments-connect-square' );
	}

	/**
	 * Fluent Forms hides the payment-method radios when only one gateway is enabled.
	 * Show a short notice so buyers know they will pay on Square after submit.
	 *
	 * @param string               $contents Existing markup.
	 * @param array<string, mixed> $method   Method config.
	 * @param array<string, mixed> $data     Field data.
	 * @param object               $form     Form object.
	 * @return string
	 */
	public function renderHostedCheckoutNotice( $contents, $method, $data, $form ) {
		unset( $data, $form );

		$label = isset( $method['settings']['option_label']['value'] )
			? (string) $method['settings']['option_label']['value']
			: __( 'Pay with Square', 'payments-connect-square' );

		$display = ! empty( $method['is_default'] ) ? 'block' : 'none';

		$markup  = '<div class="shc4wc-square-hosted-notice ff_pay_inline ff_pay_inline_' . esc_attr( $this->key ) . '" style="display:' . esc_attr( $display ) . ';">';
		$markup .= '<p class="shc4wc-square-hosted-notice__label"><strong>' . esc_html( $label ) . '</strong></p>';
		$markup .= '<p class="shc4wc-square-hosted-notice__hint">' . esc_html__( 'After you submit this form you will be redirected to Square to pay securely (card, Apple Pay, Google Pay, and more).', 'payments-connect-square' ) . '</p>';

		if ( 'sandbox' === SHC4WC_Plugin::get_current_environment() ) {
			$markup .= '<p class="shc4wc-square-hosted-notice__sandbox">' . esc_html__( 'Square Sandbox — test payments only. No real charges.', 'payments-connect-square' ) . '</p>';
		}

		$markup .= '</div>';

		return $contents . $markup;
	}

	public function enqueueFormStyles() {
		$css = '.shc4wc-square-hosted-notice{margin:0 0 1em;padding:.85em 1em;border:1px solid #d0d7de;border-radius:4px;background:#f6f8fa;} .shc4wc-square-hosted-notice__label{margin:0 0 .35em;} .shc4wc-square-hosted-notice__hint{margin:0;font-size:.92em;color:#57606a;} .shc4wc-square-hosted-notice__sandbox{margin:.5em 0 0;font-size:.88em;font-style:italic;color:#9a6700;}';
		wp_register_style( 'shc4wc-fluentform-square-notice', false, array(), SHC4WC_VERSION );
		wp_enqueue_style( 'shc4wc-fluentform-square-notice' );
		wp_add_inline_style( 'shc4wc-fluentform-square-notice', $css );
	}

	/**
	 * @return array<string, mixed>
	 */
	public function getGlobalFields() {
		$connected = SHC4WC_Plugin::is_connected();
		$fields    = array();

		if ( $connected ) {
			$fields[] = array(
				'type'         => 'notice',
				'settings_key' => 'shc4wc_environment',
				'label'        => __( 'Environment', 'payments-connect-square' ),
				'inline_help'  => $this->get_environment_inline_help(),
			);
		}

		$fields[] = array(
			'type'           => 'yes-no-checkbox',
			'settings_key'   => 'is_active',
			'label'          => __( 'Status', 'payments-connect-square' ),
			'checkbox_label' => __( 'Enable Payments Square Connect for Fluent Forms', 'payments-connect-square' ),
			'inline_help'    => $connected
				? __( 'Buyers are redirected to Square Hosted Checkout after they submit a form with a payment field.', 'payments-connect-square' )
				: $this->get_connect_required_inline_help(),
		);

		return array(
			'label'  => SHC4WC_FluentForms::GATEWAY_NAME,
			'fields' => $fields,
		);
	}

	/**
	 * Plain-text environment summary (Fluent Forms payment settings only render select field types).
	 *
	 * @return string
	 */
	private function get_environment_inline_help() {
		$env  = SHC4WC_Plugin::get_current_environment();
		$link = SHC4WC_Connection_Settings::page_url();

		if ( 'sandbox' === $env ) {
			$message = __( 'Square Sandbox is active — test payments only. No real money is charged.', 'payments-connect-square' );
		} else {
			$message = __( 'Square Live mode is active — real payments are processed.', 'payments-connect-square' );
		}

		return $message . ' ' . sprintf(
			/* translators: %s: Payments Square Connect settings URL */
			__( 'Manage connection: %s', 'payments-connect-square' ),
			$link
		);
	}

	/**
	 * Message shown when Square is not connected for the active environment.
	 *
	 * @return string
	 */
	private function get_connect_required_inline_help() {
		$env  = SHC4WC_Plugin::get_current_environment();
		$link = SHC4WC_Connection_Settings::page_url();
		$env_label = ( 'sandbox' === $env )
			? __( 'Sandbox', 'payments-connect-square' )
			: __( 'Live', 'payments-connect-square' );

		return sprintf(
			/* translators: 1: Sandbox or Live, 2: Payments Square Connect settings URL */
			__( 'Square is not connected for %1$s mode yet. Open Payments Square Connect, connect your Square account, and choose a location. Then return here to enable Fluent Forms payments. %2$s', 'payments-connect-square' ),
			$env_label,
			$link
		);
	}

	/**
	 * @param array<string, mixed> $settings Settings payload.
	 * @return array<string, mixed>
	 */
	public function sanitizeGlobalSettings( $settings ) {
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}

		if ( ! SHC4WC_Plugin::is_connected() ) {
			$settings['is_active'] = 'no';
		}

		return $settings;
	}

	/**
	 * Keep Fluent Forms disabled when Square is disconnected.
	 */
	public function disable_on_square_disconnect() {
		$settings = get_option( 'fluentform_payment_settings_' . $this->key, array() );
		if ( ! is_array( $settings ) ) {
			$settings = array();
		}
		$settings['is_active'] = 'no';
		update_option( 'fluentform_payment_settings_' . $this->key, $settings, false );
	}

	/**
	 * @return array<string, string>
	 */
	public function getGlobalSettings() {
		$saved = get_option( 'fluentform_payment_settings_' . $this->key, array() );
		$settings = is_array( $saved ) ? $saved : array();

		if ( ! SHC4WC_Plugin::is_connected() ) {
			$settings['is_active'] = 'no';
			return $settings;
		}

		if ( ! isset( $settings['is_active'] ) ) {
			$settings['is_active'] = 'yes';
		}

		return $settings;
	}

	public function isEnabled() {
		$settings = $this->getGlobalSettings();
		if ( 'yes' !== ( $settings['is_active'] ?? 'no' ) ) {
			return false;
		}

		return SHC4WC_Plugin::is_connected();
	}

	/**
	 * @param array<string, string> $errors   Validation errors.
	 * @param array<string, mixed>  $settings Settings payload.
	 * @return array<string, string>
	 */
	public function validateSettings( $errors, $settings ) {
		if ( ! empty( $settings['is_active'] ) && 'yes' === $settings['is_active'] && ! SHC4WC_Plugin::is_connected() ) {
			$errors['is_active'] = __( 'Connect Square under Payments Square Connect before enabling this gateway.', 'payments-connect-square' );
		}

		return $errors;
	}
}
