<?php

namespace EDPW\Core\Controllers;
defined( 'ABSPATH' ) || exit;

use Liquid\Template;
use EDPW\Core\Helpers\EmailTemplate;
use EDPW\Core\Helpers\ShortCodes as ShortCodeHelper;
use EDPW\Core\Helpers\WC;

class ShortCodes {
	private $order = '', $type, $email_arguments, $html_template, $language, $sample = false;
	private $email_template;

	function __construct( $type, $template, $args, $order_id = '', $sample = false ) {
		$language = $template->language ?? '';
		if ( empty( $language ) ) {
			$language = WC::getSiteDefaultLang();
		}

		$this->order = null;
		if ( ! empty( $order_id ) ) {
			$this->order = WC::getOrder( $order_id );
		}
		$this->sample          = $sample;
		$this->html_template   = $template->html ?? '';
		$this->type            = $type;
		$this->email_arguments = $args;
		$this->language        = $language;
		if ( is_object( $template ) ) {
			$template->mj_component_data = ! empty( $template->mj_component_data ) && is_string( $template->mj_component_data ) ? json_decode( $template->mj_component_data, true ) : '';
			$template->global_styles     = ! empty( $template->global_styles ) && is_string( $template->global_styles ) ? json_decode( $template->global_styles, true ) : '';
		}
		$this->email_template = $template;
	}

	/**
	 * Render template.
	 *
	 * @param bool $encoded_content Need to encode.
	 *
	 * @return string
	 */
	function renderTemplate( $encoded_content = true, $is_preview = false ) {
		$liquid_template     = new Template();
		$this->html_template = apply_filters( 'edpw_get_raw_html_template', $this->html_template, [
			'order'           => $this->order,
			'template'        => $this->email_template,
			'email_arguments' => $this->email_arguments,
			'is_preview'      => $is_preview
		] );
		$liquid_template->parse( $this->html_template );
		$short_codes = $this->getShortCodeList();
		$html        = $liquid_template->render( $short_codes );
		$direction   = EmailTemplate::getLanguageDirection( $this->language );
		$html        = EmailTemplate::changeDirection( $html, $direction );
		if ( $encoded_content ) {
			$html = '<edpw>' . base64_encode( $html ) . '</edpw>';
		}

		return apply_filters( 'edpw_get_short_code_replaced_template', $html, $this->order, $encoded_content );
	}

	function renderSampleTemplate( $encoded_content = true, $is_preview = false ) {
		$liquid_template     = new Template();
		$short_code_values   = self::getSampleData( $this->type );
		$this->html_template = apply_filters( 'edpw_get_raw_html_template', $this->html_template, [
			'order'           => $this->order,
			'template'        => $this->email_template,
			'email_arguments' => $this->email_arguments,
			'is_preview'      => $is_preview
		] );
		$liquid_template->parse( $this->html_template );
		$html      = $liquid_template->render( $short_code_values );
		$direction = EmailTemplate::getLanguageDirection( $this->language );
		$html      = EmailTemplate::changeDirection( $html, $direction );
		if ( $encoded_content ) {
			$html = '<edpw>' . base64_encode( $html ) . '</edpw>';
		}

		return apply_filters( 'edpw_get_short_code_replaced_sample_template', $html, $this->order, $encoded_content );
	}

