<?php

namespace EDPW\Core\Helpers;

use EDPW\Core\Models\EmailTemplates;

defined( 'ABSPATH' ) || exit;

class EmailTemplate {
	/**
	 * Is pro version.
	 * @return bool
	 */
	public static function isPro() {
		return apply_filters( 'edpw_is_pro', false );
	}

	public static function isWordPressTemplate( $template ) {
		if ( empty( $template ) ) {
			return false;
		}
		$templates = [
			'wp_new_user_register_email',
			'wp_retrieve_password_email',
			'wp_password_change_email',
			'wp_email_change_email',
		];

		return in_array( $template, $templates );
	}

	/**
	 * Get email templates list.
	 * @return array
	 */
	public static function getEmailTypeLists(): array {
		$email_list = [
			'wp_new_user_register_email' => (object) [
				'id'          => 'wp_new_user_register_email',
				'title'       => 'New User Registration',
				'description' => 'New user registration email notification to customer.',
			],
			'wp_retrieve_password_email' => (object) [
				'id'          => 'wp_retrieve_password_email',
				'title'       => 'Password Reset Request',
				'description' => 'Password reset email notification to customer.',
			],
			'wp_password_change_email'   => (object) [
				'id'          => 'wp_password_change_email',
				'title'       => 'Password Changed',
				'description' => 'Password changed email notification to customer.',
			],
			'wp_email_change_email'      => (object) [
				'id'          => 'wp_email_change_email',
				'title'       => 'Email Changed',
				'description' => 'Email changed notification to customer.',
			],
		];
		if ( function_exists( 'WC' ) && WC::isMethodExists( WC(), 'mailer' ) ) {
			$email_list = array_merge( $email_list, WC()->mailer()->get_emails() );
		}

		return apply_filters( 'edpw_email_type_list', $email_list );
	}

	/**
	 * Get default template list.
	 * @return array
	 */
	public static function getDefaultTemplates() {
		return apply_filters( 'edpw_default_email_templates', [
			//WordPress
			'wp_new_user_register_email',
			'wp_retrieve_password_email',
			'wp_password_change_email',
			'wp_email_change_email',
			//WooCommerce
			'WC_Email_New_Order',
			'WC_Email_Cancelled_Order',
			'WC_Email_Failed_Order',
			'WC_Email_Customer_Failed_Order',
			'WC_Email_Customer_On_Hold_Order',
			'WC_Email_Customer_Processing_Order',
			'WC_Email_Customer_Completed_Order',
			'WC_Email_Customer_Refunded_Order',
			'WC_Email_Customer_Invoice',
			'WC_Email_Customer_Note',
			'WC_Email_Customer_Reset_Password',
			'WC_Email_Customer_New_Account',
			'WC_Email_Customer_Cancelled_Order',
			'WC_Email_Customer_POS_Completed_Order',
			'WC_Email_Customer_POS_Refunded_Order'
		] );
	}

	/**
	 * Get email template name.
	 *
	 * @param string $type Email type.
	 *
	 * @return string
	 */
	public static function getEmailTitle( $type = '' ) {
		if ( empty( $type ) ) {
			return '';
		}
		foreach ( self::getEmailTypeLists() as $template ) {
			if ( is_object( $template ) && $template->id == $type ) {
				return $template->title;
			}
		}

		return '';
	}

