<?php
/**
 * Ninja Forms Square Hosted Checkout integration.
 *
 * @package SHC4WC
 */

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

class SHC4WC_Ninja_Forms {

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

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

	private function __construct() {
		add_filter( 'ninja_forms_register_payment_gateways', array( $this, 'register_gateway' ) );
		add_action( 'ninja_forms_display_before_form', array( $this, 'maybe_render_success_notice' ), 5, 2 );
		add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue_success_styles' ), 20 );
	}

	/**
	 * @param array $gateways Registered gateways.
	 * @return array
	 */
	public function register_gateway( $gateways ) {
		if ( ! SHC4WC_Plugin::is_connected() ) {
			return $gateways;
		}

		require_once SHC4WC_PLUGIN_DIR . 'includes/class-shc4wc-ninja-forms-gateway.php';
		if ( ! class_exists( 'SHC4WC_Ninja_Forms_Gateway' ) ) {
			return $gateways;
		}

		$gateways[ SHC4WC_Ninja_Forms_Gateway::SLUG ] = new SHC4WC_Ninja_Forms_Gateway();
		return $gateways;
	}

	/**
	 * @param int   $form_id Form id.
	 * @param array $data    Form display data.
	 * @return void
	 */
	public function maybe_render_success_notice( $form_id, $data ) {
		unset( $data );
		if ( empty( $_GET['shc4wc_ninjaforms_paid'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}
		if ( (int) $form_id !== (int) ( $_GET['shc4wc_nf_form'] ?? 0 ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}

		SHC4WC_Hosted_Checkout_Flow::render_success_notice(
			esc_html__( 'Thank you — your Square payment was received.', 'payments-connect-square' )
		);
	}

	/**
	 * @return void
	 */
	public function maybe_enqueue_success_styles() {
		if ( empty( $_GET['shc4wc_ninjaforms_paid'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return;
		}
		SHC4WC_Hosted_Checkout_Flow::enqueue_success_styles();
	}

	/**
	 * @param string $ref Reference id.
	 * @param string $key Return key.
	 * @return void
	 */
	public static function handle_return( $ref, $key ) {
		$stored = SHC4WC_Hosted_Checkout_Flow::pull_pending( 'ninjaforms', $ref, $key );
		if ( ! is_array( $stored ) ) {
			wp_safe_redirect( home_url( '/' ) );
			exit;
		}

		$url = ! empty( $stored['return_url'] ) ? (string) $stored['return_url'] : home_url( '/' );
		$url = add_query_arg(
			array(
				'shc4wc_ninjaforms_paid' => '1',
				'shc4wc_nf_form'         => isset( $stored['form_id'] ) ? (int) $stored['form_id'] : 0,
			),
			$url
		);

		wp_safe_redirect( $url );
		exit;
	}

	/**
	 * @param int $form_id Form id.
	 * @return string
	 */
	public static function submission_return_url( $form_id ) {
		$form_id = (int) $form_id;
		if ( $form_id > 0 && class_exists( 'Ninja_Forms' ) ) {
			$form = Ninja_Forms()->form( $form_id )->get();
			if ( $form && method_exists( $form, 'get_setting' ) ) {
				$permalink = (string) $form->get_setting( 'form_permalink' );
				if ( '' !== $permalink ) {
					return $permalink;
				}
			}
		}

		$referer = wp_get_referer();
		return $referer ? $referer : home_url( '/' );
	}

	/**
	 * @return string
	 */
	public static function get_currency() {
		return SHC4WC_Hosted_Checkout_Flow::default_currency();
	}

	/**
	 * @param array $data Ninja Forms submission data.
	 * @return array
	 */
	public static function extract_buyer_from_submission( $data ) {
		$customer = array(
			'email'       => '',
			'given_name'  => '',
			'family_name' => '',
			'phone'       => '',
			'wp_user_id'  => get_current_user_id(),
		);

		if ( empty( $data['fields'] ) || ! is_array( $data['fields'] ) ) {
			return $customer;
		}

		foreach ( $data['fields'] as $field ) {
			if ( ! is_array( $field ) ) {
				continue;
			}
			$value = isset( $field['value'] ) ? (string) $field['value'] : '';
			$type  = isset( $field['type'] ) ? (string) $field['type'] : '';
			$key   = isset( $field['key'] ) ? (string) $field['key'] : '';

			if ( '' === $customer['email'] && ( 'email' === $type || false !== stripos( $key, 'email' ) ) ) {
				$customer['email'] = sanitize_email( $value );
			}
			if ( '' === $customer['phone'] && ( 'phone' === $type || false !== stripos( $key, 'phone' ) ) ) {
				$customer['phone'] = sanitize_text_field( $value );
			}
			if ( '' === $customer['given_name'] && ( 'firstname' === $type || false !== stripos( $key, 'first' ) ) ) {
				$customer['given_name'] = sanitize_text_field( $value );
			}
			if ( '' === $customer['family_name'] && ( 'lastname' === $type || false !== stripos( $key, 'last' ) ) ) {
				$customer['family_name'] = sanitize_text_field( $value );
			}
		}

		return $customer;
	}
}
