<?php

/**
 * Woofunnel Ecom tracking
 * Class BWFAN_BWF_Ecom_Tracking
 */
class BWFAN_BWF_Ecom_Tracking extends BWFAN_Merge_Tag {

	private static $instance = null;

	public function __construct() {
		$this->tag_name        = 'ecom_tracking_data';
		$this->tag_description = __( 'Ecom Tracking Data', 'wp-marketing-automations-pro' );
		add_shortcode( 'bwfan_ecom_tracking_data', array( $this, 'parse_shortcode' ) );
	}

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

		return self::$instance;
	}

	/**
	 * Show the html in popup for the merge tag.
	 */
	public function get_view() {
		$handle_utm_fields = $this->get_view_data();
		$this->get_back_button();
		?>
        <div class="bwfan_mtag_wrap">
            <div class="bwfan_label">
                <label for="" class="bwfan-label-title"><?php esc_html_e( 'Select Ecom Tracking', 'wp-marketing-automations-pro' ); ?></label>
            </div>
            <div class="bwfan_label_val">
                <select id="" class="bwfan-input-wrapper bwfan_tag_select" name="data">
					<?php
					foreach ( $handle_utm_fields as $slug => $name ) {
						echo '<option value="' . esc_attr__( $slug ) . '">' . esc_attr__( $name ) . '</option>';
					}
					?>
                </select>
            </div>
        </div>
		<?php
		if ( $this->support_fallback ) {
			$this->get_fallback();
		}
		$this->get_preview();
		$this->get_copy_button();
	}

	public function get_view_data() {
		$handler_merge_key = array(
			'utm_campaign'    => __( 'UTM Campaign', 'wp-marketing-automations-pro' ),
			'utm_source'      => __( 'UTM Source', 'wp-marketing-automations-pro' ),
			'utm_term'        => __( 'UTM Term', 'wp-marketing-automations-pro' ),
			'utm_medium'      => __( 'UTM Medium', 'wp-marketing-automations-pro' ),
			'utm_content'     => __( 'UTM Content', 'wp-marketing-automations-pro' ),
			'funnel_id'       => __( 'Funnel ID', 'wp-marketing-automations-pro' ),
			'funnel_name'     => __( 'Funnel Name', 'wp-marketing-automations-pro' ),
			'referrer'        => __( 'Referrer', 'wp-marketing-automations-pro' ),
			'device'          => __( 'Device', 'wp-marketing-automations-pro' ),
			'browser'         => __( 'Browser', 'wp-marketing-automations-pro' ),
			'first_click'     => __( 'First Interaction', 'wp-marketing-automations-pro' ),
			'conversion_time' => __( 'Conversion Time', 'wp-marketing-automations-pro' ),
		);

		return apply_filters( 'bwfan_external_ecom_tracking_key', $handler_merge_key );
	}

	/**
	 * Parse the merge tag and return its value.
	 *
	 * @param $attr
	 *
	 * @return mixed|string|void
	 */
	public function parse_shortcode( $attr ) {
		if ( true === BWFAN_Merge_Tag_Loader::get_data( 'is_preview' ) ) {
			return $this->parse_shortcode_output( $this->get_dummy_preview(), $attr );
		}

		$data_key = ! isset( $attr['data'] ) ? 'utm_campaign' : $attr['data'];

		/** if order id available then get the details */
		$order_id = $this->get_order_id();
		if ( empty( $order_id ) ) {
			return $this->parse_shortcode_output( '', $attr );
		}

		global $wpdb;

		$query    = $wpdb->prepare( "SELECT * FROM " . $wpdb->prefix . "bwf_conversion_tracking WHERE `type` = 2 AND `source` = %d", $order_id );
		$get_data = $wpdb->get_row( $query, ARRAY_A );//phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		if ( empty( $get_data ) ) {
			return $this->parse_shortcode_output( '', $attr );
		}

		$value = '';
		switch ( $data_key ) {
			case "utm_campaign":
				$value = isset( $get_data['utm_campaign'] ) ? $get_data['utm_campaign'] : '';
				break;
			case "utm_term":
				$value = isset( $get_data['utm_term'] ) ? $get_data['utm_term'] : '';
				break;
			case "utm_content":
				$value = isset( $get_data['utm_content'] ) ? $get_data['utm_content'] : '';
				break;
			case "utm_medium":
				$value = isset( $get_data['utm_medium'] ) ? $get_data['utm_medium'] : '';
				break;
			case "utm_source":
				$value = isset( $get_data['utm_source'] ) ? $get_data['utm_source'] : '';
				break;
			case "funnel_id":
				$value = isset( $get_data['funnel_id'] ) ? $get_data['funnel_id'] : 0;
				break;
			case "funnel_name":
				$funnel_id = isset( $get_data['funnel_id'] ) ? $get_data['funnel_id'] : 0;
				if ( class_exists( 'WFFN_Funnel' ) && class_exists( 'WFFN_Common' ) && intval( $funnel_id ) > 0 ) {
					$funnel_obj = new WFFN_Funnel( $funnel_id );
					if ( $funnel_obj instanceof WFFN_Funnel && $funnel_obj->get_id() > 0 ) {
						$value = ! empty( $funnel_obj->get_title() ) ? $funnel_obj->get_title() : $funnel_obj->get_id();
					}
				}
				break;
			case "referrer":
				$value = isset( $get_data['referrer'] ) ? $get_data['referrer'] : '';
				break;
			case "device":
				$value = isset( $get_data['device'] ) ? $get_data['device'] : '';
				break;
			case "browser":
				$value = isset( $get_data['browser'] ) ? $get_data['browser'] : '';
				break;
			case "first_click":
				$value = isset( $get_data['first_click'] ) ? $get_data['first_click'] : '';
				break;
			case "conversion_time":
				$first_click = isset( $get_data['first_click'] ) ? $get_data['first_click'] : '';
				if ( ! empty( $first_click ) ) {
					$timestamp = isset( $get_data['timestamp'] ) ? $get_data['timestamp'] : '';
					$d1        = strtotime( $timestamp );
					$d2        = strtotime( $first_click );
					$value     = human_time_diff( $d1, $d2 );
				}
				break;
			default:
				break;
		}

		$value = apply_filters( 'bwfan_modify_ecom_tracking_key_val', $value, $order_id, $data_key, $get_data );

		return $this->parse_shortcode_output( $value, $attr );
	}

	public function get_order_id() {
		$order_id = absint( BWFAN_Merge_Tag_Loader::get_data( 'wc_order_id' ) );
		$order_id = ( 0 === $order_id ) ? absint( BWFAN_Merge_Tag_Loader::get_data( 'order_id' ) ) : $order_id;

		if ( 0 === $order_id ) {
			$order    = BWFAN_Merge_Tag_Loader::get_data( 'wc_order' );
			$order_id = $order instanceof WC_Order ? absint( BWFAN_Woocommerce_Compatibility::get_order_id( $order ) ) : 0;
		}

		return $order_id;
	}

	/**
	 * Show dummy value of the current merge tag.
	 *
	 * @return string
	 */
	public function get_dummy_preview() {
		return '';
	}

	/**
	 * Return mergetag schema
	 *
	 * @return array[]
	 */
	public function get_setting_schema() {
		$utm_ecom_data = $this->get_view_data();
		$utm_data      = [];
		foreach ( $utm_ecom_data as $utm_key => $utm_value ) {
			$utm_data[] = [
				'value' => $utm_key,
				'label' => $utm_value,
			];
		}

		return [
			[
				'id'          => 'data',
				'type'        => 'select',
				'options'     => $utm_data,
				'label'       => __( 'Select', 'wp-marketing-automations-pro' ),
				"class"       => 'bwfan-input-wrapper',
				"placeholder" => 'Select',
				"required"    => false,
				"description" => ""
			],
		];
	}
}

if ( class_exists( 'BWF_Ecomm_Tracking_Common' ) ) {
	BWFAN_Merge_Tag_Loader::register( 'wc_order', 'BWFAN_BWF_Ecom_Tracking' );
}
