<?php
class HappyForms_Integration_Payments {

	private static $instance;

	private $frontend_styles = false;

	public $transaction_id_meta = 'transaction_id';
	public $transaction_details_meta = 'transaction_details';

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

		self::$instance->hook();

		return self::$instance;
	}

	public function hook() {
		require_once( happyforms_get_integrations_folder() . '/services/payments/helper-payments.php' );
		require_once( happyforms_get_integrations_folder() . '/services/payments/class-part-payments.php' );

		happyforms_get_part_library()->register_part( 'HappyForms_Part_Payments', 22 );

		add_filter( 'happyforms_message_part_value', array( $this, 'message_part_value' ), 10, 4 );
		add_filter( 'happyforms_email_part_value', array( $this, 'email_part_value' ), 10, 5 );
		add_filter( 'happyforms_stringify_part_value', array( $this, 'stringify_part_value' ), 10, 3 );
		add_filter( 'happyforms_default_validation_messages', array( $this, 'add_payment_validation_messages' ), 20 );
		add_filter( 'happyforms_messages_fields', array( $this, 'meta_messages_fields' ) );
		add_filter( 'happyforms_messages_controls', array( $this, 'get_message_controls' ) );

		$payment_details_parts = $this->get_details_supported_parts();

		foreach ( $payment_details_parts as $part ) {
			add_filter( "happyforms_part_customize_fields_{$part}", array( $this, 'add_part_fields' ) );
			add_action( "happyforms_part_customize_{$part}_before_advanced_options", array( $this, 'add_part_controls' ) );
		}
	}

	public function append_response_transaction( $response_id, $gateway, $status = 'pending', $transaction_id = '', $transaction_details = array() ) {
		$transaction_details = wp_parse_args( $transaction_details, array(
			'gateway' => $gateway,
			'status' => $status,
			'transaction_id' => $transaction_id,
		) );
		$transaction_id = "{$gateway}:{$transaction_id}";

		happyforms_update_meta( $response_id, $this->transaction_id_meta, $transaction_id );
		happyforms_update_meta( $response_id, $this->transaction_details_meta, $transaction_details );
	}

	public function stringify_part_value( $value, $part, $form ) {
		if ( 'payments' !== $part['type'] ) {
			return $value;
		}

		if ( empty( $value['payment_method'] ) ) {
			$value = __( 'N/A', 'happyforms' );
			return $value;
		}

		$currencies = happyforms_payment_get_currencies();
		$currency = $currencies[$value['currency']];
		$currency_format = $currency['format'];
		$currency_symbol = $currency['symbol'];
		$price = floatval( $value['price'] );
		$decimals = 'float' === $currency_format ? 2 : 0;
		$gateway = $value['payment_method'];

		$service = happyforms_get_integrations()->get_service( $gateway );
		$gateway_label = $service->label;
		$price_value = number_format( $price, $decimals );
		$paid_through = "&rarr;";
		$string = "{$currency_symbol}{$price_value} {$paid_through} {$gateway_label}";

		$string = apply_filters( 'happyforms_get_currency_value', $string, $value, $value['currency'] );

		return $string;
	}

	public function message_part_value( $value, $original_value, $part, $context ) {
		if ( 'payments' !== $part['type'] ) {
			return $value;
		}

		if ( 'admin-edit' !== $context ) {
			return $value;
		}

		global $post_id;

		$details = happyforms_payment_get_formatted_details( $post_id );
		$value = $value . "\n{$details}";

		return $value;
	}

	public function email_part_value( $value, $message, $part, $form, $context ) {
		if ( 'payments' !== $part['type'] ) {
			return $value;
		}

		if ( 'admin-email' !== $context ) {
			return $value;
		}

		$response_id = $message['ID'];
		$details = happyforms_payment_get_formatted_details( $response_id );
		$value = $value . "\n{$details}";

		return $value;
	}

	public function add_payment_validation_messages( $messages ) {
		$validation_messages = wp_list_pluck( $this->get_messages_fields(), 'default' );
		$messages = array_merge( $messages, $validation_messages );

		return $messages;
	}

	public function add_part_fields( $fields ) {
		$fields['add_to_payment_details'] = array(
			'default' => 0,
			'sanitize' => 'happyforms_sanitize_checkbox'
		);

		return $fields;
	}

	public function get_details_supported_parts() {
		return array(
			'single_line_text',
			'email',
			'website_url',
			'radio',
			'checkbox',
			'select',
			'number',
			'phone',
			'date',
			'title',
			'address',
		);
	}

	public function add_part_controls() {
		require( happyforms_get_integrations_folder() . '/services/payments/templates/partial-part-controls.php' );
	}

	public function get_transaction_description( $form, $submission ) {
		$description = array();

		foreach ( $form['parts'] as $part ) {
			if ( ! isset( $part['add_to_payment_details'] ) || 0 === (int) $part['add_to_payment_details'] ) {
				continue;
			}

			$part_id = $part['id'];
			$description[] = "{$part['label']}: {$submission[$part_id]}";
		}

		$description = implode( ', ', $description );

		return $description;
	}

	public function get_messages_fields() {
		$fields = array(
			'amount_too_low' => array(
				'default' => __( "Oops. This price isn't high enough.", 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'payment_completed' => array(
				'default' => __( 'Thank you! Your payment was successful.', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'payment_failed' => array(
				'default' => __( 'Ooops! Payment failed.', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'payment_cancelled' => array(
				'default' => __( 'Payment canceled.', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'payment_method_choice_label' => array(
				'default' => __( 'Choose a payment method', 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
			'user_price_label' => array(
				'default' => __( "Name a price", 'happyforms' ),
				'sanitize' => 'sanitize_text_field',
			),
		);

		return $fields;
	}


	public function meta_messages_fields( $fields ) {
		$fields = array_merge( $fields, $this->get_messages_fields() );

		return $fields;
	}

	public function get_message_controls( $controls ) {
		$controls[4340] = array(
			'type' => 'text',
			'label' => __( 'Price is too low', 'happyforms' ),
			'field' => 'amount_too_low',
		);
		$controls[200] = array(
			'type' => 'text',
			'label' => __( 'Payment completed', 'happyforms' ),
			'field' => 'payment_completed',
		);
		$controls[201] = array(
			'type' => 'text',
			'label' => __( 'Payment failed', 'happyforms' ),
			'field' => 'payment_failed',
		);
		$controls[202] = array(
			'type' => 'text',
			'label' => __( 'Payment cancelled', 'happyforms' ),
			'field' => 'payment_cancelled',
		);
		$controls[6135] = array(
			'type' => 'text',
			'label' => __( 'Payment method', 'happyforms' ),
			'field' => 'payment_method_choice_label',
		);
		$controls[6136] = array(
			'type' => 'text',
			'label' => __( "'Pay what you want' pricing label", 'happyforms' ),
			'field' => 'user_price_label',
		);

		return $controls;
	}


}

if ( ! function_exists( 'happyforms_get_payments_integration' ) ):

function happyforms_get_payments_integration() {
	return HappyForms_Integration_Payments::instance();
}

endif;

happyforms_get_payments_integration();
