<?php
/**
 * Ninja Forms payment gateway (Collect Payment action).
 *
 * @package SHC4WC
 */

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

if ( ! class_exists( 'NF_Abstracts_PaymentGateway' ) ) {
	return;
}

class SHC4WC_Ninja_Forms_Gateway extends NF_Abstracts_PaymentGateway {

	const SLUG = 'payments_square_connect';

	protected $_slug = 'payments_square_connect';

	protected $_name = '';

	public function __construct() {
		$this->_name = __( 'Payments Square Connect', 'payments-connect-square' );
		parent::__construct();
	}

	/**
	 * @param array $action_settings Action settings.
	 * @param int   $form_id         Form id.
	 * @param array $data            Submission data.
	 * @return array
	 */
	protected function process( $action_settings, $form_id, $data ) {
		$amount = isset( $action_settings['payment_total'] ) ? (float) $action_settings['payment_total'] : 0;
		if ( $amount <= 0 ) {
			$data['errors']['form'] = __( 'Enter a valid payment amount.', 'payments-connect-square' );
			return $data;
		}

		$form_title = '';
		if ( class_exists( 'Ninja_Forms' ) ) {
			$form = Ninja_Forms()->form( $form_id )->get();
			if ( $form && method_exists( $form, 'get_setting' ) ) {
				$form_title = (string) $form->get_setting( 'title' );
			}
		}
		if ( '' === $form_title ) {
			$form_title = sprintf( __( 'Form %d', 'payments-connect-square' ), (int) $form_id );
		}

		$started = SHC4WC_Hosted_Checkout_Flow::start_one_time_payment(
			array(
				'type'        => 'ninjaforms',
				'amount'      => $amount,
				'currency'    => SHC4WC_Ninja_Forms::get_currency(),
				'description' => sprintf(
					/* translators: 1: form title, 2: reference placeholder. */
					__( 'Ninja Forms: %1$s', 'payments-connect-square' ),
					$form_title
				),
				'line_name'   => $form_title,
				'customer'    => SHC4WC_Ninja_Forms::extract_buyer_from_submission( $data ),
				'payload'     => array(
					'form_id'     => (int) $form_id,
					'data'        => $data,
					'return_url'  => SHC4WC_Ninja_Forms::submission_return_url( (int) $form_id ),
					'form_title'  => $form_title,
				),
			)
		);

		if ( is_wp_error( $started ) ) {
			$data['errors']['form'] = $started->get_error_message();
			return $data;
		}

		wp_redirect( esc_url_raw( $started['redirect'] ) ); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
		exit;
	}
}
