<?php

namespace EDPW\Core\Controllers\Admin;

use EDPW\Core\Controllers\ShortCodes;
use EDPW\Core\Helpers\EmailTemplate;
use EDPW\Core\Helpers\Input;
use EDPW\Core\Helpers\Plugin;
use EDPW\Core\Helpers\ShortCodes as ShortCodeHelper;
use EDPW\Core\Helpers\WC;
use Exception;
use WC_Email;
use WC_Emails;
use WC_Order_Query;

defined( 'ABSPATH' ) || exit;

class EmailTemplates {

	/**
	 * Get email template list.
	 * @return void
	 */
	public static function getEmailTemplates() {
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$search            = (string) Input::get( 'search' );
		$limit             = (int) Input::get( 'limit', 20 );
		$offset            = (int) Input::get( 'offset', 0 );
		$lang              = (string) Input::get( 'lang' );
		$email_type        = (string) Input::get( 'type', 'all' );
		$email_list        = EmailTemplate::getEmailTypeLists();
		$default_templates = EmailTemplate::getDefaultTemplates();
		$default_language  = WC::getSiteDefaultLang();
		$chosen_language   = empty( $lang ) ? $default_language : $lang;
		$saved_templates   = \EDPW\Core\Models\EmailTemplates::getSavedTemplates( $chosen_language );
		$items             = [];
		$offset_count      = 0;
		$total_count       = 0;
		$is_pro            = EmailTemplate::isPro();
		foreach ( $email_list as $template_name => $email ) {
			if ( ! is_object( $email ) || ! isset( $email->title ) || ! EmailTemplate::getPreviewUrl( 'default', $email->id )
			     || ( ! empty( $search ) && ! EmailTemplate::isSearchHaveIt( $search, $email, [ 'title' ] ) ) ) {
				continue;
			}
			$tag = EmailTemplate::getTemplatePluginTag( $email->id );
			if ( ! empty( $email_type ) && $email_type != 'all' && ( empty( $tag['group'] ) || $tag['group'] != $email_type ) ) {
				continue;
			}

			$total_count += 1;
			if ( count( $items ) >= $limit ) {
				continue;
			}
			if ( ! empty( $offset ) && $offset > $offset_count ) {
				$offset_count ++;
				continue;
			}
			$item = [
				'id'          => 0,
				'is_editable' => false,
				'type'        => $email->id,
				'is_saved'    => false,
				'title'       => $email->title,
				'tag'         => $tag,
			];
			$offset_count ++;
			if ( in_array( $template_name, $default_templates ) || $is_pro ) {
				$item['is_editable'] = true;
			}
			$wordpress_email_ids         = [
				'wp_new_user_register_email',
				'wp_retrieve_password_email',
				'wp_password_change_email',
				'wp_email_change_email',
			];
			$woocommerce_admin_emails    = [
				'new_order',
				'cancelled_order',
				'failed_order',
			];
			$woocommerce_customer_emails = [
				'customer_failed_order',
				'customer_on_hold_order',
				'customer_processing_order',
				'customer_cancelled_order',
				'customer_completed_order',
				'customer_refunded_order',
				'customer_invoice',
				'customer_note',
				'customer_reset_password',
				'customer_new_account',
				'customer_pos_completed_order',
				'customer_pos_refunded_order'
			];
			if ( in_array( $email->id, $woocommerce_customer_emails, true ) || in_array( $email->id, $wordpress_email_ids, true ) ) {
				$item['is_customer_email'] = 'customer';
			} elseif ( in_array( $email->id, $woocommerce_admin_emails, true ) ) {
				$item['is_customer_email'] = 'admin';
			} else {
				$item['is_customer_email'] = 'unknown';
			}

			if ( $item['is_customer_email'] === 'unknown' ) {
				$item['is_customer_email'] = apply_filters( 'edpw_get_template_is_customer_email', $item['is_customer_email'], $email );
			}
			foreach ( $saved_templates as $template ) {
				if ( $item['type'] == $template->type && $chosen_language == $template->language ) {
					$item['language']  = $chosen_language;
					$item['id']        = (int) $template->id;
					$item['is_saved']  = true;
					$item['mjml']      = $template->mjml;
					$item['html']      = $template->html;
					$item['css']       = $template->css;
					$item['is_active'] = (int) $template->is_active;
				}
			}
			$items[] = $item;
		}
		wp_send_json_success( [
			'is_pro'           => $is_pro,
			'default_language' => WC::getSiteDefaultLang(),
			'chosen_language'  => $chosen_language,
			'search'           => $search,
			'limit'            => $limit,
			'total_count'      => $total_count,
			'items'            => $items
		] );
	}