	/**
	 * Get preview template list.
	 *
	 * @param string $lang Language string.
	 * @param string $type Template type.
	 *
	 * @return array
	 */
	public static function getPreviewTemplatesList( string $lang, string $type ): array {
		return (array) apply_filters( 'edpw_templates_list', [
			'default' => [
				'lang'                       => $lang,
				'template_preview_image_url' => self::getPreviewUrl( 'default', $type ),
				'type'                       => $type,
				'template_group'             => 'default',
				'name'                       => esc_html__( 'Default', 'email-editor-plus' ),
				'is_allow'                   => true
			],
			'caramel' => [
				'lang'                       => $lang,
				'template_preview_image_url' => self::getPreviewUrl( 'caramel', $type ),
				'type'                       => $type,
				'template_group'             => 'caramel',
				'name'                       => esc_html__( 'Caramel', 'email-editor-plus' ),
				'is_allow'                   => false
			],
			'peanut'  => [
				'lang'                       => $lang,
				'template_preview_image_url' => self::getPreviewUrl( 'peanut', $type ),
				'type'                       => $type,
				'template_group'             => 'peanut',
				'name'                       => esc_html__( 'Peanut', 'email-editor-plus' ),
				'is_allow'                   => false
			],
			'biscuit' => [
				'lang'                       => $lang,
				'template_preview_image_url' => self::getPreviewUrl( 'biscuit', $type ),
				'type'                       => $type,
				'template_group'             => 'biscuit',
				'name'                       => esc_html__( 'Biscuit', 'email-editor-plus' ),
				'is_allow'                   => false
			],
			'mint'    => [
				'lang'                       => $lang,
				'template_preview_image_url' => self::getPreviewUrl( 'mint', $type ),
				'type'                       => $type,
				'template_group'             => 'mint',
				'name'                       => esc_html__( 'Mint', 'email-editor-plus' ),
				'is_allow'                   => false
			]
		], $lang, $type );
	}

	public static function getPreviewImageUrl( string $file_name, string $template_group = 'default' ) {
		if ( empty( $file_name ) || empty( $template_group ) ) {
			return '';
		}
		$image_path = EDPW_PLUGIN_PATH . 'Assets/image';
		$file_path  = '/templates/' . $template_group . '/preview/' . $file_name . '.png';
		if ( file_exists( $image_path . $file_path ) ) {
			return EmailTemplate::getImagePath() . $file_path;
		}

		return 'https://static.flycart.net/email_customizer_advance/image/templates/' . $template_group . '/preview/' . $file_name . '.png';
	}

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

