<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'B2bking_Email_Controls' ) ) {
	class B2bking_Email_Controls {

		private static $instance = null;

		public static function init() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		private function __construct() {
			add_filter( 'woocommerce_locate_template', array( $this, 'maybe_use_custom_template' ), 1, 3 );
			add_filter( 'b2bking_recipient_new_message', array( $this, 'new_message_recipient' ), 5, 2 );
			add_filter( 'b2bking_recipient_new_message_quote', array( $this, 'new_message_quote_recipient' ), 5, 2 );
			foreach ( array(
				'b2bking_new_customer_email',
				'b2bking_new_customer_requires_approval_email',
				'b2bking_your_account_approved_email',
				'b2bking_your_account_rejected_email',
				'b2bking_quote_received_email',
				'b2bking_new_message_email',
				'b2bking_new_offer_email',
			) as $email_id ) {
				add_filter( 'woocommerce_email_subject_' . $email_id, array( $this, 'replace_subject_placeholders' ), 20, 3 );
				add_filter( 'woocommerce_email_heading_' . $email_id, array( $this, 'replace_subject_placeholders' ), 20, 3 );
			}
			add_action( 'wp_ajax_b2bking_send_test_email', array( $this, 'ajax_send_test_email' ) );
		}

		public function ajax_send_test_email() {
			check_ajax_referer( 'b2bking_security_nonce', 'security' );
			if ( ! current_user_can( 'manage_woocommerce' ) ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'b2bking' ) ) );
			}

			$email_id  = isset( $_POST['email_id'] ) ? sanitize_text_field( wp_unslash( $_POST['email_id'] ) ) : '';
			$recipient = isset( $_POST['recipient'] ) ? sanitize_email( wp_unslash( $_POST['recipient'] ) ) : '';
			$emails    = $this->get_emails();
			if ( ! isset( $emails[ $email_id ] ) || ! is_email( $recipient ) ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Invalid email type or recipient address.', 'b2bking' ) ) );
			}

			$instance = $this->get_wc_email_instance( $email_id );
			if ( ! $instance ) {
				wp_send_json_error( array( 'message' => esc_html__( 'Email handler not found.', 'b2bking' ) ) );
			}

			$user                = wp_get_current_user();
			$instance->recipient = $recipient;
			if ( property_exists( $instance, 'user_login' ) ) {
				$instance->user_login = $user->user_login;
			}
			if ( property_exists( $instance, 'user_email' ) ) {
				$instance->user_email = $user->user_email;
			}
			if ( property_exists( $instance, 'userid' ) ) {
				$instance->userid = ( 'b2bking_new_message_email' === $email_id ) ? $user->user_login : $user->ID;
			}
			if ( property_exists( $instance, 'message' ) ) {
				$instance->message = esc_html__( 'This is a test message sent from B2BKing email settings.', 'b2bking' );
			}
			if ( property_exists( $instance, 'conversationid' ) ) {
				$instance->conversationid = 0;
			}
			if ( property_exists( $instance, 'offerid' ) ) {
				$instance->offerid = 0;
			}
			if ( property_exists( $instance, 'offerlink' ) ) {
				$instance->offerlink = admin_url();
			}

			$sent = $instance->send( $recipient, $instance->get_subject(), $instance->get_content(), $instance->get_headers(), $instance->get_attachments() );
			if ( $sent ) {
				/* translators: %s: recipient email address */
				wp_send_json_success( array( 'message' => sprintf( esc_html__( 'Test email sent to %s.', 'b2bking' ), $recipient ) ) );
			}
			wp_send_json_error( array( 'message' => esc_html__( 'Failed to send test email. Check your site\'s mail configuration.', 'b2bking' ) ) );
		}

		public function get_emails() {
			return array(
				'b2bking_new_customer_email'                   => array(
					'title'              => esc_html__( 'New Customer', 'b2bking' ),
					'category'           => esc_html__( 'Registration', 'b2bking' ),
					'description'        => esc_html__( 'Sent to admin when any customer registers. Useful for B2B-only stores.', 'b2bking' ),
					'template_html'      => 'new-customer-email-template.php',
					'template_plain'     => 'plain-new-customer-email-template.php',
					'supports_recipient' => true,
					'default_subject'    => esc_html__( 'New customer registration', 'b2bking' ),
					'default_content'    => "You have a new customer registration.\n\nUsername: {user_login}\nEmail: {user_email}",
					'placeholders'       => array(
						'site_title'          => esc_html__( 'Site title', 'b2bking' ),
						'user_login'          => esc_html__( 'Username', 'b2bking' ),
						'user_email'          => esc_html__( 'User email', 'b2bking' ),
						'registration_fields' => esc_html__( 'All submitted registration fields', 'b2bking' ),
						'registration_field_ID' => esc_html__( 'Single registration field by ID (replace ID with number)', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'user_login', 'user_email' ),
				),
				'b2bking_new_customer_requires_approval_email' => array(
					'title'              => esc_html__( 'New Customer Requires Approval', 'b2bking' ),
					'category'           => esc_html__( 'Registration', 'b2bking' ),
					'description'        => esc_html__( 'Sent to admin when a customer registers and needs approval.', 'b2bking' ),
					'template_html'      => 'new-customer-requires-approval-email-template.php',
					'template_plain'     => 'plain-new-customer-requires-approval-email-template.php',
					'supports_recipient' => true,
					'default_subject'    => esc_html__( 'New customer requires approval', 'b2bking' ),
					'default_content'    => "You have a new customer registration that requires approval.\n\nUsername: {user_login}\nEmail: {user_email}\n\n<a href=\"{review_link}\">Click to Review User</a>",
					'placeholders'       => array(
						'site_title'          => esc_html__( 'Site title', 'b2bking' ),
						'user_login'          => esc_html__( 'Username', 'b2bking' ),
						'user_email'          => esc_html__( 'User email', 'b2bking' ),
						'review_link'         => esc_html__( 'Review user link', 'b2bking' ),
						'registration_fields' => esc_html__( 'All submitted registration fields', 'b2bking' ),
						'registration_field_ID' => esc_html__( 'Single registration field by ID (replace ID with number)', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'user_login', 'user_email' ),
				),
				'b2bking_your_account_approved_email'         => array(
					'title'           => esc_html__( 'Account Approved', 'b2bking' ),
					'category'        => esc_html__( 'Registration', 'b2bking' ),
					'description'     => esc_html__( 'Sent to the customer when their account is approved.', 'b2bking' ),
					'template_html'   => 'your-account-approved-email-template.php',
					'template_plain'  => 'plain-your-account-approved-email-template.php',
					'default_subject' => esc_html__( 'Your account has been approved', 'b2bking' ),
					'default_content' => "Hi {first_name},\n\nCongratulations! Your account has been approved.",
					'placeholders'    => array(
						'site_title' => esc_html__( 'Site title', 'b2bking' ),
						'first_name' => esc_html__( 'First name', 'b2bking' ),
						'user_email' => esc_html__( 'User email', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'first_name', 'user_email' ),
				),
				'b2bking_your_account_rejected_email'         => array(
					'title'           => esc_html__( 'Account Rejected', 'b2bking' ),
					'category'        => esc_html__( 'Registration', 'b2bking' ),
					'description'     => esc_html__( 'Sent to the customer when their account registration is rejected.', 'b2bking' ),
					'template_html'   => 'your-account-rejected-email-template.php',
					'template_plain'  => 'plain-your-account-rejected-email-template.php',
					'default_subject' => esc_html__( 'Your account registration was not approved', 'b2bking' ),
					'default_content' => "Hi {first_name},\n\nWe are sorry to inform you that your account registration was not approved.",
					'placeholders'    => array(
						'site_title' => esc_html__( 'Site title', 'b2bking' ),
						'first_name' => esc_html__( 'First name', 'b2bking' ),
						'user_email' => esc_html__( 'User email', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'first_name', 'user_email' ),
				),
				'b2bking_quote_received_email'                => array(
					'title'           => esc_html__( 'Quote Request Received', 'b2bking' ),
					'category'        => esc_html__( 'Quotes & Messages', 'b2bking' ),
					'description'     => esc_html__( 'Confirmation email sent to the customer after they submit a quote request.', 'b2bking' ),
					'template_html'   => 'quote-received-email-template.php',
					'template_plain'  => 'plain-quote-received-email-template.php',
					'default_subject' => esc_html__( 'We have received your quote request', 'b2bking' ),
					'default_content' => "We have received your quote request and will be in touch with you shortly. Here is your quote request:\n\n{message}",
					'placeholders'    => array(
						'site_title' => esc_html__( 'Site title', 'b2bking' ),
						'first_name' => esc_html__( 'First name', 'b2bking' ),
						'user_email' => esc_html__( 'User email', 'b2bking' ),
						'message'    => esc_html__( 'Quote request content', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'first_name', 'user_email' ),
					'audience_options' => array(
						'guests' => esc_html__( 'Guests only (default)', 'b2bking' ),
						'all'    => esc_html__( 'All customers (guests + logged-in)', 'b2bking' ),
					),
				),
				'b2bking_new_message_email'                   => array(
					'title'              => esc_html__( 'New Message / Conversation', 'b2bking' ),
					'category'           => esc_html__( 'Quotes & Messages', 'b2bking' ),
					'description'        => esc_html__( 'Generic notification for conversations, quote requests, order approvals, subaccounts, and other system messages. Admin recipients apply to customer messages and quote requests; admin replies go to the relevant customer automatically.', 'b2bking' ),
					'template_html'      => 'new-message-email-template.php',
					'template_plain'     => 'plain-new-message-email-template.php',
					'virtual_recipients' => array(
						'new_message' => esc_html__( 'Admin Recipients for Messages', 'b2bking' ),
						'quote'       => esc_html__( 'Admin Recipients for Quotes', 'b2bking' ),
					),
					'default_subject'    => esc_html__( 'New message / conversation', 'b2bking' ),
					'default_content'    => "You have a new message.\n\nUser: {user_login}\n\nMessage:\n{message}",
					'placeholders'       => array(
						'site_title'      => esc_html__( 'Site title', 'b2bking' ),
						'user_login'      => esc_html__( 'Username', 'b2bking' ),
						'message'         => esc_html__( 'Message content', 'b2bking' ),
						'conversation_id' => esc_html__( 'Conversation ID', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'user_login', 'conversation_id' ),
				),
				'b2bking_new_offer_email'                     => array(
					'title'           => esc_html__( 'New Offer', 'b2bking' ),
					'category'        => esc_html__( 'Quotes & Messages', 'b2bking' ),
					'description'     => esc_html__( 'Sent to the customer when admin emails an offer or replies to a quote request with an offer.', 'b2bking' ),
					'template_html'   => 'new-offer-email-template.php',
					'template_plain'  => 'plain-new-offer-email-template.php',
					'default_subject' => esc_html__( 'You received a new offer!', 'b2bking' ),
					'default_content' => "You've received a new offer.\n\nOffer #{offer_id}\n\n{offer_custom_text}\n\n<a href=\"{offer_link}\">View offer</a>",
					'placeholders'    => array(
						'site_title'        => esc_html__( 'Site title', 'b2bking' ),
						'offer_id'          => esc_html__( 'Offer ID', 'b2bking' ),
						'offer_link'        => esc_html__( 'Offer link', 'b2bking' ),
						'offer_custom_text' => esc_html__( 'Offer custom text', 'b2bking' ),
					),
					'subject_placeholders' => array( 'site_title', 'offer_id' ),
				),
			);
		}

		public function get_wc_option_name( $email_id ) {
			return 'woocommerce_' . $email_id . '_settings';
		}

		private function get_wc_email_instance( $email_id ) {
			if ( ! function_exists( 'WC' ) || ! WC()->mailer() ) {
				return null;
			}
			foreach ( WC()->mailer()->get_emails() as $e ) {
				if ( isset( $e->id ) && $e->id === $email_id ) {
					return $e;
				}
			}
			return null;
		}

		public function new_message_recipient( $recipient, $conversation_id ) {
			$settings = get_option( 'b2bking_email_controls_settings', array() );
			$setting  = isset( $settings['virtual_recipients']['new_message'] ) ? sanitize_text_field( $settings['virtual_recipients']['new_message'] ) : '';
			return '' !== $setting ? $setting : $recipient;
		}

		public function new_message_quote_recipient( $recipient, $conversation_id ) {
			$settings = get_option( 'b2bking_email_controls_settings', array() );
			$setting  = isset( $settings['virtual_recipients']['quote'] ) ? sanitize_text_field( $settings['virtual_recipients']['quote'] ) : '';
			return '' !== $setting ? $setting : $recipient;
		}

		public function maybe_use_custom_template( $template, $template_name, $template_path ) {
			if ( strpos( $template_path, B2BKING_DIR ) === false ) {
				return $template;
			}

			$settings = get_option( 'b2bking_email_controls_settings', array() );
			foreach ( $this->get_emails() as $email_id => $email ) {
				if ( ! isset( $settings[ $email_id ]['custom_enabled'] ) || 'yes' !== $settings[ $email_id ]['custom_enabled'] ) {
					continue;
				}

				if ( isset( $email['template_html'] ) && $template_name === $email['template_html'] ) {
					return B2BKING_DIR . 'includes/emails/templates/custom-email-template.php';
				}

				if ( isset( $email['template_plain'] ) && $template_name === $email['template_plain'] ) {
					return B2BKING_DIR . 'includes/emails/templates/plain-custom-email-template.php';
				}
			}

			return $template;
		}

		public function render_custom_content( $email_id, $context, $plain_text = false ) {
			$emails   = $this->get_emails();
			$settings = get_option( 'b2bking_email_controls_settings', array() );
			$content  = isset( $settings[ $email_id ]['custom_content'] ) && '' !== trim( $settings[ $email_id ]['custom_content'] ) ? $settings[ $email_id ]['custom_content'] : $emails[ $email_id ]['default_content'];

			if ( ! $plain_text ) {
				$content = preg_replace( '/(?<!href=")(?<!href=\')\{(review_link|offer_link)\}/', '<a href="{$1}">{$1}</a>', $content );
			}

			foreach ( $this->get_placeholder_values( $email_id, $context, $plain_text ) as $placeholder => $value ) {
				$content = str_replace( '{' . $placeholder . '}', $value, $content );
			}

			$user = $this->get_context_user( $email_id, $context );
			if ( $user && isset( $user->ID ) ) {
				$user_id = $user->ID;
				$content = preg_replace_callback(
					'/\{registration_field_(\d+)\}/',
					function ( $m ) use ( $user_id, $plain_text ) {
						$value = get_user_meta( $user_id, 'b2bking_custom_field_' . $m[1], true );
						if ( '' === $value ) {
							return '';
						}
						return $plain_text ? wp_strip_all_tags( $value ) : esc_html( $value );
					},
					$content
				);
			}

			if ( $plain_text ) {
				return trim( wp_strip_all_tags( $content ) );
			}

			return wp_kses_post( wpautop( wptexturize( $content ) ) );
		}

		public function replace_subject_placeholders( $text, $object = false, $email = false ) {
			$emails = $this->get_emails();
			if ( ! is_object( $email ) || empty( $email->id ) || ! isset( $emails[ $email->id ] ) ) {
				return $text;
			}

			$context = array( 'email' => $email );
			foreach ( array( 'user_login', 'userid', 'message', 'conversationid', 'offerid', 'offerlink' ) as $property ) {
				if ( isset( $email->{$property} ) ) {
					$context[ $property ] = $email->{$property};
				}
			}

			$values = $this->get_placeholder_values( $email->id, $context, true );
			foreach ( $emails[ $email->id ]['subject_placeholders'] as $placeholder ) {
				if ( isset( $values[ $placeholder ] ) ) {
					$text = str_replace( '{' . $placeholder . '}', $values[ $placeholder ], $text );
				}
			}

			return wp_strip_all_tags( $text );
		}

		private function build_registration_fields( $user_id, $plain_text ) {
			$field_ids = get_posts( array(
				'post_type'   => 'b2bking_custom_field',
				'post_status' => 'publish',
				'numberposts' => -1,
				'orderby'     => 'menu_order',
				'order'       => 'ASC',
				'fields'      => 'ids',
			) );

			$lines = array();
			foreach ( $field_ids as $field_id ) {
				if ( 'file' === get_post_meta( $field_id, 'b2bking_custom_field_field_type', true ) ) {
					continue;
				}
				$value = get_user_meta( $user_id, 'b2bking_custom_field_' . $field_id, true );
				if ( '' === $value || null === $value ) {
					continue;
				}
				$label = get_post_meta( $field_id, 'b2bking_custom_field_field_label', true );
				if ( $plain_text ) {
					$lines[] = wp_strip_all_tags( $label ) . ': ' . wp_strip_all_tags( $value );
				} else {
					$lines[] = '<strong>' . esc_html( $label ) . ':</strong> ' . esc_html( $value );
				}
			}

			return implode( $plain_text ? "\n" : '<br>', $lines );
		}

		private function get_placeholder_values( $email_id, $context, $plain_text = false ) {
			$user       = $this->get_context_user( $email_id, $context );
			$user_login = '';
			$user_email = '';
			$first_name = '';

			if ( $user && isset( $user->ID ) ) {
				$user_login = $user->user_login;
				$user_email = $user->user_email;
				$first_name = get_user_meta( $user->ID, 'billing_first_name', true );
				if ( '' === $first_name ) {
					$first_name = $user->first_name;
				}
			}

			if ( isset( $context['userid'] ) && ! is_numeric( $context['userid'] ) && strpos( $context['userid'], 'Quoteemail' ) !== 0 ) {
				$user_login = $context['userid'];
			}

			$conversation_id = isset( $context['conversationid'] ) ? intval( $context['conversationid'] ) : 0;
			$message        = isset( $context['message'] ) ? $context['message'] : '';
			$offer_id          = isset( $context['offerid'] ) ? intval( $context['offerid'] ) : 0;
			$offer_link        = isset( $context['offerlink'] ) ? esc_url( $context['offerlink'] ) : '';
			$offer_custom_text = $offer_id ? get_post_meta( apply_filters( 'wpml_object_id', $offer_id, 'post', true ), 'b2bking_offer_customtext_textarea', true ) : '';
			$review_link       = '';

			if ( $user && isset( $user->ID ) ) {
				$review_link = admin_url( '/user-edit.php?user_id=' . $user->ID . '#b2bking_registration_data_container' );
			}

			$registration_fields = ( $user && isset( $user->ID ) ) ? $this->build_registration_fields( $user->ID, $plain_text ) : '';

			if ( $plain_text ) {
				return array(
					'site_title'          => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
					'user_login'          => $user_login,
					'user_email'          => $user_email,
					'first_name'          => $first_name,
					'message'             => wp_strip_all_tags( $message ),
					'conversation_id'     => $conversation_id ? (string) $conversation_id : '',
					'review_link'         => $review_link,
					'offer_id'            => $offer_id ? (string) $offer_id : '',
					'offer_link'          => $offer_link,
					'offer_custom_text'   => wp_strip_all_tags( $offer_custom_text ),
					'registration_fields' => $registration_fields,
				);
			}

			return array(
				'site_title'          => esc_html( get_bloginfo( 'name' ) ),
				'user_login'          => esc_html( $user_login ),
				'user_email'          => esc_html( $user_email ),
				'first_name'          => esc_html( $first_name ),
				'message'             => wp_kses( $message, array( 'br' => true, 'b' => true, 'strong' => true, 'a' => array( 'href' => array() ) ) ),
				'conversation_id'     => $conversation_id ? esc_html( $conversation_id ) : '',
				'review_link'         => esc_url( $review_link ),
				'offer_id'            => $offer_id ? esc_html( $offer_id ) : '',
				'offer_link'          => esc_url( $offer_link ),
				'offer_custom_text'   => nl2br( esc_html( $offer_custom_text ) ),
				'registration_fields' => $registration_fields,
			);
		}

		private function get_context_user( $email_id, $context ) {
			if ( isset( $context['user_login'] ) && '' !== $context['user_login'] ) {
				$user = get_user_by( 'login', $context['user_login'] );
				if ( $user ) {
					return $user;
				}
			}

			if ( isset( $context['userid'] ) && is_numeric( $context['userid'] ) ) {
				$user = get_user_by( 'id', intval( $context['userid'] ) );
				if ( $user ) {
					return $user;
				}
			}

			if ( isset( $context['email'] ) && isset( $context['email']->recipient ) ) {
				$user = get_user_by( 'email', $context['email']->recipient );
				if ( $user ) {
					return $user;
				}
			}

			return false;
		}

		public function sanitize_controls( $input ) {
			$output = array(
				'virtual_recipients' => array(),
			);

			if ( ! is_array( $input ) ) {
				return $output;
			}

			if ( isset( $input['virtual_recipients'] ) && is_array( $input['virtual_recipients'] ) ) {
				foreach ( array( 'new_message', 'quote' ) as $key ) {
					if ( isset( $input['virtual_recipients'][ $key ] ) ) {
						$output['virtual_recipients'][ $key ] = sanitize_text_field( $input['virtual_recipients'][ $key ] );
					}
				}
			}

			foreach ( $this->get_emails() as $email_id => $email ) {
				$output[ $email_id ] = array(
					'custom_enabled' => 'no',
					'custom_content' => '',
				);

				if ( isset( $input[ $email_id ] ) && is_array( $input[ $email_id ] ) ) {
					$output[ $email_id ]['custom_enabled'] = isset( $input[ $email_id ]['custom_enabled'] ) && 'yes' === $input[ $email_id ]['custom_enabled'] ? 'yes' : 'no';
					$output[ $email_id ]['custom_content'] = isset( $input[ $email_id ]['custom_content'] ) ? wp_kses_post( $input[ $email_id ]['custom_content'] ) : '';
				}
			}

			return $output;
		}

		public function sanitize_wc_settings( $input, $email_id ) {
			$existing = get_option( $this->get_wc_option_name( $email_id ), array() );
			$output   = is_array( $existing ) ? $existing : array();

			if ( ! is_array( $input ) ) {
				return $output;
			}

			if ( isset( $input['enabled'] ) ) {
				$output['enabled'] = 'yes' === $input['enabled'] ? 'yes' : 'no';
			}

			if ( isset( $input['recipient'] ) ) {
				$output['recipient'] = sanitize_text_field( $input['recipient'] );
			}

			if ( isset( $input['subject_heading'] ) ) {
				$output['subject'] = sanitize_text_field( $input['subject_heading'] );
				$output['heading'] = sanitize_text_field( $input['subject_heading'] );
			}

			$emails = $this->get_emails();
			if ( isset( $input['audience'], $emails[ $email_id ]['audience_options'][ $input['audience'] ] ) ) {
				$output['audience'] = $input['audience'];
			}

			return $output;
		}

		public function render_settings_tab( $active_class = '' ) {
			?>
			<div class="ui bottom attached tab segment b2bking_emailsettings_tab <?php echo esc_attr( $active_class ); ?>" data-tab="emails">
				<div class="b2bking_attached_content_wrapper">
					<div class="b2bking_settings_accordion_header">
						<h2 class="ui block header">
							<i class="envelope outline icon"></i>
							<div class="content">
								<?php esc_html_e( 'Emails', 'b2bking' ); ?>
							</div>
							<button
								type="button"
								class="ui mini basic button b2bking_settings_accordion_toggle_all"
								data-expand-label="<?php echo esc_attr__( 'Expand all', 'b2bking' ); ?>"
								data-collapse-label="<?php echo esc_attr__( 'Collapse all', 'b2bking' ); ?>"
							>
								<?php esc_html_e( 'Expand all', 'b2bking' ); ?>
							</button>
						</h2>
					</div>

					<?php if ( ! defined( 'B2BKINGLABEL_DIR' ) ) : ?>
						<div class="ui ignored info icon message b2bking_email_documentation_message">
							<div class="content">
								<h3 class="header"><?php esc_html_e( 'Documentation', 'b2bking' ); ?></h3>
								<p>
									<?php
									$email_design_link = '<a href="https://woocommerce-b2b-plugin.com/docs/how-to-customize-b2bking-emails/" target="_blank" style="color: #295b6b"><span>&nbsp;<i class="paint brush icon"></i><strong style="text-decoration: underline;">%s</strong></span></a>';
									$template_link     = '<a href="https://woocommerce-b2b-plugin.com/docs/how-to-customize-b2bking-emails/" target="_blank" style="color: #295b6b"><span style="color: #295b6b">&nbsp;&nbsp;<i class="code icon"></i><strong style="text-decoration: underline;">%s</strong></span></a>';

									$translated_text = sprintf(
										/* translators: %1$s: Linked text for 'customize email design', %2$s: Linked text for 'completely overwrite PHP templates' */
										esc_html__( 'Learn how to %1$s or %2$s for more control.', 'b2bking' ),
										sprintf( $email_design_link, esc_html__( 'customize email design', 'b2bking' ) ),
										sprintf( $template_link, esc_html__( 'completely overwrite PHP templates', 'b2bking' ) )
									);

									echo wp_kses(
										$translated_text,
										array(
											'a'      => array(
												'href'   => array(),
												'target' => array(),
												'style'  => array(),
											),
											'span'   => array(
												'style' => array(),
											),
											'i'      => array(
												'class' => array(),
											),
											'strong' => array(
												'style' => array(),
											),
										)
									);
									?>
								</p>
							</div>
							<svg viewBox="0 0 24 24" fill="#333" xmlns="http://www.w3.org/2000/svg" style="width: 50px;"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M6.27103 2.11151C5.46135 2.21816 5.03258 2.41324 4.72718 2.71244C4.42179 3.01165 4.22268 3.43172 4.11382 4.225C4.00176 5.04159 4 6.12387 4 7.67568V16.2442C4.38867 15.9781 4.82674 15.7756 5.29899 15.6517C5.82716 15.513 6.44305 15.5132 7.34563 15.5135L20 15.5135V7.67568C20 6.12387 19.9982 5.04159 19.8862 4.22499C19.7773 3.43172 19.5782 3.01165 19.2728 2.71244C18.9674 2.41324 18.5387 2.21816 17.729 2.11151C16.8955 2.00172 15.7908 2 14.2069 2H9.7931C8.2092 2 7.10452 2.00172 6.27103 2.11151ZM6.75862 6.59459C6.75862 6.1468 7.12914 5.78378 7.58621 5.78378H16.4138C16.8709 5.78378 17.2414 6.1468 17.2414 6.59459C17.2414 7.04239 16.8709 7.40541 16.4138 7.40541H7.58621C7.12914 7.40541 6.75862 7.04239 6.75862 6.59459ZM7.58621 9.56757C7.12914 9.56757 6.75862 9.93058 6.75862 10.3784C6.75862 10.8262 7.12914 11.1892 7.58621 11.1892H13.1034C13.5605 11.1892 13.931 10.8262 13.931 10.3784C13.931 9.93058 13.5605 9.56757 13.1034 9.56757H7.58621Z" fill="#6aacc0"></path> <path d="M8.68965 17.1351H7.47341C6.39395 17.1351 6.01657 17.1421 5.72738 17.218C4.93365 17.4264 4.30088 18.0044 4.02952 18.7558C4.0463 19.1382 4.07259 19.4746 4.11382 19.775C4.22268 20.5683 4.42179 20.9884 4.72718 21.2876C5.03258 21.5868 5.46135 21.7818 6.27103 21.8885C7.10452 21.9983 8.2092 22 9.7931 22H14.2069C15.7908 22 16.8955 21.9983 17.729 21.8885C18.5387 21.7818 18.9674 21.5868 19.2728 21.2876C19.5782 20.9884 19.7773 20.5683 19.8862 19.775C19.9776 19.1088 19.9956 18.2657 19.9991 17.1351H13.1034V20.1417C13.1034 20.4397 13.1034 20.5886 12.9988 20.6488C12.8941 20.709 12.751 20.6424 12.4647 20.5092L11.0939 19.8713C10.9971 19.8262 10.9486 19.8037 10.8966 19.8037C10.8445 19.8037 10.796 19.8037 10.6992 19.8713L9.32842 20.5092C9.04213 20.6424 8.89899 20.709 8.79432 20.6488C8.68965 20.5886 8.68965 20.4397 8.68965 20.1417V17.1351Z" fill="#6aacc0"></path></g></svg>
						</div>
					<?php endif; ?>

					<div class="ui styled accordion b2bking_accordion b2bking_settings_accordion b2bking_email_settings_accordion">
						<?php foreach ( $this->get_emails() as $email_id => $email ) : ?>
							<?php $this->render_email_panel( $email_id, $email ); ?>
						<?php endforeach; ?>
					</div>
				</div>
			</div>
			<?php
		}

		private function render_email_panel( $email_id, $email ) {
			$wc_settings  = get_option( $this->get_wc_option_name( $email_id ), array() );
			$all_controls = get_option( 'b2bking_email_controls_settings', array() );
			$wc_settings  = is_array( $wc_settings ) ? $wc_settings : array();
			$controls     = isset( $all_controls[ $email_id ] ) && is_array( $all_controls[ $email_id ] ) ? $all_controls[ $email_id ] : array();
			$option_name = $this->get_wc_option_name( $email_id );
			if ( isset( $wc_settings['enabled'] ) ) {
				$enabled = $wc_settings['enabled'];
			} else {
				$instance = $this->get_wc_email_instance( $email_id );
				$enabled  = $instance ? $instance->enabled : 'yes';
				}
				$is_custom   = isset( $controls['custom_enabled'] ) && 'yes' === $controls['custom_enabled'];
				$content     = isset( $controls['custom_content'] ) && '' !== trim( $controls['custom_content'] ) ? $controls['custom_content'] : $email['default_content'];
				$preview_content = $email['default_content'];
				foreach ( $this->get_placeholder_values( $email_id, array(), false ) as $placeholder => $value ) {
					if ( '' !== trim( wp_strip_all_tags( (string) $value ) ) ) {
						$preview_content = str_replace( '{' . $placeholder . '}', $value, $preview_content );
					}
				}
				$preview_content = preg_replace( '/href=("|\')\{[^}]+\}\1/', 'href="#"', $preview_content );
				$subject_heading = '';
				$recipient_tip   = esc_html__( 'You can add multiple email addresses, separated by commas.', 'b2bking' );
			$placeholder_list = array();
			foreach ( $email['subject_placeholders'] as $placeholder ) {
				$placeholder_list[] = '{' . $placeholder . '}';
			}
			$subject_tip = sprintf( esc_html__( 'You can use these placeholders in the email subject: %s', 'b2bking' ), implode( ', ', $placeholder_list ) );
			if ( isset( $wc_settings['subject'] ) && '' !== $wc_settings['subject'] ) {
				$subject_heading = $wc_settings['subject'];
			} elseif ( isset( $wc_settings['heading'] ) && '' !== $wc_settings['heading'] ) {
				$subject_heading = $wc_settings['heading'];
			} elseif ( isset( $email['default_subject'] ) ) {
				$subject_heading = $email['default_subject'];
			}
			?>
			<div class="title">
				<i class="dropdown icon"></i>
				<span class="ui toggle checkbox b2bking_email_title_toggle b2bking_email_send_toggle">
					<input type="checkbox" class="b2bking_email_title_enabled" data-email-id="<?php echo esc_attr( $email_id ); ?>" <?php checked( $enabled, 'yes' ); ?>>
					<label></label>
				</span>
				<?php if ( ! empty( $email['category'] ) ) : ?>
					<span class="b2bking_email_title_category"><?php echo esc_html( $email['category'] ); ?></span>
					<span class="b2bking_email_title_dash">&mdash;</span>
				<?php endif; ?>
				<span class="b2bking_email_title_text"><?php echo esc_html( $email['title'] ); ?></span>
			</div>
				<div class="content">
					<div class="ui form b2bking_email_settings_panel">
						<p class="b2bking_email_settings_description"><?php echo esc_html( $email['description'] ); ?></p>

						<div class="b2bking_email_settings_grid">
						<label><?php esc_html_e( 'Enable Email', 'b2bking' ); ?></label>
						<div class="ui toggle checkbox b2bking_email_send_toggle">
							<input type="hidden" name="<?php echo esc_attr( $option_name ); ?>[enabled]" value="no">
							<input type="checkbox" class="b2bking_email_panel_enabled" data-email-id="<?php echo esc_attr( $email_id ); ?>" name="<?php echo esc_attr( $option_name ); ?>[enabled]" value="yes" <?php checked( $enabled, 'yes' ); ?>>
							<label></label>
						</div>

						<?php if ( ! empty( $email['supports_recipient'] ) ) : ?>
							<label>
								<?php esc_html_e( 'Recipient(s)', 'b2bking' ); ?>
								<?php echo wc_help_tip( $recipient_tip, false ); ?>
							</label>
							<input type="text" name="<?php echo esc_attr( $option_name ); ?>[recipient]" value="<?php echo esc_attr( isset( $wc_settings['recipient'] ) ? $wc_settings['recipient'] : '' ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
						<?php endif; ?>

						<?php if ( ! empty( $email['virtual_recipients'] ) ) : ?>
							<?php foreach ( $email['virtual_recipients'] as $key => $label ) : ?>
								<?php $virtual_recipient = isset( $all_controls['virtual_recipients'][ $key ] ) ? sanitize_text_field( $all_controls['virtual_recipients'][ $key ] ) : ''; ?>
								<label>
									<?php echo esc_html( $label ); ?>
									<?php echo wc_help_tip( $recipient_tip, false ); ?>
								</label>
								<input type="text" name="b2bking_email_controls_settings[virtual_recipients][<?php echo esc_attr( $key ); ?>]" value="<?php echo esc_attr( $virtual_recipient ); ?>" placeholder="<?php echo esc_attr( get_option( 'admin_email' ) ); ?>">
							<?php endforeach; ?>
						<?php endif; ?>

						<label>
							<?php esc_html_e( 'Email Subject', 'b2bking' ); ?>
							<?php echo wc_help_tip( $subject_tip, false ); ?>
						</label>
						<input type="text" name="<?php echo esc_attr( $option_name ); ?>[subject_heading]" value="<?php echo esc_attr( $subject_heading ); ?>">

						<?php if ( ! empty( $email['audience_options'] ) ) : ?>
							<?php $current_audience = isset( $wc_settings['audience'] ) ? $wc_settings['audience'] : key( $email['audience_options'] ); ?>
							<label><?php esc_html_e( 'Send to', 'b2bking' ); ?></label>
							<select name="<?php echo esc_attr( $option_name ); ?>[audience]">
								<?php foreach ( $email['audience_options'] as $value => $label ) : ?>
									<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current_audience, $value ); ?>><?php echo esc_html( $label ); ?></option>
								<?php endforeach; ?>
							</select>
						<?php endif; ?>
					</div>

					<div class="b2bking_email_custom_box <?php echo $is_custom ? 'b2bking_email_custom_enabled' : ''; ?>">
							<div class="b2bking_email_custom_header">
								<div>
									<p class="b2bking_email_custom_status" data-default-label="<?php echo esc_attr__( 'Using default template', 'b2bking' ); ?>" data-custom-label="<?php echo esc_attr__( 'Using custom content', 'b2bking' ); ?>">
										<?php echo $is_custom ? esc_html__( 'Using custom content', 'b2bking' ) : esc_html__( 'Using default template', 'b2bking' ); ?>
									</p>
							</div>
							<div class="ui toggle checkbox">
								<input type="hidden" name="b2bking_email_controls_settings[<?php echo esc_attr( $email_id ); ?>][custom_enabled]" value="no">
								<input class="b2bking_email_custom_toggle" type="checkbox" name="b2bking_email_controls_settings[<?php echo esc_attr( $email_id ); ?>][custom_enabled]" value="yes" <?php checked( $is_custom ); ?>>
								<label><?php esc_html_e( 'Custom content', 'b2bking' ); ?></label>
							</div>
							</div>

							<div class="b2bking_email_default_preview">
								<div><?php echo wp_kses_post( wpautop( $preview_content ) ); ?></div>
								<p class="b2bking_email_default_preview_note"><?php esc_html_e( 'Template overrides may change the final email. Send a test email to confirm.', 'b2bking' ); ?></p>
							</div>

							<textarea class="b2bking_email_custom_content" name="b2bking_email_controls_settings[<?php echo esc_attr( $email_id ); ?>][custom_content]" rows="8" data-default-content="<?php echo esc_attr( $email['default_content'] ); ?>" <?php echo $is_custom ? '' : 'readonly="readonly"'; ?>><?php echo esc_textarea( $content ); ?></textarea>

						<div class="b2bking_email_custom_tools">
							<div class="b2bking_email_placeholders_intro">
								<?php esc_html_e( 'Available placeholders:', 'b2bking' ); ?>
							</div>
							<div class="b2bking_email_placeholders">
								<?php foreach ( $email['placeholders'] as $placeholder => $label ) : ?>
									<code title="<?php echo esc_attr( $label ); ?>">{<?php echo esc_html( $placeholder ); ?>}<span><?php echo esc_html( $label ); ?></span></code>
								<?php endforeach; ?>
							</div>
						</div>

							<div class="b2bking_email_actions">
								<button type="button" class="ui mini basic button b2bking_email_reset_default"><?php esc_html_e( 'Reset to default', 'b2bking' ); ?></button>
								<button type="button" class="ui mini basic button b2bking_email_send_test" data-email-id="<?php echo esc_attr( $email_id ); ?>"><?php esc_html_e( 'Send test email', 'b2bking' ); ?></button>
							</div>
						</div>

				</div>
			</div>
			<?php
		}
	}
}

if ( ! function_exists( 'b2bking_email_controls' ) ) {
	function b2bking_email_controls() {
		return B2bking_Email_Controls::init();
	}
}

b2bking_email_controls();
