<?php
/**
 * Forminator Square Hosted Checkout field.
 *
 * @package SHC4WC
 */

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

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

class SHC4WC_Forminator_Field extends Forminator_Field {

	/** @var string */
	public $name = '';

	/** @var string */
	public $slug = 'shc4wc_square';

	/** @var string */
	public $type = 'shc4wc_square';

	/** @var int */
	public $position = 25;

	/** @var array */
	public $options = array();

	/** @var string */
	public $icon = 'sui-icon-credit-card';

	/** @var bool */
	public $is_connected = false;

	public function __construct() {
		parent::__construct();

		$this->name         = esc_html__( 'Square Hosted Checkout', 'payments-connect-square' );
		$this->is_connected = SHC4WC_Plugin::is_connected();
	}

	/**
	 * @return array
	 */
	public function defaults() {
		return array(
			'field_label'         => esc_html__( 'Square Hosted Checkout', 'payments-connect-square' ),
			'currency'            => SHC4WC_Hosted_Checkout_Flow::default_currency(),
			'amount_type'         => 'fixed',
			'amount'              => '10',
			'variable'            => '',
			'product_description' => '',
		);
	}

	/**
	 * @param array                  $field     Field.
	 * @param Forminator_Render_Form $views_obj Render object.
	 * @return string
	 */
	public function markup( $field, $views_obj ) {
		unset( $views_obj );

		if ( ! SHC4WC_Plugin::is_connected() ) {
			return '<p class="shc4wc-forminator-payment-note">' . esc_html__( 'Square is not connected. Connect Payments Square Connect in wp-admin.', 'payments-connect-square' ) . '</p>';
		}

		$element_name = self::get_property( 'element_id', $field );
		$field_id     = $element_name . '-field';
		$currency     = self::get_property( 'currency', $field, SHC4WC_Hosted_Checkout_Flow::default_currency() );
		$amount_type  = self::get_property( 'amount_type', $field, 'fixed' );
		$amount       = self::get_property( 'amount', $field, '0' );
		$amount_var   = self::get_property( 'variable', $field, '' );

		$attr = array(
			'type'              => 'hidden',
			'name'              => $element_name,
			'id'                => 'forminator-' . $field_id . '_' . Forminator_CForm_Front::$uid,
			'class'             => 'forminator-shc4wc-square-input',
			'data-is-payment'   => 'true',
			'data-payment-type' => $this->type,
			'data-currency'     => esc_attr( strtolower( (string) $currency ) ),
			'data-amount-type'  => esc_attr( (string) $amount_type ),
			'data-amount'       => ( 'fixed' === $amount_type ? esc_attr( (string) $amount ) : esc_attr( (string) $amount_var ) ),
		);

		$html  = '<div class="shc4wc-forminator-payment-note">';
		$html .= esc_html__( 'After you submit this form, you will be redirected to Square to complete payment securely.', 'payments-connect-square' );
		$html .= '</div>';
		$html .= self::create_input( $attr );

		return apply_filters( 'forminator_field_shc4wc_square_markup', $html, $attr, $field );
	}

	/**
	 * @param array        $field Field.
	 * @param array|string $data  Data.
	 * @return array|string
	 */
	public function sanitize( $field, $data ) {
		$original_data = $data;
		$data          = forminator_sanitize_field( $data );

		return apply_filters( 'forminator_field_shc4wc_square_sanitize', $data, $field, $original_data );
	}

	/**
	 * @param mixed $field Field.
	 * @return bool
	 */
	public function is_available( $field ) {
		unset( $field );
		return SHC4WC_Plugin::is_connected();
	}

	/**
	 * @param array $field Field.
	 * @return array
	 */
	public function process_to_entry_data( $field ) {
		$currency = self::get_property( 'currency', $field, SHC4WC_Hosted_Checkout_Flow::default_currency() );
		$amount   = number_format( (float) $this->get_payment_amount( $field ), 2, '.', '' );
		$txn_id   = '';

		if ( class_exists( 'Forminator_CForm_Front_Action' ) && ! empty( Forminator_CForm_Front_Action::$prepared_data['payment_transaction_id'] ) ) {
			$txn_id = sanitize_text_field( (string) Forminator_CForm_Front_Action::$prepared_data['payment_transaction_id'] );
		}

		if ( '' === $txn_id ) {
			return array(
				'error' => esc_html__( 'Payment was not completed. Please try again.', 'payments-connect-square' ),
			);
		}

		return array(
			'status'           => 'COMPLETED',
			'amount'           => $amount,
			'currency'         => strtoupper( (string) $currency ),
			'transaction_id'   => $txn_id,
			'transaction_link' => '',
		);
	}

	/**
	 * @param array $field Field.
	 * @return float
	 */
	public function get_payment_amount( $field ) {
		$payment_amount = 0.0;
		$amount_type    = self::get_property( 'amount_type', $field, 'fixed' );
		$amount         = self::get_property( 'amount', $field, '0' );
		$amount_var     = self::get_property( 'variable', $field, '' );

		if ( 'fixed' === $amount_type ) {
			$payment_amount = $amount;
		} elseif ( class_exists( 'Forminator_CForm_Front_Action' ) && class_exists( 'Forminator_Front_Action' ) ) {
			$form_field = Forminator_Front_Action::$module_object
				? Forminator_Front_Action::$module_object->get_field( $amount_var, false )
				: null;

			if ( $form_field ) {
				$form_field = $form_field->to_formatted_array();
				if ( isset( $form_field['type'] ) ) {
					$field_id = $form_field['element_id'];
					if ( 'calculation' === $form_field['type'] && isset( Forminator_CForm_Front_Action::$prepared_data[ $amount_var ] ) ) {
						$payment_amount = Forminator_CForm_Front_Action::$prepared_data[ $amount_var ];
					} elseif ( 'currency' === $form_field['type'] && isset( Forminator_CForm_Front_Action::$prepared_data[ $field_id ] ) ) {
						$payment_amount = self::forminator_replace_number( $form_field, Forminator_CForm_Front_Action::$prepared_data[ $field_id ] );
					} else {
						$field_object = Forminator_Core::get_field_object( $form_field['type'] );
						if ( $field_object ) {
							$submitted_field_data = Forminator_CForm_Front_Action::$prepared_data[ $amount_var ] ?? null;
							$payment_amount       = $field_object::get_calculable_value( $submitted_field_data, $form_field );
						}
					}
				}
			}
		}

		if ( ! is_numeric( $payment_amount ) ) {
			$payment_amount = 0.0;
		}

		return (float) apply_filters(
			'forminator_field_shc4wc_square_payment_amount',
			$payment_amount,
			$field,
			class_exists( 'Forminator_Front_Action' ) ? Forminator_Front_Action::$module_object : null,
			class_exists( 'Forminator_CForm_Front_Action' ) ? Forminator_CForm_Front_Action::$prepared_data : array()
		);
	}

	/**
	 * @param array $field_settings Field settings.
	 * @return array
	 */
	public function get_amount_dependent_fields( $field_settings ) {
		$depend_field = array();
		$amount_type  = self::get_property( 'amount_type', $field_settings, 'fixed' );
		$amount_var   = self::get_property( 'variable', $field_settings, '' );

		if ( 'variable' === $amount_type && ! empty( $amount_var ) ) {
			$depend_field[] = $amount_var;
		}

		return $depend_field;
	}
}