		return [
			//WordPress
			'wp_new_user_register_email' => self::getPreviewImageUrl( 'wp_new_user_register_email', $template_group ),
			'wp_retrieve_password_email' => self::getPreviewImageUrl( 'wp_retrieve_password_email', $template_group ),
			'wp_password_change_email'   => self::getPreviewImageUrl( 'wp_password_change_email', $template_group ),
			'wp_email_change_email'      => self::getPreviewImageUrl( 'wp_email_change_email', $template_group ),
			//WooCommerce
			'new_order'                  => self::getPreviewImageUrl( 'new-order', $template_group ),
			'cancelled_order'            => self::getPreviewImageUrl( 'cancelled-order', $template_group ),
			'customer_cancelled_order'   => self::getPreviewImageUrl( 'customer-cancelled-order', $template_group ),
			'customer_pos_completed_order'   => self::getPreviewImageUrl( 'customer-pos-completed-order', $template_group ),
			'customer_pos_refunded_order'   => self::getPreviewImageUrl( 'customer-pos-refunded-order', $template_group ),
			'failed_order'               => self::getPreviewImageUrl( 'failed-order', $template_group ),
			'customer_failed_order'      => self::getPreviewImageUrl( 'customer-failed-order', $template_group ),
			'customer_on_hold_order'     => self::getPreviewImageUrl( 'customer-on-hold-order', $template_group ),
			'customer_processing_order'  => self::getPreviewImageUrl( 'customer-processing-order', $template_group ),
			'customer_completed_order'   => self::getPreviewImageUrl( 'completed-order', $template_group ),
			'customer_refunded_order'    => self::getPreviewImageUrl( 'customer-refunded-order', $template_group ),
			'customer_invoice'           => self::getPreviewImageUrl( 'customer_invoice', $template_group ),
			'customer_note'              => self::getPreviewImageUrl( 'customer-note', $template_group ),
			'customer_reset_password'    => self::getPreviewImageUrl( 'customer-reset-password', $template_group ),
			'customer_new_account'       => self::getPreviewImageUrl( 'customer-new-account', $template_group ),
		];
	}

	public static function getTemplateList() {
		return [
			'default' => self::getWooCommercePreviewImageList(),
			'caramel' => self::getWooCommercePreviewImageList( 'caramel' ),
			'peanut'  => self::getWooCommercePreviewImageList( 'peanut' ),
			'biscuit' => self::getWooCommercePreviewImageList( 'biscuit' ),
			'mint'    => self::getWooCommercePreviewImageList( 'mint' ),
		];
	}

	/**
	 * Template preview URLs.
	 *
	 * @param $name
	 * @param $type
	 *
	 * @return mixed|null
	 */
	public static function getPreviewUrl( $name, $type ) {
		$template_preview_urls = apply_filters( 'edpw_templates_image_list', self::getTemplateList(), $name, $type );

		return $template_preview_urls[ $name ][ $type ] ?? '';
	}

	public static function isWoocommerceTemplate( $template ) {
		if ( empty( $template ) ) {
			return false;
		}
		$woocommerce_templates = [
			'new_order',
			'cancelled_order',
			'failed_order',
			'customer_failed_order',
			'customer_on_hold_order',
			'customer_processing_order',
			'customer_completed_order',
			'customer_cancelled_order',
			'customer_refunded_order',
			'customer_invoice',
			'customer_note',
			'customer_reset_password',
			'customer_new_account',
			'customer_pos_completed_order',
			'customer_pos_refunded_order'
		];

		return in_array( $template, $woocommerce_templates );
	}

	public static function getTemplatePluginTag( $template ) {
		$template_plugin = [
			'group' => 'wordpress',
			'name'  => esc_html__( 'WordPress', 'email-editor-plus' ),
			'style' => 'color:#ffffff;backgroundColor:#2271b1'
		];
		if ( empty( $template ) || ! is_string( $template ) ) {
			return $template_plugin;
		}

		if ( self::isWoocommerceTemplate( $template ) ) {
			return [
				'group' => 'woocommerce',
				'name'  => esc_html__( 'WooCommerce', 'email-editor-plus' ),
				'style' => 'color:#ffffff;backgroundColor:#7f54b3'
			];
		}

		return apply_filters( 'edpw_template_plugin_tag', $template_plugin, $template );
	}

	public static function getEmailGroups() {
		$groups = [
			[
				'label' => esc_html__( 'All', 'email-editor-plus' ),
				'value' => 'all'
			],
			[
				'label' => esc_html__( 'WordPress', 'email-editor-plus' ),
				'value' => 'wordpress'
			],
			[
				'label' => esc_html__( 'WooCommerce', 'email-editor-plus' ),
				'value' => 'woocommerce'
			]
		];

		return apply_filters( 'edpw_email_template_groups', $groups );
	}

	public static function getToReplaceDirectionContents( $direction = "ltr" ) {
		$replace_contents = array();
		if ( $direction == 'rtl' ) {
			$replace_contents['<body>']         = '<body dir="rtl">';
			$replace_contents['dir="ltr"']      = 'dir="rtl"';
			$replace_contents['direction:ltr']  = 'direction:rtl';
			$replace_contents['align="left"']   = 'align="right"';
			$replace_contents['align = "left"'] = 'align="right"';
			$replace_contents[':left;']         = ':right;direction:rtl;';
			$replace_contents[': left;']        = ':right;direction:rtl;';
		}

		return apply_filters( 'edpw_direction_replace_contents', $replace_contents, $direction );
	}

	public static function changeDirection( $content, $direction = 'ltr' ) {
		$replace_contents = self::getToReplaceDirectionContents( $direction );
		if ( empty( $replace_contents ) ) {
			return $content;
		}
		$replaced_content = null;
		if ( is_array( $replace_contents ) ) {
			$search           = array_keys( $replace_contents );
			$replace          = array_values( $replace_contents );
			$replaced_content = str_replace( $search, $replace, $content );
		}

		return apply_filters( 'edpw_change_direction_content', $replaced_content, $content, $direction );
	}

	public static function getSettings() {
		return get_option( 'edpw_settings', self::getDefaultSettings() );
	}

	public static function getSetting( $key, $value ) {
		$settings = self::getSettings();

		return $settings[ $key ] ?? $value;
	}

	public static function getDefaultSettings() {
		$default_settings = [
			'custom_css'          => self::getDefaultCustomCss(),
			'autofix_broken_html' => 1,
			'license_key'         => '',
			'facebook_link'       => 'https://www.facebook.com/',
			'twitter_link'        => 'https://x.com/',
			'linkedin_link'       => 'https://www.linkedin.com/',
			'pinterest_link'      => 'https://www.pinterest.com/'
		];
		$languages        = WC::getAvailableLanguages();
		foreach ( $languages as $language ) {
			if ( ! empty( $language['value'] ) ) {
				$default_settings[ 'language_direction_for_' . $language['value'] ] = 'ltr';
			}
		}

		return $default_settings;
	}

	public static function getLanguageOptions() {
		$languages = WC::getAvailableLanguages();
		foreach ( $languages as &$language ) {
			if ( ! empty( $language['value'] ) ) {
				$language['value'] = 'language_direction_for_' . $language['value'];
			}
		}

		return $languages;
	}

	public static function getDefaultCustomCss() {
		$css = '.email-subscription-list, .email-product-list, .email-download-list {
                    overflow: auto;
                }
        
                .email-subscription-list table, .email-product-list table, .email-download-list table {
                    border-collapse: collapse;
                }
                .email-product-list table tbody tr td ul {
                    list-style-type: none;
                }
                .email-product-list table tbody tr td:first-child {
                    width: 50%; 
                }
                .email-product-list table tbody tr td:nth-child(2) {
                    width: 1%;
                } 
               
                table thead tr th {
                    white-space: nowrap;
                }
            ';

		return apply_filters( 'edpw_default_custom_css', $css );
	}

	public static function getLanguageDirection( $language ) {
		$settings = self::getSettings();
		$key      = 'language_direction_for_' . $language;

		return apply_filters( 'edpw_get_language_direction', ( $settings[ $key ] ?? 'ltr' ), $language );
	}

	public static function getDefaultTemplateContent( $template_group, $template_name, $lang, $data = [] ) {
		if ( empty( $template_group ) || empty( $template_name ) ) {
			return '';
		}
		$file_path = EDPW_PLUGIN_PATH . 'Core/Views/Templates/' . $template_name . '/' . $template_group . '.html';
		$file_path = apply_filters( 'edpw_template_path', $file_path, [
			'template_group' => $template_group,
			'template_name'  => $template_name,
			'lang'           => $lang,
			'data'           => $data
		] );
		$content   = '';
		if ( file_exists( $file_path ) ) {
			$content = Util::renderTemplate( $file_path, $data );
			$content = str_replace( '{{shop.image_path}}', self::getImagePath(), $content );
		}

		return $content;
	}

	public static function getImagePath() {
		return 'https://static.flycart.net/email_customizer_advance/image';//EDPW_PLUGIN_URL . 'Assets/image';
	}

	public static function getMailHeaders() {
		$charset      = ( function_exists( 'get_bloginfo' ) ) ? get_bloginfo( 'charset' ) : 'UTF-8';
		$from_name    = esc_html__( 'Admin', 'email-editor-plus' );
		$from_address = get_option( 'admin_email' );
		//Prepare for sending emails
		$headers = array(
			"From: \"$from_name\" <$from_address>",
			"Return-Path: <" . $from_address . ">",
			"Reply-To: \"" . $from_name . "\" <" . $from_address . ">",
			"X-Mailer: PHP" . phpversion(),
			"Content-Type: text/html; charset=\"" . $charset . "\""
		);
		$header  = implode( "\n", $headers );

		return apply_filters( 'edpw_modify_email_headers', $header );
	}

	/**
	 * Is object have search word.
	 *
	 * @param string $search Search word.
	 * @param object $email_template Email template object.
	 * @param array $fields Search fields.
	 *
	 * @return bool
	 */
	public static function isSearchHaveIt( string $search, $email_template, array $fields = [] ): bool {
		if ( empty( $search ) || empty( $fields ) || empty( $email_template ) ) {
			return true;
		}

		preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $search, $matches );
		$search_keys = Util::getValidSearchWords( $matches[0] );
		if ( empty( $search_keys ) ) {
			return false;
		}

		foreach ( $fields as $field ) {
			if ( ! empty( $field ) && ! empty( $email_template->$field ) ) {

				foreach ( $search_keys as $search_key ) {
					if ( strpos( strtolower( $email_template->$field ), strtolower( $search_key ) ) !== false ) {
						return true;
					}
				}
			}
		}

		return false;
	}

	/**
	 * Format short codes.
	 *
	 * @param array $short_codes Short code list.
	 *
	 * @return array
	 */
	public static function formatShortCode( $short_codes, $pre_fix = '' ) {
		if ( ! is_array( $short_codes ) ) {
			return $short_codes;
		}

		foreach ( $short_codes as $short_code => $data ) {
			unset( $short_codes[ $short_code ] );
			$short_codes[ '{{' . $pre_fix . $short_code . '}}' ] = $data;
		}

		return $short_codes;
	}

	/**
	 * Retrieves a custom rendered email template based on the provided arguments.
	 *
	 * @param array $args An array of arguments for retrieving the custom template.
	 *
	 * @return string|null The rendered custom template, or null if no template was found.
	 */
	public static function getCustomRenderedTemplate( $args = [] ) {
		if ( empty( $args['type'] ) ) {
			return null;
		}
		$lang             = ! empty( $args['lang'] ) ? $args['lang'] : WC::getSiteDefaultLang();
		$customizer_model = new EmailTemplates();
		$template         = $customizer_model->getActiveTemplate( $lang, $args['type'] );
		if ( $template ) {
			$order_id       = ! empty( $args['order_id'] ) ? $args['order_id'] : '';
			$email_heading  = ! empty( $args['email_heading'] ) ? $args['email_heading'] : '';
			$change_content = '<body><p style="display: none !important; visibility: hidden; opacity: 0; color: transparent; height: 0; width: 0; font-size: 0px; mso-hide: all; max-height: 0; line-height: 0;"><span>' . $email_heading . '</span></p>';
			$template->html = str_replace( '<body>', $change_content, $template->html );
			$short_code     = new \EDPW\Core\Controllers\ShortCodes( $args['type'], $template, $args, $order_id );

			return $short_code->renderTemplate( false );
		}

		return null;
	}
	/**
	 * Get all supported email template IDs grouped by category.
	 *
	 * @return array<string, string[]> Filtered list of email template IDs.
	 */
	public static function getAllEmailTemplateIds(): array {
		$email_template_ids = [
			'woocommerce' => [
				'new_order',
				'cancelled_order',
				'failed_order',
				'customer_failed_order',
				'customer_on_hold_order',
				'customer_processing_order',
				'customer_completed_order',
				'customer_refunded_order',
				'customer_invoice',
				'customer_note',
				'customer_reset_password',
				'customer_new_account',
				'customer_cancelled_order',
				'customer_pos_completed_order',
				'customer_pos_refunded_order'
			],
			'wordpress' => [
				'wp_new_user_register_email',
				'wp_retrieve_password_email',
				'wp_password_change_email',
				'wp_email_change_email',
			],
		];

		/**
		 * Filter the list of all email template IDs.
		 *
		 * @param array<string, string[]> $email_template_ids
		 */
		return apply_filters('edpw_email_template_ids', $email_template_ids);
	}

}