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

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

class SHC4WC_Formidable {

	const GATEWAY = 'payments_square_connect';

	/** @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() {
		require_once SHC4WC_PLUGIN_DIR . 'includes/class-frm-shc4wc-hosted-actions-controller.php';

		add_filter( 'frm_payment_gateways', array( $this, 'register_gateway' ) );
		add_filter( 'frm_success_filter', array( $this, 'maybe_force_message' ), 5 );
		add_filter( 'frm_main_feedback', array( $this, 'maybe_success_message' ), 5 );
		add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue_success_styles' ), 20 );
	}

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

		$gateways[ self::GATEWAY ] = array(
			'label'      => __( 'Payments Square Connect', 'payments-connect-square' ),
			'user_label' => __( 'Payment', 'payments-connect-square' ),
			'class'      => 'Shc4wcHosted',
			'recurring'  => false,
			'include'    => array(
				'billing_first_name',
				'billing_last_name',
			),
		);

		return $gateways;
	}

	/**
	 * @return string
	 */
	public function maybe_force_message() {
		if ( empty( $_GET['shc4wc_formidable_paid'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return 'message';
		}
		return 'message';
	}

	/**
	 * @param string $message Existing message.
	 * @return string
	 */
	public function maybe_success_message( $message ) {
		if ( empty( $_GET['shc4wc_formidable_paid'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			return $message;
		}

		$text = esc_html__( 'Thank you — your Square payment was received.', 'payments-connect-square' );
		return '<div class="frm_message shc4wc-formidable-payment-success">' . $text . '</div>';
	}

	/**
	 * @return void
	 */
	public function maybe_enqueue_success_styles() {
		if ( empty( $_GET['shc4wc_formidable_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( 'formidable', $ref, $key );
		if ( ! is_array( $stored ) || empty( $stored['entry_id'] ) || empty( $stored['action_id'] ) ) {
			wp_safe_redirect( home_url( '/' ) );
			exit;
		}

		if ( ! class_exists( 'FrmTransLitePayment' ) || ! class_exists( 'FrmTransLiteActionsController' ) ) {
			wp_safe_redirect( home_url( '/' ) );
			exit;
		}

		$entry_id  = (int) $stored['entry_id'];
		$action_id = (int) $stored['action_id'];
		$amount    = isset( $stored['amount'] ) ? (float) $stored['amount'] : 0;
		$action    = FrmTransLiteAction::get_single_action_type( $action_id, 'payment' );

		$square_payment_id = '';
		if ( class_exists( 'SHC4WC_Plugin' ) && ! empty( $stored['square_order_id'] ) ) {
			$square_payment_id = SHC4WC_Plugin::instance()->retrieve_square_payment_id_for_hosted_checkout(
				(string) $stored['square_order_id'],
				(string) ( $stored['link_id'] ?? '' ),
				'',
				time()
			);
		}

		$frm_payment = new FrmTransLitePayment();
		$payment_id  = $frm_payment->create(
			array(
				'amount'     => $amount,
				'status'     => 'complete',
				'paysys'     => self::GATEWAY,
				'item_id'    => $entry_id,
				'action_id'  => $action_id,
				'receipt_id' => $square_payment_id ? $square_payment_id : (string) $ref,
				'sub_id'     => '',
				'test'       => 0,
			)
		);

		$payment = $frm_payment->get_one( $payment_id );
		if ( $payment && $action ) {
			FrmTransLiteActionsController::trigger_payment_status_change(
				array(
					'status'  => 'complete',
					'payment' => $payment,
				)
			);
		}

		$url = ! empty( $stored['return_url'] ) ? (string) $stored['return_url'] : home_url( '/' );
		$url = SHC4WC_Hosted_Checkout_Flow::add_paid_query_arg( $url, 'shc4wc_formidable_paid' );
		if ( ! empty( $stored['form_id'] ) ) {
			$url = add_query_arg( 'frm_form', (int) $stored['form_id'], $url );
		}

		wp_safe_redirect( $url );
		exit;
	}

	/**
	 * @param int $form_id Form id.
	 * @return string
	 */
	public static function entry_return_url( $form_id ) {
		$form_id = (int) $form_id;
		if ( $form_id > 0 && class_exists( 'FrmForm' ) ) {
			$form = FrmForm::getOne( $form_id );
			if ( $form && ! empty( $form->form_key ) ) {
				return FrmForm::get_form_url( $form );
			}
		}

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

	/**
	 * @param WP_Post  $action Payment action.
	 * @param stdClass $entry  Entry.
	 * @return array
	 */
	public static function extract_buyer_from_entry( $action, $entry ) {
		$customer = array(
			'email'       => '',
			'given_name'  => '',
			'family_name' => '',
			'phone'       => '',
			'wp_user_id'  => get_current_user_id(),
		);

		if ( ! class_exists( 'FrmEntryMeta' ) || ! is_object( $entry ) ) {
			return $customer;
		}

		$content = is_object( $action ) ? (array) $action->post_content : array();
		$map     = array(
			'email'             => 'email',
			'billing_first_name'=> 'given_name',
			'billing_last_name' => 'family_name',
		);

		foreach ( $map as $setting_key => $customer_key ) {
			if ( empty( $content[ $setting_key ] ) ) {
				continue;
			}
			$value = FrmTransLiteAppHelper::process_shortcodes(
				array(
					'entry' => $entry,
					'form'  => $entry->form_id,
					'value' => $content[ $setting_key ],
				)
			);
			if ( 'email' === $customer_key ) {
				$customer[ $customer_key ] = sanitize_email( (string) $value );
			} else {
				$customer[ $customer_key ] = sanitize_text_field( (string) $value );
			}
		}

		return $customer;
	}
}