	public static function getSampleData( $type ) {
		$short_codes = [
			'billing_address'  => ShortCodeHelper::getAddressFields( 'billing', 'default' ),
			'shipping_address' => ShortCodeHelper::getAddressFields( 'shipping', 'default' ),
			'shipping_method'  => ShortCodeHelper::getShippingMethodFields( 'default' ),
			'order'            => ShortCodeHelper::getOrderFields( 'default' ),
			'payment'          => ShortCodeHelper::getPaymentFields( 'default' ),
			'customer'         => ShortCodeHelper::getCustomerFields( 'default' ),
			'shop'             => ShortCodeHelper::getShopFields( 'default' ),
			'social'           => ShortCodeHelper::getSocialFields( 'default' ),
			'wordpress'        => ShortCodeHelper::getWordPressFields( 'default' ),
			'order_meta'       =>
				[
					'_order_key'                             => 'sample',
					'_customer_user'                         => '0',
					'_payment_method'                        => 'cheque',
					'_payment_method_title'                  => 'Check payments',
					'_customer_ip_address'                   => '127.0.0.1',
					'_customer_user_agent'                   => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:72.0) Gecko/20100101 Firefox/72.0',
					'_created_via'                           => 'checkout',
					'_cart_hash'                             => '52e12998f191b8cec6ce6e23b58a841a',
					'_billing_first_name'                    => 'Cecilia',
					'_billing_last_name'                     => 'Chapman',
					'_billing_address_1'                     => '8105 West Brickell Drive',
					'_billing_city'                          => 'Pomona',
					'_billing_state'                         => 'CA',
					'_billing_postcode'                      => '92703',
					'_billing_country'                       => 'US',
					'_billing_email'                         => 'cecilia.chapman@flycart.test',
					'_billing_phone'                         => '563-7401',
					'_shipping_first_name'                   => 'Cecilia',
					'_shipping_last_name'                    => 'Chapman',
					'_shipping_address_1'                    => '8105 West Brickell Drive',
					'_shipping_city'                         => 'Pomona',
					'_shipping_state'                        => 'CA',
					'_shipping_postcode'                     => '92703',
					'_shipping_country'                      => 'US',
					'_order_currency'                        => 'INR',
					'_cart_discount'                         => '0',
					'_cart_discount_tax'                     => '0',
					'_order_shipping'                        => '50.00',
					'_order_shipping_tax'                    => '0',
					'_order_tax'                             => '0',
					'_order_total'                           => '690.00',
					'_order_version'                         => '3.9.1',
					'_prices_include_tax'                    => 'no',
					'_billing_address_index'                 => 'Cecilia Chapman  8105 West Brickell Drive  Pomona CA 92703 US cecilia.chapman@flycart.test 563-7401',
					'_shipping_address_index'                => 'Cecilia Chapman  8105 West Brickell Drive  Pomona CA 92703 US',
					'is_vat_exempt'                          => 'no',
					'_recorded_sales'                        => 'yes',
					'_recorded_coupon_usage_counts'          => 'yes',
					'_order_stock_reduced'                   => 'yes',
					'_woocs_order_rate'                      => '1',
					'_woocs_order_base_currency'             => 'INR',
					'_woocs_order_currency_changed_mannualy' => '0',
				]
		];

		return apply_filters( 'edpw_dummy_data', $short_codes, $type );
	}

	/**
	 * Get short code data.
	 * @return array
	 */
	function getShortCodeList() {

		if ( empty( $this->order ) && isset( $this->email_arguments['booking'] ) && ! empty( $this->email_arguments['booking'] ) && $this->email_arguments['booking']->order_id ) {
			$this->order = WC::getOrder( $this->email_arguments['booking']->order_id );
		}
		$response              = apply_filters( 'edpw_before_processing_short_codes', [
			'order'           => $this->order,
			'email_arguments' => $this->email_arguments
		] );
		$this->order           = ! empty( $response['order'] ) ? $response['order'] : $this->order;
		$this->email_arguments = ! empty( $response['email_arguments'] ) ? $response['email_arguments'] : $this->email_arguments;
		$short_codes           = [
			'billing_address'  => ShortCodeHelper::getAddressFields( 'billing', 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments
			] ),
			'shipping_address' => ShortCodeHelper::getAddressFields( 'shipping', 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments
			] ),
			'shipping_method'  => ShortCodeHelper::getShippingMethodFields( 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments
			] ),
			'order'            => ShortCodeHelper::getOrderFields( 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments,
				'language'        => $this->language,
				'email_template'  => $this->email_template,
				'extra_setting'   => []
			] ),
			'payment'          => ShortCodeHelper::getPaymentFields( 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments
			] ),
			'customer'         => ShortCodeHelper::getCustomerFields( 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments
			] ),
			'shop'             => ShortCodeHelper::getShopFields(),
			'social'           => ShortCodeHelper::getSocialFields(),
			'wordpress'        => ShortCodeHelper::getWordPressFields(),
			'order_meta'       => ShortCodeHelper::getOrderMetaFields( 'value', '', [
				'order'           => $this->order,
				'email_arguments' => $this->email_arguments
			] )
		];

		if ( ! empty( $short_codes['order']['id'] ) && ! isset( $this->email_arguments['booking'] ) ) {
			$booking_post = get_children( array(
				'numberposts' => 1,
				'post_type'   => 'wc_booking',
				'post_status' => 'any',
				'post_parent' => $short_codes['order']['id'],
			) );
			$booking_post = reset( $booking_post );
			if ( ! empty( $booking_post ) ) {
				$booking_id                       = $booking_post->ID;
				$this->email_arguments['booking'] = get_wc_booking( $booking_id );
			}
		}

		return apply_filters( 'edpw_after_template_short_codes', $short_codes, $this->order, $this->email_arguments, $this->sample );
	}
}