	/**
	 * Enable/Disable email template.
	 * @return void
	 */
	public static function toggleEmailTemplate() {
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$id = (int) Input::get( 'id', 0 );
		if ( $id <= 0 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Invalid Template ID', 'email-editor-plus' ) ] );
		}
		$email_template = \EDPW\Core\Models\EmailTemplates::getByKey( $id );
		if ( empty( $email_template ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Invalid Template ID', 'email-editor-plus' ) ] );
		}
		$status = (int) Input::get( 'is_active', 0 );
		if ( ! \EDPW\Core\Models\EmailTemplates::update( [ 'is_active' => $status ], [ 'id' => $id ] ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Updating the template has failed', 'email-editor-plus' ) ] );
		}
		wp_send_json_success( [
			'lang'    => Input::get( 'lang' ),
			'message' => $status ? esc_html__( 'Template enabled successfully!', 'email-editor-plus' ) : esc_html__( 'Template disabled successfully!', 'email-editor-plus' )
		] );
	}

	/**
	 * Delete email template.
	 * @return void
	 */
	public static function deleteEmailTemplate() {
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$id = (int) Input::get( 'id', 0 );
		if ( $id <= 0 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Invalid Template ID', 'email-editor-plus' ) ] );
		}
		$email_template = \EDPW\Core\Models\EmailTemplates::getByKey( $id );
		if ( empty( $email_template ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Invalid Template ID', 'email-editor-plus' ) ] );
		}
		\EDPW\Core\Models\EmailTemplates::delete( [ 'id' => $id ] );
		wp_send_json_success( [ 'message' => esc_html__( 'Template deleted successfully', 'email-editor-plus' ) ] );
	}

	public static function getExportTemplate() {
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) ) {
			wp_send_json_error( [ 'message' => __( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$id = (int) Input::get( 'id', 0 );
		if ( $id <= 0 ) {
			wp_send_json_error( [ 'message' => __( 'Invalid Template ID', 'email-editor-plus' ) ] );
		}
		global $wp_filesystem;

		if ( empty( $wp_filesystem ) ) {
			require_once ABSPATH . '/wp-admin/includes/file.php';
			WP_Filesystem();
		}
		$export_path = EDPW_PLUGIN_PATH . 'File/';
		if ( ! $wp_filesystem->is_writable( $export_path ) ) {
			if ( ! $wp_filesystem->chmod( $export_path, FS_CHMOD_DIR ) ) {
				wp_send_json_error( [
					'message' => __( 'Permission denied to write a file', 'email-editor-plus' )
				] );
			}
		}

		$email_template = \EDPW\Core\Models\EmailTemplates::getByKey( $id );
		if ( empty( $email_template ) ) {
			wp_send_json_error( [ 'message' => __( 'Template not found', 'email-editor-plus' ) ] );
		}

		$language         = ! empty( $email_template->language ) ? $email_template->language : '';
		$template_type    = ! empty( $email_template->type ) ? $email_template->type : '';
		$template_content = ! empty( $email_template->mjml ) ? $email_template->mjml : '';
		$file_name        = $template_type . '-' . $language . '.mjml';
		try {
			$file_path = $export_path . $file_name;
			if ( $wp_filesystem->exists( $file_path ) ) {
				$wp_filesystem->delete( $file_path );
			}
			$written = $wp_filesystem->put_contents( $file_path, $template_content, FS_CHMOD_FILE );
			if ( ! $written ) {
				wp_send_json_error( [ 'message' => __( 'Failed to write the file', 'email-editor-plus' ) ] );
			}
			wp_send_json_success( [
				'download'      => true,
				'download_name' => $file_name,
				'download_url'  => EDPW_PLUGIN_URL . 'File/' . $file_name,
				'message'       => __( 'Your template start downloading', 'email-editor-plus' )
			] );
		} catch ( Exception $e ) {

		}
	}

	/**
	 * Get preview data.
	 * @return void
	 */
	public static function getPreviewData() {
		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$sample_data           = [
			[
				'value' => 0,
				'label' => esc_html__( 'Dummy Data', 'email-editor-plus' )
			]
		];
		$type                  = (string) Input::get( 'type' );
		$dis_allowed_templates = (array) apply_filters( 'edpw_disallowed_preview_template_order', [
			'wp_new_user_register_email',
			'wp_retrieve_password_email',
			'wp_password_change_email',
			'wp_email_change_email',
			'customer_reset_password',
			'customer_new_account',

		] );
		if ( ! Plugin::isActive( 'woocommerce/woocommerce.php' ) || in_array( $type, $dis_allowed_templates ) ) {
			wp_send_json_success( (array) apply_filters( 'edpw_preview_template_args', [ 'sample_orders' => $sample_data ] ) );
		}
		try {
			$order_status = wc_get_order_statuses();
			unset( $order_status['wc-checkout-draft'] );

			$query = new WC_Order_Query( [
				'limit'   => 10,
				'orderby' => 'date',
				'order'   => 'DESC',
				'type'    => 'shop_order',
				'status'  => array_keys( $order_status ),
				'return'  => 'ids'
			] );

			$orders = $query->get_orders();

			foreach ( $orders as $order_id ) {
				$sample_data[] = [
					'value' => $order_id,
					'label' => WC::getOrderLabel( $order_id )
				];
			}
		} catch ( Exception $e ) {

		}

		wp_send_json_success( (array) apply_filters( 'edpw_preview_template_args', [ 'sample_orders' => $sample_data ] ) );
	}

	/**
	 * Preview email template.
	 * @return void
	 */
	public static function previewEmailTemplates() {
		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$template_id = (int) Input::get( 'template_id', 0 );
		if ( $template_id <= 0 ) {
			wp_send_json_error( esc_html__( 'Invalid Template ID', 'email-editor-plus' ) );
		}

		$email_template = \EDPW\Core\Models\EmailTemplates::getByKey( $template_id );
		if ( empty( $email_template ) ) {
			wp_send_json_error( esc_html__( 'Template is not found.', 'email-editor-plus' ) );
		}
		$sample_order_id = (int) Input::get( 'sample_order_id', 0 );
		// Need email object for process template.
		if ( Plugin::isActive( 'woocommerce/woocommerce.php' ) ) {
			require_once plugin_dir_path( WC_PLUGIN_FILE ) . 'includes/emails/class-wc-email.php';
			$email_obj     = new WC_Email();
			$email_obj->id = $email_template->type;
		} else {
			$email_obj = (object) [
				'id' => $email_template->type
			];
		}

		$args = [ 'email' => $email_obj ];
		//$heading = esc_html__("Test mail", 'email-editor-plus');
		//$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>' . $heading . '</span></p>';
		//$email_template->html = str_replace('<body>', $change_content, $email_template->html);
		if ( empty( $sample_order_id ) ) {
			$short_code_obj = new ShortCodes( $email_template->type, $email_template, $args, '', true );
			$html           = $short_code_obj->renderSampleTemplate( false, true );
		} else {
			$short_code_obj = new ShortCodes( $email_template->type, $email_template, $args, $sample_order_id, true );
			$html           = $short_code_obj->renderTemplate( false, true );
		}
		wp_send_json_success( [ 'html' => $html ] );
	}

	/**
	 * Send test email.
	 * @return void
	 */
	public static function sendTestMail() {
		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$email           = (string) Input::get( 'email' );
		$template_id     = (int) Input::get( 'template_id', 0 );
		$sample_order_id = (int) Input::get( 'sample_order_id', 0 );

		if ( empty( $email ) || ! filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Please enter a valid email address', 'email-editor-plus' ) ] );
		}
		if ( empty( $template_id ) || $template_id <= 0 || $sample_order_id < 0 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Invalid request', 'email-editor-plus' ) ] );
		}
		$email_template = \EDPW\Core\Models\EmailTemplates::getByKey( $template_id );
		if ( empty( $email_template ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Template is not found', 'email-editor-plus' ) ] );
		}
		if ( Plugin::isActive( 'woocommerce/woocommerce.php' ) ) {
			$email_obj = WC_Emails::instance();
		} else {
			$email_obj = new \stdClass();
		}

		$args = [ 'email' => $email_obj ];
		if ( empty( $sample_order_id ) ) {
			$short_code_obj = new ShortCodes( $email_template->type, $email_template, $args, '', true );
			$html           = $short_code_obj->renderSampleTemplate( false );
		} else {
			$short_code_obj = new ShortCodes( $email_template->type, $email_template, $args, $sample_order_id, true );
			$html           = $short_code_obj->renderTemplate( false );
		}

		$headers = EmailTemplate::getMailHeaders();
		if ( Plugin::isActive( 'woocommerce/woocommerce.php' ) ) {
			if ( wc_mail( $email, esc_html__( 'Test Email', 'email-editor-plus' ), $html, $headers, [] ) ) {
				wp_send_json_success( [ 'message' => esc_html__( 'Email is sent successfully', 'email-editor-plus' ) ] );
			}
		} else {
			if ( wp_mail( $email, esc_html__( 'Test Email', 'email-editor-plus' ), $html, $headers, [] ) ) {
				wp_send_json_success( [ 'message' => esc_html__( 'Email is sent successfully', 'email-editor-plus' ) ] );
			}
		}


		wp_send_json_error( [ 'message' => esc_html__( 'An error occurred while sending the email', 'email-editor-plus' ) ] );
	}

	/**
	 * Get email template.
	 * @return void
	 */
	public static function getEmailTemplate() {
		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$template_id    = (int) Input::get( 'id', 0 );
		$email_template = \EDPW\Core\Models\EmailTemplates::getByKey( $template_id );

		if ( empty( $email_template ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Email template is not found', 'email-editor-plus' ) ] );
		}
		if ( ! empty( $email_template->global_styles ) && is_string( $email_template->global_styles ) ) {
			$email_template->global_styles = json_decode( $email_template->global_styles, true );
		}
		if ( ! empty( $email_template->mj_component_data ) && is_string( $email_template->mj_component_data ) ) {
			$email_template->mj_component_data = json_decode( $email_template->mj_component_data, true );
		}
		wp_send_json_success( apply_filters( 'edpw_edit_email_template', [
			'item'  => $email_template,
			'title' => EmailTemplate::getEmailTitle( $email_template->type )
		] ) );
	}

	/**
	 * Save email templates.
	 * @return void
	 */
	public static function saveEmailTemplate() {
		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$template_id = Input::get( 'template_id', 0 );
		if ( $template_id <= 0 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Template is not found', 'email-editor-plus' ) ] );
		}

		$templates = \EDPW\Core\Models\EmailTemplates::getByKey( $template_id );
		if ( empty( $templates ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Template is not found', 'email-editor-plus' ) ] );
		}
		$template_data = [
			'mjml'              => urldecode( base64_decode( Input::get( 'mjml_content' ) ) ),
			'html'              => urldecode( base64_decode( Input::get( 'html_content' ) ) ),
			'css'               => urldecode( base64_decode( Input::get( 'css_content' ) ) ),
			'global_styles'     => urldecode( base64_decode( Input::get( 'global_styles' ) ) ),
			'mj_component_data' => urldecode( base64_decode( Input::get( 'mj_component_data' ) ) ),
		];
		\EDPW\Core\Models\EmailTemplates::update( $template_data, [ 'id' => $template_id ] );
		wp_send_json_success( [ 'message' => esc_html__( 'Template saved successfully!', 'email-editor-plus' ) ] );
	}

	/**
	 * Copy email template.
	 * @return void
	 */
	public static function copyEmailTemplate() {
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$source_template_id = (int) Input::get( 'copy_from', 0 );

		$source_template = \EDPW\Core\Models\EmailTemplates::getByKey( $source_template_id );
		if ( empty( $source_template ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'The source template could not be found', 'email-editor-plus' ) ] );
		}
		$copy_to_email_type   = (string) Input::get( 'copy_to_email_type' );
		$copy_to_language     = (string) Input::get( 'copy_to_language' );
		$destination_template = \EDPW\Core\Models\EmailTemplates::getTemplateBasedLang( $copy_to_language, $copy_to_email_type );
		if ( empty( $destination_template ) ) {
			$save_data = (array) $source_template;
			unset( $save_data['id'] );
			$save_data['type']      = $copy_to_email_type;
			$save_data['language']  = $copy_to_language;
			$save_data['is_active'] = 0;
			$template_id            = \EDPW\Core\Models\EmailTemplates::saveNewTemplate( $save_data );
			if ( $template_id <= 0 ) {
				wp_send_json_error( [ 'message' => esc_html__( 'Copying of the template has failed', 'email-editor-plus' ) ] );
			}
			wp_send_json_success( [
				'message'  => esc_html__( 'Template copied successfully.', 'email-editor-plus' ),
				'id'       => $template_id,
				'language' => $copy_to_language,
				'type'     => $copy_to_email_type
			] );
		}
		if ( $destination_template->id == $source_template->id ) {
			wp_send_json_error( [ 'message' => wp_kses_post( __( "Can't copy the template because source and destination templates are same!", 'email-editor-plus' ) ) ] );
		}

		$template_data = [
			'css'               => $source_template->css,
			'html'              => $source_template->html,
			'mjml'              => $source_template->mjml,
			'styles'            => $source_template->styles,
			'elements'          => $source_template->elements,
			'global_styles'     => $source_template->global_styles,
			'mj_component_data' => $source_template->mj_component_data,
		];

		\EDPW\Core\Models\EmailTemplates::update( $template_data, [ 'id' => $destination_template->id ] );
		wp_send_json_success( [
			'message'  => esc_html__( 'The old template is successfully replaced with the new template', 'email-editor-plus' ),
			'id'       => $destination_template->id,
			'language' => $copy_to_language,
			'type'     => $copy_to_email_type
		] );
	}

	/**
	 * Choose new template.
	 * @return void
	 */
	public static function getNewTemplateList() {
		$type = (string) Input::get( 'type' );
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) || empty( $type ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}
		$lang = Input::get( 'lang', null );
		wp_send_json_success( [ 'templates' => EmailTemplate::getPreviewTemplatesList( $lang, $type ) ] );
	}

	/**
	 * Save chosen template.
	 * @return void
	 */
	public static function saveChosenTemplate() {
		$type = (string) Input::get( 'type' );
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) || empty( $type ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}
		$lang           = Input::get( 'lang' );
		$template_group = Input::get( 'template_group' );

		if ( empty( $type ) || empty( $template_group ) || empty( $lang ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$save_data   = [
			'type'      => $type,
			'is_active' => 1,
			'mjml'      => EmailTemplate::getDefaultTemplateContent( $template_group, $type, $lang ),
			'language'  => $lang,
		];
		$template_id = \EDPW\Core\Models\EmailTemplates::saveNewTemplate( $save_data );
		if ( $template_id <= 0 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Already template created.', 'email-editor-plus' ) ] );
		}
		wp_send_json_success( [
			'message'  => esc_html__( 'Template saved successfully.', 'email-editor-plus' ),
			'id'       => $template_id,
			'language' => $lang,
			'type'     => $type
		] );
	}

	public static function getShortCodes() {

		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$lang = (string) Input::get( 'lang' );
		$type = (string) Input::get( 'type' );
		if ( empty( $type ) || empty( $lang ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}

		$template_id = (int) Input::get( 'template_id', 0 );
		if ( $template_id <= 0 ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Template is not found', 'email-editor-plus' ) ] );
		}

		$template = \EDPW\Core\Models\EmailTemplates::getByKey( $template_id );
		if ( empty( $template ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Template is not found', 'email-editor-plus' ) ] );
		}
		if ( empty( $template->type ) ) {
			wp_send_json_error( [ 'message' => __( 'Template is invalid', 'email-editor-plus' ) ] );
		}

		$short_codes = [
			'billing_address'  => [
				'label'       => esc_html__( 'Billing Address', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getAddressFields( 'billing', 'desc', 'billing_address.' ) )
			],
			'shipping_address' => [
				'label'       => esc_html__( 'Shipping Address', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getAddressFields( 'shipping', 'desc', 'shipping_address.' ) )
			],
			'shipping_method'  => [
				'label'       => esc_html__( 'Shipping Method', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getShippingMethodFields( 'desc', 'shipping_method.' ) )
			],
			'order'            => [
				'label'       => esc_html__( 'Order', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getOrderFields( 'desc', 'order.' ) )
			],
			'payment'          => [
				'label'       => esc_html__( 'Payment Method', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getPaymentFields( 'desc', 'payment.' ) )
			],
			'customer'         => [
				'label'       => esc_html__( 'Customer', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getCustomerFields( 'desc', 'customer.' ) )
			],
			'social'           => [
				'label'       => esc_html__( 'Social', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getSocialFields( 'desc', 'social.' ) )
			],
			'shop'             => [
				'label'       => esc_html__( 'Shop details', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getShopFields( 'desc', 'shop.' ) )
			],
			'wordpress'        => [
				'label'       => esc_html__( 'WordPress', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getWordPressFields( 'desc', 'wordpress.' ) )
			]
		];
		$order_id    = (string) Input::get( 'order_id' );
		if ( ! empty( $order_id ) ) {
			$short_codes['order_meta'] = [
				'label'       => esc_html__( 'Order Meta', 'email-editor-plus' ),
				'short_codes' => EmailTemplate::formatShortCode( ShortCodeHelper::getOrderMetaFields( 'desc', 'order_meta.', [ 'order' => wc_get_order( $order_id ) ] ) )
			];
		}
		$short_codes = ShortCodeHelper::processShortCodeList( $template->type, $short_codes );
		wp_send_json_success( [ 'items' => apply_filters( 'edpw_short_code_list', $short_codes, $type ) ] );
	}

	/**
	 * Get template options.
	 * @return void
	 */
	public static function getTemplateOptions() {
		if ( ! WC::isSecurityValid( 'edpw-template-list-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic check failed', 'email-editor-plus' ) ] );
		}
		$email_list        = EmailTemplate::getEmailTypeLists();
		$default_templates = EmailTemplate::getDefaultTemplates();
		$is_pro            = EmailTemplate::isPro();
		$items             = [];
		foreach ( $email_list as $template_name => $email ) {
			$email = (object) $email;
			if ( ! is_object( $email ) || ! isset( $email->title ) || ! EmailTemplate::getPreviewUrl( 'default', $email->id ) ) {
				continue;
			}

			$is_selectable = false;
			if ( in_array( $template_name, $default_templates ) || $is_pro ) {
				$is_selectable = true;
			}
			$items[] = [
				'label'         => $email->title,
				'value'         => $email->id,
				'is_selectable' => $is_selectable
			];
		}
		wp_send_json_success( [
			'items' => $items
		] );

	}

	public static function getImageList() {
		if ( ! WC::isSecurityValid( 'edpw-template-nonce' ) ) {
			wp_send_json_error( [ 'message' => esc_html__( 'Basic validation has failed', 'email-editor-plus' ) ] );
		}
		$query         = [
			'orderby'        => 'date',
			'order'          => 'DESC',
			'posts_per_page' => (int) Input::get( 'limit', 20 ),
			'paged'          => (int) Input::get( 'page', 1 ),
			'post_mime_type' => 'image',
			'post_type'      => 'attachment',
			//'post_id'        => 0,
			'post_status'    => 'inherit,private'
		];
		$selected_date = (string) Input::get( 'date' );

		if ( ! empty( $selected_date ) && $selected_date != '0' ) {
			$dates = explode( '|', $selected_date );
			if ( count( $dates ) == 2 ) {
				$query['year']     = $dates[0];
				$query['monthnum'] = $dates[1];
			}
		}
		$search = (string) Input::get( 'search' );
		if ( ! empty( $search ) ) {
			$query['s'] = $search;
			add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' );
		}
		//phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		$query             = apply_filters( 'ajax_query_attachments_args', $query );
		$attachments_query = new \WP_Query( $query );
		$posts             = array_map( 'wp_prepare_attachment_for_js', $attachments_query->posts );
		$posts             = array_filter( $posts );

		wp_send_json_success( [ 'items' => $posts ] );
	}

	/**
	 * This function adds a custom column to the email listing table in WooCommerce → Settings → Emails.
	 *
	 * @param $column
	 *
	 * @return array|mixed
	 */
	public static function setEmailTemplateColumns( $column ) {
		if ( empty( $column ) || ! is_array( $column ) ) {
			return $column;
		}
		if ( isset( $column['actions'] ) ) {
			unset( $column['actions'] );

			return array_merge(
				$column,
				[
					'spark_email_editor' => __( 'Spark Email Editor', 'email-editor-plus' ),
					'actions'            => '',
				]
			);

		}

		return $column;
	}

	/**
	 * This function displays the "Customize with Spark" button for both active and inactive email templates in the Spark Email Editor section on the WooCommerce Email Settings page.
	 *
	 * @param $email
	 *
	 * @return void
	 */
	public static function setEmailTemplateColumnContent( $email ) {
		// Validate the incoming object early and output an empty cell when invalid.
		if ( empty( $email ) || ! is_object( $email ) ) {
			echo '<td></td>';

			return;
		}

		// Define all supported WooCommerce email template IDs and allow 3rd-party filtering.
		$templates_ids = EmailTemplate::getAllEmailTemplateIds();
		$templates     = array_merge( ...array_values( $templates_ids ) );
		// If the current email is not handled by Spark, bail out.
		if ( ! in_array( $email->id, $templates, true ) ) {
			echo '<td></td>';

			return;
		}

		// Retrieve saved templates once and search for a match.
		$saved_templates     = \EDPW\Core\Models\EmailTemplates::getSavedTemplates( WC::getSiteDefaultLang() );
		$matched_template_id = null;
		foreach ( $saved_templates as $template ) {
			if ( isset( $template->type, $template->id ) && $template->type === $email->id ) {
				$matched_template_id = $template->id;
				break; // Only the first match is needed.
			}
		}

		$slug = EmailTemplate::isPro() ? 'email-editor-plus-pro' : 'email-editor-plus';
		$url  = $matched_template_id
			? admin_url( sprintf( 'admin.php?page=%s#/templates/%s/%s', $slug, $email->id, $matched_template_id ) )
			: admin_url( sprintf( 'admin.php?page=%s#/templates/%s/', $slug, $email->id ) );

		printf(
			'<td><a class="button button-primary" href="%s" target="_blank">%s</a></td>',
			esc_url( $url ),
			esc_html__( 'Customize with Spark', 'email-editor-plus' ) . ' - (' . esc_html( WC::getSiteDefaultLang() ) . ')'
		);
	}
}
