<?php

if ( ! class_exists( 'GFForms' ) ) {
	die();
}

class Wiaas_Merge_Tag_Customer_Order_Url extends Gravity_Flow_Merge_Tag {

	/**
	 * Name of the merge tag
	 * 
	 * @var string
	 */
	public $name = 'customer_order_url';


	/**
	 * The regular expression to use for the matching.
	 *
	 * @var string
	 */
	protected $regex = '/{customer_order_url(:(.*?))?}/';


	public function replace( $text ) {

		$matches = $this->get_matches( $text );

		if ( ! empty( $matches ) ) {

			$entry = $this->entry;

			$form = GFAPI::get_form($entry['form_id']);

			$order_field = GFCommon::get_fields_by_type($form, 'wiaas_order')[0];

			if (empty($order_field)) {

				return $text;
			}

			$order_id = $entry[$order_field->id];

			$url = WIAAS_CUSTOMER_INTERFACE . '/orders/' . $order_id;

			$link = sprintf( '<a href="%s">%s</a>', $url, 'Order' );

			foreach ( $matches as $match ) {
				$full_tag = $match[0];

				$text = str_replace( $full_tag, $link, $text );
			}
		}

		return $text;
	}
}

Gravity_Flow_Merge_Tags::register( new Wiaas_Merge_Tag_Customer_Order_Url );