<?php

namespace ESCT\App\Controllers;

defined( 'ABSPATH' ) || exit;

use EDPW\Core\Helpers\EmailTemplate;
use EDPW\Core\Helpers\ShortCodes;
use EDPW\Core\Helpers\Util;
use EDPW\Core\Helpers\WC;
use WC_Order;

class Subscription {

	protected static $subscription_templates = [
		'cancelled_subscription',
		'customer_completed_renewal_order',
		'customer_completed_switch_order',
		'customer_on_hold_renewal_order',
		'customer_processing_renewal_order',
		'customer_renewal_invoice',
		'expired_subscription',
		'new_renewal_order',
		'new_switch_order',
		'suspended_subscription',
		'customer_payment_retry',
		'payment_retry'
	];

	/**
	 * Add admin menu.
	 * @return void
	 */
	public static function addAdminMenu() {
		if ( WC::hasAdminPrivilege() ) {
			add_menu_page( ESCT_PLUGIN_NAME, ESCT_PLUGIN_NAME, 'manage_woocommerce', ESCT_PLUGIN_SLUG, [
				self::class,
				'displayMenuContent'
			], 'dashicons-megaphone', 57 );
		}
	}

	/**
	 * Hide add-on menu.
	 * @return void
	 */
	public static function hideMenu() {
		?>
        <style>
            #toplevel_page_esct-subscription-compatibility {
                display: none !important;
            }
        </style>
		<?php
	}

	/**
	 * Display menu content.
	 * @return void
	 */
	public static function displayMenuContent() {
		if ( ! WC::hasAdminPrivilege() ) {
			return;
		}
		wc_get_template( 'main.php', [], '', ESCT_PLUGIN_DIR . '/App/Views/Admin/' );
	}

	/**
	 * List subscription short codes.
	 *
	 * @param array $short_codes Short codes.
	 * @param string $type Email type.
	 *
	 * @return array
	 */
	public static function addShortCodes( $short_codes, $type ) {

		if ( ! is_array( $short_codes ) ) {
			return $short_codes;
		}

		if ( ! in_array( $type, self::$subscription_templates ) ) {
			return $short_codes;
		}
		$short_codes['subscription'] = [
			'label'       => __( 'Subscription', 'email-editor-plus' ),
			'short_codes' => EmailTemplate::formatShortCode( self::getShortCodes( 'desc', 'subscription.' ) )
		];

		return self::processShortCodeList( $type, $short_codes );
	}

	public static function processShortCodeList( $type, $short_codes ) {
		if ( ! is_string( $type ) || ! is_array( $short_codes ) || ! in_array( $type, self::$subscription_templates ) ) {
			return $short_codes;
		}
		switch ( $type ) {
			case 'new_renewal_order':
			case 'customer_completed_renewal_order':
			case 'customer_completed_switch_order':
			case 'customer_on_hold_renewal_order':
			case 'customer_processing_renewal_order':
			case 'customer_renewal_invoice':
			case 'expired_subscription':
			case 'new_switch_order':
			case 'suspended_subscription':
				$ignore_short_codes = [
					'subscription' => [
						'{{subscription.cancelled}}',
						'{{subscription.retry_time}}'
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
			case 'payment_retry';
			case 'customer_payment_retry':
				$ignore_short_codes = [
					'subscription' => [
						'{{subscription.cancelled}}'
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
		}

		return $short_codes;
	}

	/**
	 * Add dummy data.
	 *
	 * @param array $short_codes short codes.
	 *
	 * @return array
	 */
	public static function addDummyData( $short_codes, $type ) {
		if ( ! is_array( $short_codes ) ) {
			return $short_codes;
		}
		if ( ! in_array( $type, self::$subscription_templates ) ) {
			return $short_codes;
		}
		$short_codes['subscription'] = self::getShortCodes( 'default' );

		return $short_codes;
	}

	/**
	 * Get subscription short codes.
	 * @return array
	 */
	public static function getShortCodes( $type = 'value', $pre_fix = '', $args = [] ) {
		$default = [
			'order'           => '',
			'subscription'    => '',
			'email_arguments' => [],
		];
		$args    = wp_parse_args( $args, $default );
		extract( $args );
		$fields = apply_filters( ESCT_PLUGIN_PREFIX . '_subscription_short_codes', [
			'detail'                  => [
				'value'   => self::getSubscriptionDetailTable( $subscription, $order ),
				'desc'    => __( 'To load the subscription details in table format', 'email-editor-plus' ),
				'default' => ''
			],
			'start_on'                => [
				'value'   => self::getSubscriptionDate( $subscription ),
				'desc'    => __( 'Display subscription start date', 'email-editor-plus' ),
				'default' => ''
			],
			'end_on'                  => [
				'value'   => self::getSubscriptionDate( $subscription, 'end' ),
				'desc'    => __( 'Display subscription end date', 'email-editor-plus' ),
				'default' => ''
			],
			'next_payment'            => [
				'value'   => self::getSubscriptionDate( $subscription, 'next_payment' ),
				'desc'    => __( 'Display subscription next payment date', 'email-editor-plus' ),
				'default' => ''
			],
			'trial_end'               => [
				'value'   => self::getSubscriptionDate( $subscription, 'trial_end' ),
				'desc'    => __( 'Display subscription trial end date', 'email-editor-plus' ),
				'default' => ''
			],
			'cancelled'               => [
				'value'   => self::getSubscriptionDate( $subscription, 'cancelled' ),
				'desc'    => __( 'Display subscription cancelled date', 'email-editor-plus' ),
				'default' => ''
			],
			'payment_retry'           => [
				'value'   => self::getSubscriptionDate( $subscription, 'payment_retry' ),
				'desc'    => __( 'Display subscription payment retry date', 'email-editor-plus' ),
				'default' => ''
			],
			'last_order_date_created' => [
				'value'   => self::getSubscriptionDate( $subscription, 'last_order_date_created' ),
				'desc'    => __( 'Display subscription last order created date', 'email-editor-plus' ),
				'default' => ''
			],
			'retry_time'              => [
				'value'   => self::getSubscriptionOrderRetryTime( $email_arguments ),
				'desc'    => __( 'Display subscription payment retry time', 'email-editor-plus' ),
				'default' => ''
			]
		], $type );

		return ShortCodes::getFieldData( $fields, $type, $pre_fix );
	}

	public static function getSubscriptionOrderRetryTime( $email_arguments ) {
		$retry_time = '';
		if ( ! empty( $email_arguments['retry'] ) && is_object( $email_arguments['retry'] ) ) {
			$retry_time = wcs_get_human_time_diff( $email_arguments['retry']->get_time() );
		}

		return $retry_time;
	}

	/**
	 * Add subscription short codes.
	 *
	 * @param array $short_codes Short code list.
	 * @param WC_Order $order Order object.
	 * @param array $args Arguments.
	 * @param bool $sample Is sample data.
	 *
	 * @return array
	 */
	public static function getTemplateShortCodes( $short_codes, $order, $args, $sample ) {
		if ( ! is_array( $short_codes ) ) {
			return $short_codes;
		}
		if ( isset( $args['subscription'] ) ) {
			$subscription = $args['subscription'];
		} else if ( $order ) {
			$subscription_id = self::getSubscriptionIdFromOrder( $order );
			$subscription    = function_exists( 'wcs_get_subscription' ) ? wcs_get_subscription( $subscription_id ) : '';
		}
		if ( empty( $subscription ) && isset( $args['subscriptions'] ) && ! empty( $args['subscriptions'] ) ) {
			foreach ( $args['subscriptions'] as $subscription_id => $subscription_obj ) {
				if ( $subscription_obj->get_parent()->get_id() ) {
					$subscription = $subscription_obj;
				}
			}
		}
		if ( empty( $subscription ) ) {
			return $short_codes;
		}
		$short_codes['subscription'] = $sample && empty( $order ) ? self::getShortCodes( 'default' ) : self::getShortCodes( 'value', '', [
			'order'           => $order,
			'subscription'    => $subscription,
			'email_arguments' => $args
		] );

		return apply_filters( ESCT_PLUGIN_PREFIX . '_subscription_additional_short_codes', $short_codes, $order, $args, $sample );
	}

	/**
	 * Get subscription id from order.
	 *
	 * @param WC_Order $order Order object.
	 *
	 * @return int
	 */
	public static function getSubscriptionIdFromOrder( $order ) {
		if ( ! is_object( $order ) ) {
			return 0;
		}

		$order_id = WC::getOrderId( $order );
		if ( $order_id <= 0 ) {
			return 0;
		}
		if ( WC::isMethodExists( $order, 'get_type' ) && $order->get_type() == 'shop_subscription' ) {
			return $order_id;
		}
		$subscription_ids = function_exists( 'wcs_get_subscriptions_for_order' ) ? wcs_get_subscriptions_for_order( $order_id ) : [];
		if ( ! empty( $subscription_ids ) ) {
			foreach ( $subscription_ids as $subscription_id => $subscription_obj ) {
				if ( $subscription_obj->get_parent()->get_id() == $order_id ) {
					return $subscription_id;
				}
			}
		}

		$subscription = function_exists( 'wcs_get_subscription' ) ? wcs_get_subscription( $order_id ) : '';
		if ( ! empty( $subscription ) ) {
			return $order_id;
		}

		$subscription_ids = function_exists( 'wcs_get_subscriptions_for_renewal_order' ) ? wcs_get_subscriptions_for_renewal_order( $order_id ) : [];
		if ( ! empty( $subscription_ids ) ) {
			foreach ( $subscription_ids as $subscription_id => $subscription_obj ) {
				return $subscription_id;
			}
		}

		return 0;
	}


	/**
	 * Get subscription details in table.
	 *
	 * @param object $subscription Subscription object.
	 * @param WC_Order $order Order object.
	 *
	 * @return string
	 */
	protected static function getSubscriptionDetailTable( $subscription, $order ) {
		if ( empty( $subscription ) ) {
			return '';
		}
		$template_path = ESCT_PLUGIN_PATH . 'App/Views/Site/subscription_details.php';
		$override_path = get_theme_file_path( EDPW_PLUGIN_SLUG . '/templates/subscription_details.php' );
		if ( file_exists( $override_path ) ) {
			$template_path = $override_path;
		}
		$content = Util::renderTemplate( $template_path, [
			'subscription' => $subscription,
			'order'        => $order
		] );
		$css     = EmailTemplate::getSetting( 'custom_css', EmailTemplate::getDefaultCustomCss() );

		return apply_filters( ESCT_PLUGIN_PREFIX . '_woocommerce_subscription_details_table', WC::styleInline( $content, $css ), $subscription, $order );
	}

	/**
	 * Get subscription date data.
	 *
	 * @param object $subscription Subscription object.
	 * @param string $type date type.
	 *
	 * @return string
	 */
	public static function getSubscriptionDate( $subscription, $type = 'start' ) {
		if ( ! is_object( $subscription ) ) {
			return '';
		}

		if ( WC::isMethodExists( $subscription, 'get_time' ) ) {
			$date_of_type = $subscription->get_time( $type, 'site' );
			if ( ! empty( $date_of_type ) ) {
				return date_i18n( wc_date_format(), $date_of_type );
			}
		}

		return '';
	}

	/**
	 * Add booking template images.
	 *
	 * @param array $templates Template lists.
	 * @param string $name Template group name.
	 * @param string $type Template type.
	 *
	 * @return array
	 */
	public static function addTemplateImage( $templates, $name, $type ) {
		$all_templates = self::getAllTemplateImages();
		foreach ( $templates as $template_name => $template ) {
			$template_images = $all_templates[ $template_name ];
			if ( ! empty( $template_images ) ) {
				$templates[ $template_name ] = array_merge( $template, $template_images );
			}
		}

		return $templates;
	}

	protected static function getSubscriptionPreviewImageList( string $template_group = 'default' ) {
		if ( empty( $template_group ) ) {
			return [];
		}

		return [
			'cancelled_subscription'            => EmailTemplate::getPreviewImageUrl( 'cancelled-subscription', $template_group ),
			'customer_completed_renewal_order'  => EmailTemplate::getPreviewImageUrl( 'customer-completed-renewal-order', $template_group ),
			'customer_completed_switch_order'   => EmailTemplate::getPreviewImageUrl( 'customer-completed-switch-order', $template_group ),
			'customer_on_hold_renewal_order'    => EmailTemplate::getPreviewImageUrl( 'customer-on-hold-renewal-order', $template_group ),
			'customer_processing_renewal_order' => EmailTemplate::getPreviewImageUrl( 'customer-processing-renewal-order', $template_group ),
			'customer_renewal_invoice'          => EmailTemplate::getPreviewImageUrl( 'customer-renewal-invoice', $template_group ),
			'expired_subscription'              => EmailTemplate::getPreviewImageUrl( 'expired-subscription', $template_group ),
			'new_renewal_order'                 => EmailTemplate::getPreviewImageUrl( 'new-renewal-order', $template_group ),
			'new_switch_order'                  => EmailTemplate::getPreviewImageUrl( 'new-switch-order', $template_group ),
			'suspended_subscription'            => EmailTemplate::getPreviewImageUrl( 'suspended-subscription', $template_group ),
			'customer_payment_retry'            => EmailTemplate::getPreviewImageUrl( 'customer_payment_retry', $template_group ),
			'payment_retry'                     => EmailTemplate::getPreviewImageUrl( 'payment_retry', $template_group ),
		];
	}

	/**
	 * Get booking template list.
	 * @return array
	 */
	public static function getAllTemplateImages() {
		return apply_filters( ESCT_PLUGIN_PREFIX . '_subscription_template_images', [
			'default' => self::getSubscriptionPreviewImageList(),
			'caramel' => self::getSubscriptionPreviewImageList( 'caramel' ),
			'peanut'  => self::getSubscriptionPreviewImageList( 'peanut' ),
			'biscuit' => self::getSubscriptionPreviewImageList( 'biscuit' ),
			'mint'    => self::getSubscriptionPreviewImageList( 'mint' )
		] );
	}

	/**
	 * Is valid template.
	 *
	 * @param string $template_group Template group.
	 * @param string $template Template id.
	 *
	 * @return bool
	 */
	public static function isValidTemplate( $template_group, $template ) {
		$templates = self::getAllTemplateImages();

		return isset( $templates[ $template_group ] ) && array_key_exists( $template, $templates[ $template_group ] );
	}

	/**
	 * Add template path.
	 *
	 * @param $file_path
	 * @param $args
	 *
	 * @return string
	 */
	public static function addTemplatePath( $file_path, $args ) {
		if ( ! is_array( $args ) || empty( $args['template_group'] ) || empty( $args['template_name'] ) || ! self::isValidTemplate( $args['template_group'], $args['template_name'] ) ) {
			return $file_path;
		}
		$new_file_path = ESCT_PLUGIN_PATH . 'App/Views/Templates/' . $args['template_name'] . '/' . $args['template_group'] . '.html';
		if ( file_exists( $new_file_path ) ) {
			return $new_file_path;
		}

		return $file_path;
	}

	public static function getTagDetails( $template_plugin, $template ) {
		if ( empty( $template ) || ! in_array( $template, self::$subscription_templates ) ) {
			return $template_plugin;
		}

		return [
			'group' => 'woocommerce_subscription',
			'name'  => __( 'Woo Subscriptions', 'email-editor-plus' ),
			'style' => 'color:#ffffff;backgroundColor:#ad712b'
		];
	}

	public static function addToGroups( $groups ) {
		if ( ! is_array( $groups ) ) {
			return $groups;
		}
		$groups[] = [
			'label' => esc_html__( 'Woo Subscriptions', 'email-editor-plus' ),
			'value' => 'woocommerce_subscription'
		];

		return $groups;
	}
}