<?php

namespace WLCT\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 WPLoyalty {
	protected static $plugin_templates = [
		'wlr_earn_point_email',
		'wlr_earn_reward_email',
		'wlr_expire_email',
		'wlr_point_expire_email',
		'wlr_birthday_email',
		'wlr_new_level_email',
	];

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

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

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

	/**
	 * List WPLoyalty 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::$plugin_templates ) ) {
			return $short_codes;
		}
		$short_codes['wployalty'] = [
			'label'       => __( 'WPLoyalty', 'email-editor-plus' ),
			'short_codes' => EmailTemplate::formatShortCode( self::getShortCodes( 'desc', 'wployalty.' ) )
		];

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

	/**
	 * Add loyalty 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 ( $sample ) {
			$short_codes['wployalty'] = self::getShortCodes( 'default' );
		} else {
			$short_codes['wployalty'] = self::getShortCodes( 'value', '', $args );
		}

		return apply_filters( WLCT_PLUGIN_PREFIX . '_wployalty_additional_short_codes', $short_codes, $order, $args, $sample );
	}

	/**
	 * 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::$plugin_templates ) ) {
			return $short_codes;
		}
		$short_codes['wployalty'] = self::getShortCodes( 'default' );

		return $short_codes;
	}

	/**
	 * Process a list of short codes based on the provided type.
	 *
	 * @param string $type Type of email template.
	 * @param array $short_codes List of short codes to process.
	 *
	 * @return array Processed list of short codes.
	 */
	public static function processShortCodeList( $type, $short_codes ) {
		if ( ! is_string( $type ) || ! is_array( $short_codes ) ) {
			return $short_codes;
		}
		switch ( $type ) {
			case 'wlr_earn_point_email':
				$ignore_short_codes = [
					'billing_address'  => [],
					'shipping_address' => [],
					'shipping_method'  => [],
					'order'            => [],
					'payment'          => [],
					'customer'         => [],
					'order_meta'       => [],
					'wployalty'        => [
						'short_codes' => [
							'{{wployalty.wlr_earn_reward}}',
							'{{wployalty.wlr_reward_name}}',
							'{{wployalty.wlr_reward_title}}',
							'{{wployalty.wlr_reward_label}}',
							'{{wployalty.wlr_reward_display_name}}',
							'{{wployalty.wlr_earn_point_or_reward}}',
							'{{wployalty.wlr_expiry_date}}',
							'{{wployalty.wlr_expiry_redeem_url}}',
							'{{wployalty.wlr_point_expiry_content}}',
							'{{wployalty.wlr_level_name}}',
							'{{wployalty.wlr_expiry_points}}',
							'{{wployalty.wlr_shop_url}}'
						]
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
			case 'wlr_earn_reward_email':
				$ignore_short_codes = [
					'billing_address'  => [],
					'shipping_address' => [],
					'shipping_method'  => [],
					'order'            => [],
					'payment'          => [],
					'customer'         => [],
					'order_meta'       => [],
					'wployalty'        => [
						'short_codes' => [
							'{{wployalty.wlr_points_label}}',
							'{{wployalty.wlr_earn_point}}',
							'{{wployalty.wlr_reward_name}}',
							'{{wployalty.wlr_earn_point_or_reward}}',
							'{{wployalty.wlr_level_name}}',
							'{{wployalty.wlr_expiry_points}}',
							'{{wployalty.wlr_expiry_date}}',
							'{{wployalty.wlr_expiry_redeem_url}}',
							'{{wployalty.wlr_point_expiry_content}}',
							'{{wployalty.wlr_shop_url}}'
						]
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
			case 'wlr_expire_email':
				$ignore_short_codes = [
					'billing_address'  => [],
					'shipping_address' => [],
					'shipping_method'  => [],
					'order'            => [],
					'payment'          => [],
					'customer'         => [],
					'order_meta'       => [],
					'wployalty'        => [
						'short_codes' => [
							'{{wployalty.wlr_campaign_name}}',
							'{{wployalty.wlr_action_name}}',
							'{{wployalty.wlr_points_label}}',
							'{{wployalty.wlr_earn_point}}',
							'{{wployalty.wlr_earn_reward}}',
							'{{wployalty.wlr_reward_title}}',
							'{{wployalty.wlr_reward_label}}',
							'{{wployalty.wlr_reward_display_name}}',
							'{{wployalty.wlr_earn_point_or_reward}}',
							'{{wployalty.wlr_level_name}}',
							'{{wployalty.wlr_point_expiry_content}}',
							'{{wployalty.wlr_order_id}}',
							'{{wployalty.wlr_expiry_points}}',
							'{{wployalty.wlr_shop_url}}'
						]
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
			case 'wlr_point_expire_email':
				$ignore_short_codes = [
					'billing_address'  => [],
					'shipping_address' => [],
					'shipping_method'  => [],
					'order'            => [],
					'payment'          => [],
					'customer'         => [],
					'order_meta'       => [],
					'wployalty'        => [
						'short_codes' => [
							'{{wployalty.wlr_campaign_name}}',
							'{{wployalty.wlr_action_name}}',
							'{{wployalty.wlr_earn_point}}',
							'{{wployalty.wlr_earn_reward}}',
							'{{wployalty.wlr_reward_name}}',
							'{{wployalty.wlr_reward_title}}',
							'{{wployalty.wlr_reward_label}}',
							'{{wployalty.wlr_reward_display_name}}',
							'{{wployalty.wlr_earn_point_or_reward}}',
							'{{wployalty.wlr_expiry_redeem_url}}',
							'{{wployalty.wlr_level_name}}',
							'{{wployalty.wlr_order_id}}',
						]
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
			case 'wlr_birthday_email':
				$ignore_short_codes = [
					'billing_address'  => [],
					'shipping_address' => [],
					'shipping_method'  => [],
					'order'            => [],
					'payment'          => [],
					'customer'         => [],
					'order_meta'       => [],
					'wployalty'        => [
						'short_codes' => [
							'{{wployalty.wlr_reward_name}}',
							'{{wployalty.wlr_expiry_redeem_url}}',
							'{{wployalty.wlr_expiry_date}}',
							'{{wployalty.wlr_level_name}}',
							'{{wployalty.wlr_point_expiry_content}}',
							'{{wployalty.wlr_order_id}}',
							'{{wployalty.wlr_expiry_points}}'
						]
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
			case 'wlr_new_level_email':
				$ignore_short_codes = [
					'billing_address'  => [],
					'shipping_address' => [],
					'shipping_method'  => [],
					'order'            => [],
					'payment'          => [],
					'customer'         => [],
					'order_meta'       => [],
					'wployalty'        => [
						'short_codes' => [
							'{{wployalty.wlr_campaign_name}}',
							'{{wployalty.wlr_action_name}}',
							'{{wployalty.wlr_earn_point}}',
							'{{wployalty.wlr_earn_reward}}',
							'{{wployalty.wlr_reward_name}}',
							'{{wployalty.wlr_reward_title}}',
							'{{wployalty.wlr_reward_label}}',
							'{{wployalty.wlr_reward_display_name}}',
							'{{wployalty.wlr_earn_point_or_reward}}',
							'{{wployalty.wlr_expiry_date}}',
							'{{wployalty.wlr_expiry_redeem_url}}',
							'{{wployalty.wlr_point_expiry_content}}',
							'{{wployalty.wlr_order_id}}',
							'{{wployalty.wlr_expiry_points}}',
							'{{wployalty.wlr_shop_url}}',
						]
					]
				];
				$short_codes        = ShortCodes::removeIgnoreShortCodes( $short_codes, $ignore_short_codes );
				break;
		}

		return $short_codes;
	}

	/**
	 * Get WPLoyalty short codes.
	 * @return array
	 */
	public static function getShortCodes( $type = 'value', $pre_fix = '', $args = [] ) {
		$fields = apply_filters( WLCT_PLUGIN_PREFIX . '_wployalty_short_codes', [
			'wlr_campaign_name'             => [
				'value'   => $args['{wlr_campaign_name}'] ?? '',
				'desc'    => __( 'Campaign name', 'email-editor-plus' ),
				'default' => 'Earn 1 points from $1'
			],
			'wlr_action_name'               => [
				'value'   => $args['{wlr_action_name}'] ?? '',
				'desc'    => __( 'Campaign action name', 'email-editor-plus' ),
				'default' => 'Point For Purchase'
			],
			'wlr_user_point'                => [
				'value'   => $args['{wlr_user_point}'] ?? '',
				'desc'    => __( 'Points balance', 'email-editor-plus' ),
				'default' => 600
			],
			'wlr_points_label'              => [
				'value'   => $args['{wlr_points_label}'] ?? '',
				'desc'    => __( 'Point label', 'email-editor-plus' ),
				'default' => 'point'
			],
			'wlr_total_earned_point'        => [
				'value'   => $args['{wlr_total_earned_point}'] ?? '',
				'desc'    => __( 'Total earned points of a customer', 'email-editor-plus' ),
				'default' => 1100
			],
			'wlr_used_point'                => [
				'value'   => $args['{wlr_used_point}'] ?? '',
				'desc'    => __( 'Used / redeemed points for a customer', 'email-editor-plus' ),
				'default' => 500
			],
			'wlr_user_name'                 => [
				'value'   => $args['{wlr_user_name}'] ?? '',
				'desc'    => __( 'Customer name', 'email-editor-plus' ),
				'default' => 'Sam'
			],
			'wlr_earn_point'                => [
				'value'   => $args['{wlr_earn_point}'] ?? 0,
				'desc'    => __( 'Points earned', 'email-editor-plus' ),
				'default' => 500
			],
			'wlr_earn_reward'               => [
				'value'   => $args['{wlr_earn_reward}'] ?? '',
				'desc'    => __( 'Reward earned', 'email-editor-plus' ),
				'default' => 'Test'
			],
			'wlr_referral_url'              => [
				'value'   => $args['{wlr_referral_url}'] ?? '',
				'desc'    => __( 'Referral link', 'email-editor-plus' ),
				'default' => site_url() . '/?wlr_ref=sampleurl'
			],
			'wlr_reward_name'               => [
				'value'   => $args['{wlr_reward_name}'] ?? '',
				'desc'    => __( 'Reward name', 'email-editor-plus' ),
				'default' => 'Free Product'
			],
			'wlr_reward_title'              => [
				'value'   => $args['{wlr_reward_title}'] ?? '',
				'desc'    => __( 'Reward title', 'email-editor-plus' ),
				'default' => 'Free Product'
			],
			'wlr_reward_label'              => [
				'value'   => $args['{wlr_reward_label}'] ?? '',
				'desc'    => __( 'Reward label', 'email-editor-plus' ),
				'default' => 'reward'
			],
			'wlr_reward_display_name'       => [
				'value'   => $args['{wlr_reward_display_name}'] ?? '',
				'desc'    => __( 'Reward display name', 'email-editor-plus' ),
				'default' => 'reward'
			],
			'wlr_earn_point_or_reward'      => [
				'value'   => $args['{wlr_earn_point_or_reward}'] ?? '',
				'desc'    => __( 'Display points / rewards earned', 'email-editor-plus' ),
				'default' => '10'
			],
			'wlr_customer_reward_page_link' => [
				'value'   => $args['{wlr_customer_reward_page_link}'] ?? '',
				'desc'    => __( 'Reward page link', 'email-editor-plus' ),
				'default' => ''
			],
			'wlr_expiry_date'               => [
				'value'   => $args['{wlr_expiry_date}'] ?? '',
				'desc'    => __( 'Date when points / rewards expire', 'email-editor-plus' ),
				'default' => gmdate( 'Y-m-d H:i:s', current_time( 'timestamp' ) + 3600 )
			],
			'wlr_expiry_redeem_url'         => [
				'value'   => $args['{wlr_expiry_redeem_url}'] ?? '',
				'desc'    => __( 'URL to redeem the reward', 'email-editor-plus' ),
				'default' => site_url()
			],
			'wlr_level_name'                => [
				'value'   => $args['{wlr_level_name}'] ?? '',
				'desc'    => __( 'Level Name', 'email-editor-plus' ),
				'default' => 'level 1'
			],
			'wlr_point_expiry_content'      => [
				'value'   => $args['{wlr_point_expiry_content}'] ?? '',
				'desc'    => __( 'Points expiry message', 'email-editor-plus' ),
				'default' => ''
			],
			'wlr_order_id'                  => [
				'value'   => $args['{wlr_order_id}'] ?? '',
				'desc'    => __( 'Order ID of the points/rewards earned (if available)', 'email-editor-plus' ),
				'default' => '123'
			],
			'wlr_expiry_points'             => [
				'value'   => $args['{wlr_expiry_points}'] ?? '',
				'desc'    => __( 'Expiring Points', 'email-editor-plus' ),
				'default' => 5
			],
			'wlr_shop_url'                  => [
				'value'   => $args['{wlr_shop_url}'] ?? '',
				'desc'    => __( 'URL for shop page', 'email-editor-plus' ),
				'default' => get_permalink( wc_get_page_id( 'shop' ) )
			],
		], $type );

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


	/**
	 * 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;
	}

	/**
	 * Get the list of preview image URLs for WP Loyalty email templates.
	 *
	 * @param string $template_group Template group for which images are needed.
	 *
	 * @return array Associative array containing the preview image URLs for different WP Loyalty email templates.
	 */
	protected static function getWPLoyaltyPreviewImageList( string $template_group = 'default' ) {
		if ( empty( $template_group ) ) {
			return [];
		}

		return [
			'wlr_earn_point_email'   => EmailTemplate::getPreviewImageUrl( 'loyalty-point-earned', $template_group ),
			'wlr_earn_reward_email'  => EmailTemplate::getPreviewImageUrl( 'loyalty-reward-earned', $template_group ),
			'wlr_expire_email'       => EmailTemplate::getPreviewImageUrl( 'loyalty-coupon-expire-email', $template_group ),
			'wlr_point_expire_email' => EmailTemplate::getPreviewImageUrl( 'loyalty-point-expire-email', $template_group ),
			'wlr_birthday_email'     => EmailTemplate::getPreviewImageUrl( 'loyalty-birthday-email', $template_group ),
			'wlr_new_level_email'    => EmailTemplate::getPreviewImageUrl( 'loyalty-new-level-email', $template_group ),
		];
	}

	/**
	 * Get booking template list.
	 * @return array
	 */
	public static function getAllTemplateImages() {
		return apply_filters( WLCT_PLUGIN_PREFIX . '_wployalty_template_images', [
			'default' => self::getWPLoyaltyPreviewImageList(),
			'caramel' => self::getWPLoyaltyPreviewImageList( 'caramel' ),
			'peanut'  => self::getWPLoyaltyPreviewImageList( 'peanut' ),
			'biscuit' => self::getWPLoyaltyPreviewImageList( 'biscuit' ),
			'mint'    => self::getWPLoyaltyPreviewImageList( '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 string $file_path File path.
	 * @param array $args Arguments.
	 *
	 * @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 = WLCT_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;
	}

	/**
	 * Retrieves tag details.
	 *
	 * @param string $template_plugin Template plugin to check against.
	 * @param string $template Template to retrieve details for.
	 *
	 * @return array Tag details including group, name, and style.
	 */
	public static function getTagDetails( $template_plugin, $template ) {
		if ( empty( $template ) || ! in_array( $template, self::$plugin_templates ) ) {
			return $template_plugin;
		}

		return [
			'group' => 'wployalty',
			'name'  => __( 'WPLoyalty', 'email-editor-plus' ),
			'style' => 'color:#ffffff;backgroundColor:#5850EC'
		];
	}

	/**
	 * Add to groups.
	 *
	 * @param array $groups List of groups to add to.
	 *
	 * @return array Updated list of groups with WPLoyalty group added.
	 */
	public static function addToGroups( array $groups ) {
		$groups[] = [
			'label' => esc_html__( 'WPLoyalty', 'email-editor-plus' ),
			'value' => 'wployalty'
		];

		return $groups;
	}

	/**
	 * Method to check and merge preview order templates.
	 *
	 * @param array $templates Array of templates to check and merge.
	 *
	 * @return array Merged array of templates with the disallowed preview order templates.
	 */
	public static function disallowedPreviewOrderTemplates( array $templates ) {

		return array_merge( $templates, self::$plugin_templates );
	}
}