<?php
/**
 * Fluent Forms Square Hosted Checkout integration (free or Pro).
 *
 * @package SHC4WC
 */

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

class SHC4WC_FluentForms {
	const GATEWAY_KEY  = 'payments_square_connect';
	const GATEWAY_NAME = 'Payments Square Connect';

	/** @var self|null */
	private static $instance = null;

	/** @var bool */
	private static $gateway_booted = false;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'fluentform/loaded', array( $this, 'boot_gateway' ), 20 );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_success_styles' ), 20 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_settings_scripts' ) );
		add_filter( 'fluentform/rendering_form', array( $this, 'maybe_prepend_success_notice' ), 5, 2 );

		// Fluent Forms 6.x fires fluentform/loaded (fluentform_loaded is deprecated and may not run).
		if ( did_action( 'fluentform/loaded' ) ) {
			$this->boot_gateway();
		}
	}

	public function boot_gateway() {
		if ( self::$gateway_booted ) {
			return;
		}

		if ( ! self::has_payment_module() ) {
			return;
		}

		self::$gateway_booted = true;

		require_once SHC4WC_PLUGIN_DIR . 'includes/class-shc4wc-fluentforms-gateway.php';
		require_once SHC4WC_PLUGIN_DIR . 'includes/class-shc4wc-fluentforms-processor.php';

		$gateway = new SHC4WC_FluentForms_Gateway();
		$gateway->init();
	}

	/**
	 * Fluent Forms free ships payment base classes; Pro adds its own copies.
	 *
	 * @return bool
	 */
	public static function has_payment_module() {
		return class_exists( '\FluentForm\App\Modules\Payments\PaymentMethods\BasePaymentMethod' )
			|| class_exists( '\FluentFormPro\Payments\PaymentMethods\BasePaymentMethod' );
	}

	/**
	 * @param string $ref Reference id.
	 * @param string $key Verification key.
	 */
	public static function handle_return( $ref, $key ) {
		$ref = sanitize_text_field( (string) $ref );
		$key = sanitize_text_field( (string) $key );

		if ( '' === $ref || '' === $key || ! hash_equals( wp_hash( $ref . wp_salt( 'auth' ) ), $key ) ) {
			wp_safe_redirect( home_url( '/' ) );
			exit;
		}

		$stored = get_transient( 'shc4wc_fluentform_' . $ref );
		if ( ! is_array( $stored ) ) {
			wp_safe_redirect( home_url( '/' ) );
			exit;
		}

		SHC4WC_FluentForms_Processor::complete_stored_payment( $stored );
		delete_transient( 'shc4wc_fluentform_' . $ref );

		$url = ! empty( $stored['return_url'] ) ? (string) $stored['return_url'] : home_url( '/' );
		$url = add_query_arg( 'shc4wc_fluentform_paid', '1', $url );

		wp_safe_redirect( $url );
		exit;
	}

	/**
	 * @param object $form Fluent Forms row object (see fluentform/rendering_form).
	 * @return object
	 */
	public function maybe_prepend_success_notice( $form ) {
		if ( empty( $_GET['shc4wc_fluentform_paid'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return $form;
		}

		if ( ! is_object( $form ) || empty( $form->fields ) || ! is_array( $form->fields ) ) {
			return $form;
		}

		if ( empty( $form->fields['fields'] ) || ! is_array( $form->fields['fields'] ) ) {
			return $form;
		}

		$message = esc_html__( 'Thank you — your Square payment was received and your form was submitted.', 'payments-connect-square' );
		$banner  = '<div class="shc4wc-fluentform-payment-success" role="status">' . $message . '</div>';

		array_unshift(
			$form->fields['fields'],
			array(
				'index'          => -1,
				'element'        => 'custom_html',
				'attributes'     => array(),
				'settings'       => array(
					'html_codes'         => $banner,
					'conditional_logics' => array(),
					'container_class'    => '',
				),
				'editor_options' => array(
					'title'    => 'Custom HTML',
					'template' => 'customHTML',
				),
				'uniqElKey'      => 'shc4wc_fluentform_paid_notice',
			)
		);

		return $form;
	}

	public function enqueue_success_styles() {
		if ( empty( $_GET['shc4wc_fluentform_paid'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}

		$css = '.shc4wc-fluentform-payment-success{display:block;margin:0 0 1.5em;padding:1em 1.25em;border:2px solid #46b450;background:#ecf7ed;color:#1e4620;border-radius:4px;}';
		wp_register_style( 'shc4wc-fluentform-payment-success', false, array(), SHC4WC_VERSION );
		wp_enqueue_style( 'shc4wc-fluentform-payment-success' );
		wp_add_inline_style( 'shc4wc-fluentform-payment-success', $css );
	}

	/**
	 * Turn the plain connect URL in Fluent Forms inline help into a button link.
	 *
	 * @param string $hook Admin screen hook.
	 */
	public function enqueue_admin_settings_scripts( $hook ) {
		if ( false === strpos( (string) $hook, 'fluent_forms' ) ) {
			return;
		}

		$connect_url = SHC4WC_Connection_Settings::page_url();

		wp_register_script( 'shc4wc-fluentform-admin', false, array(), SHC4WC_VERSION, true );
		wp_enqueue_script( 'shc4wc-fluentform-admin' );
		wp_add_inline_script(
			'shc4wc-fluentform-admin',
			'(function(url,label){function linkify(){document.querySelectorAll(".payment-methods-item .text-note").forEach(function(el){if(el.dataset.shc4wcFf||el.textContent.indexOf(url)===-1){return;}el.dataset.shc4wcFf="1";el.innerHTML=el.innerHTML.replace(url,"<a class=\"button button-secondary\" href=\""+url+"\" style=\"margin-top:8px;display:inline-block\">"+label+"</a>");});}function run(){linkify();}var obs=new MutationObserver(run);if(document.body){obs.observe(document.body,{childList:true,subtree:true});}if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",run);}else{run();}})(' . wp_json_encode( $connect_url ) . ',' . wp_json_encode( __( 'Open Payments Square Connect', 'payments-connect-square' ) ) . ');'
		);
	}
}
