<?php
/**
 * Cart Recovery — Settings helper
 *
 * Single source of truth for reading + sanitizing the module's admin
 * option (`OPT_CART_RECOVERY_SETTINGS`). Phase 6 admin UI renders the
 * form using the same keys and calls `sanitize()` before persisting.
 *
 * The settings schema is intentionally flat — nested keys are hard to
 * translate across `register_setting` + WordPress option save paths
 * without extra sanitize callbacks, so we keep one top-level map.
 *
 * Default values are resolved from constants so a plain install needs
 * zero admin interaction before the module is functional.
 *
 * @package Niwa_AI
 * @since   0.12.0
 */

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

class Niwa_AI_Cart_Recovery_Settings {

	public const CHANNEL_EMAIL    = 'email';
	public const CHANNEL_WHATSAPP = 'whatsapp';
	public const CHANNEL_BOTH     = 'both';

	/**
	 * Register the filter bridges that translate stored admin options
	 * into the `apply_filters(...)` values the Scheduler consumes. Must
	 * be called exactly once at plugin boot (before `tick()` ever fires)
	 * — otherwise the Scheduler falls back to the hard-coded constants
	 * and the admin's UI changes are silently ignored.
	 *
	 * Each filter only reads from `get_settings()`, which itself merges
	 * stored over defaults, so missing keys degrade cleanly.
	 */
	public static function register_hooks(): void {
		add_filter( 'niwa_ai_cart_recovery_mail1_delay_minutes',  array( __CLASS__, 'filter_mail1_delay_minutes' ),  10, 1 );
		add_filter( 'niwa_ai_cart_recovery_mail2_delay_hours',    array( __CLASS__, 'filter_mail2_delay_hours' ),    10, 1 );
		add_filter( 'niwa_ai_cart_recovery_inactivity_cap_hours', array( __CLASS__, 'filter_inactivity_cap_hours' ), 10, 1 );
		add_filter( 'niwa_ai_cart_recovery_cooldown_days',        array( __CLASS__, 'filter_cooldown_days' ),        10, 1 );
	}

	public static function filter_mail1_delay_minutes( $default ): int {
		$s     = self::get_settings();
		$value = isset( $s['mail1_delay_minutes'] ) ? (int) $s['mail1_delay_minutes'] : (int) $default;
		return max( 1, min( 720, $value ) );
	}

	public static function filter_mail2_delay_hours( $default ): int {
		$s     = self::get_settings();
		$value = isset( $s['mail2_delay_hours'] ) ? (int) $s['mail2_delay_hours'] : (int) $default;
		return max( 1, min( 168, $value ) );
	}

	public static function filter_inactivity_cap_hours( $default ): int {
		$s     = self::get_settings();
		$value = isset( $s['inactivity_cap_hours'] ) ? (int) $s['inactivity_cap_hours'] : (int) $default;
		return max( 1, min( 720, $value ) );
	}

	public static function filter_cooldown_days( $default ): int {
		$s     = self::get_settings();
		$value = isset( $s['cooldown_days'] ) ? (int) $s['cooldown_days'] : (int) $default;
		return max( 0, min( 365, $value ) );
	}

	/**
	 * Full flat schema with default values. Phase 6 admin UI reads this
	 * map to render the form; any missing key on read falls back to
	 * this table.
	 *
	 * @return array<string, mixed>
	 */
	public static function defaults(): array {
		return array(
			// Feature toggles.
			'enabled'                   => true,
			'enable_mail1'              => true,
			'enable_mail2'              => true,
			'delivery_channel'          => self::CHANNEL_EMAIL,

			// Drip timing (also exposed via filter hooks in Scheduler).
			'mail1_delay_minutes'       => Niwa_AI_Constants::CART_RECOVERY_MAIL1_DELAY_MIN,
			'mail2_delay_hours'         => Niwa_AI_Constants::CART_RECOVERY_MAIL2_DELAY_HOURS,
			'inactivity_cap_hours'      => Niwa_AI_Constants::CART_RECOVERY_INACTIVITY_CAP_H,
			'cooldown_days'             => Niwa_AI_Constants::CART_RECOVERY_COOLDOWN_DAYS,

			// Coupon.
			'coupon_enabled'            => true,
			'discount_type'             => Niwa_AI_Constants::CART_RECOVERY_COUPON_TYPE,
			'amount'                    => (float) Niwa_AI_Constants::CART_RECOVERY_COUPON_PERCENT,
			'ttl_hours'                 => Niwa_AI_Constants::CART_RECOVERY_COUPON_TTL_HOURS,
			'prefix'                    => Niwa_AI_Constants::CART_RECOVERY_COUPON_PREFIX,
			'restrict_to_cart_products' => false,
			'minimum_spend_mode'        => Niwa_AI_Cart_Recovery_Coupon_Config::MIN_SPEND_NONE,
			'exclude_sale_items'        => false,
			'individual_use'            => true,
			'free_shipping'             => false,

			// Sender.
			'from_name'                 => '',
			'from_email'                => '',
			'store_brand_name'          => '',

			// Per-stage content source: 'ai' (composer) or 'template' (admin/built-in text).
			'mail1_source'              => 'template',
			'mail1_subject_template'    => '',
			'mail1_html_template'       => '',
			'mail1_text_template'       => '',
			'mail2_source'              => 'template',
			'mail2_subject_template'    => '',
			'mail2_html_template'       => '',
			'mail2_text_template'       => '',

			// Unsubscribe.
			'unsubscribe_endpoint_slug' => 'niwa-ai/cart-recovery',
		);
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function get_settings(): array {
		$stored = function_exists( 'get_option' )
			? get_option( Niwa_AI_Constants::OPT_CART_RECOVERY_SETTINGS, array() )
			: array();

		if ( ! is_array( $stored ) ) {
			$stored = array();
		}

		return array_merge( self::defaults(), $stored );
	}

	public static function get_coupon_config(): Niwa_AI_Cart_Recovery_Coupon_Config {
		return Niwa_AI_Cart_Recovery_Coupon_Config::from_raw( self::get_settings() );
	}

	public static function is_enabled(): bool {
		$s = self::get_settings();
		return (bool) ( $s['enabled'] ?? true );
	}

	public static function is_coupon_enabled(): bool {
		$s = self::get_settings();
		return (bool) ( $s['enabled'] ?? true ) && (bool) ( $s['coupon_enabled'] ?? true );
	}

	public static function get_delivery_channel(): string {
		$settings = self::get_settings();
		$channel  = (string) ( $settings['delivery_channel'] ?? self::CHANNEL_EMAIL );

		return in_array( $channel, array( self::CHANNEL_EMAIL, self::CHANNEL_WHATSAPP, self::CHANNEL_BOTH ), true )
			? $channel
			: self::CHANNEL_EMAIL;
	}

	/**
	 * Return configured channels for which this recovery row has a usable target.
	 *
	 * @param array<string, mixed> $row Recovery row.
	 * @return string[]
	 */
	public static function delivery_channels_for_row( array $row ): array {
		$channels = array();
		$selected = self::get_delivery_channel();
		$email    = trim( (string) ( $row['email'] ?? '' ) );

		if ( in_array( $selected, array( self::CHANNEL_EMAIL, self::CHANNEL_BOTH ), true ) && self::is_valid_delivery_email( $email ) ) {
			$channels[] = self::CHANNEL_EMAIL;
		}

		$digits = class_exists( 'Niwa_AI_Phone_Normalizer' )
			? Niwa_AI_Phone_Normalizer::normalize( (string) ( $row['phone'] ?? '' ), (string) ( $row['country'] ?? '' ) )
			: '';
		if ( in_array( $selected, array( self::CHANNEL_WHATSAPP, self::CHANNEL_BOTH ), true ) && '' !== $digits ) {
			$channels[] = self::CHANNEL_WHATSAPP;
		}

		return $channels;
	}

	public static function is_stage_enabled( string $stage ): bool {
		$settings = self::get_settings();
		if ( empty( $settings['enabled'] ) ) {
			return false;
		}

		if ( 'mail1' === $stage ) {
			return ! empty( $settings['enable_mail1'] );
		}
		if ( 'mail2' === $stage ) {
			return ! empty( $settings['enable_mail2'] );
		}

		return false;
	}

	private static function is_valid_delivery_email( string $email ): bool {
		if ( '' === $email ) {
			return false;
		}

		return function_exists( 'is_email' )
			? (bool) is_email( $email )
			: (bool) filter_var( $email, FILTER_VALIDATE_EMAIL );
	}

	/**
	 * Sanitize an incoming settings array before persisting. Safe to
	 * register as the sanitize callback on `register_setting`.
	 *
	 * @param array<string, mixed> $input
	 * @return array<string, mixed>
	 */
	public static function sanitize( array $input ): array {
		$defaults = self::defaults();
		// Base the sanitized output on the CURRENT stored settings, not
		// on defaults. Otherwise saving a single tab would reset every
		// other tab's value to defaults (each tab renders its own form
		// that only submits its own fields). `get_settings()` already
		// merges stored over defaults so any missing key still has a
		// sane fallback.
		$out      = self::get_settings();

		// Toggles.
		foreach ( array( 'enabled', 'enable_mail1', 'enable_mail2', 'coupon_enabled', 'restrict_to_cart_products', 'exclude_sale_items', 'individual_use', 'free_shipping' ) as $toggle ) {
			if ( array_key_exists( $toggle, $input ) ) {
				$out[ $toggle ] = (bool) $input[ $toggle ];
			}
		}

		$delivery_channel = array_key_exists( 'delivery_channel', $input )
			? sanitize_key( (string) $input['delivery_channel'] )
			: (string) ( $out['delivery_channel'] ?? self::CHANNEL_EMAIL );
		$out['delivery_channel'] = in_array( $delivery_channel, array( self::CHANNEL_EMAIL, self::CHANNEL_WHATSAPP, self::CHANNEL_BOTH ), true )
			? $delivery_channel
			: self::CHANNEL_EMAIL;

		// Integer timing fields with safe floors.
		foreach ( array(
			'mail1_delay_minutes'  => array( 1, 720 ),
			'mail2_delay_hours'    => array( 1, 168 ),
			'inactivity_cap_hours' => array( 1, 720 ),
			'cooldown_days'        => array( 0, 365 ),
			'ttl_hours'            => array( 1, 24 * 30 ),
		) as $key => $bounds ) {
			if ( isset( $input[ $key ] ) ) {
				$out[ $key ] = max( $bounds[0], min( $bounds[1], (int) $input[ $key ] ) );
			}
		}

		// Enums.
		if ( isset( $input['discount_type'] ) ) {
			$candidate = (string) $input['discount_type'];
			if ( in_array(
				$candidate,
				array(
					Niwa_AI_Cart_Recovery_Coupon_Config::TYPE_PERCENT,
					Niwa_AI_Cart_Recovery_Coupon_Config::TYPE_FIXED_CART,
					Niwa_AI_Cart_Recovery_Coupon_Config::TYPE_FIXED_PRODUCT,
				),
				true
			) ) {
				$out['discount_type'] = $candidate;
			}
		}

		if ( isset( $input['minimum_spend_mode'] ) ) {
			$candidate = (string) $input['minimum_spend_mode'];
			if ( in_array(
				$candidate,
				array(
					Niwa_AI_Cart_Recovery_Coupon_Config::MIN_SPEND_NONE,
					Niwa_AI_Cart_Recovery_Coupon_Config::MIN_SPEND_CART_TOTAL,
				),
				true
			) ) {
				$out['minimum_spend_mode'] = $candidate;
			}
		}

		// Amount: clamp based on type.
		if ( isset( $input['amount'] ) ) {
			$amount = (float) $input['amount'];
			if ( Niwa_AI_Cart_Recovery_Coupon_Config::TYPE_PERCENT === $out['discount_type'] ) {
				$out['amount'] = max( 0.0, min( 100.0, $amount ) );
			} else {
				$out['amount'] = max( 0.0, $amount );
			}
		}

		// Strings.
		if ( isset( $input['prefix'] ) ) {
			$prefix = preg_replace( '/[^A-Za-z0-9_\-]/', '', (string) $input['prefix'] );
			$prefix = is_string( $prefix ) ? strtoupper( substr( $prefix, 0, 32 ) ) : '';
			$out['prefix'] = '' !== $prefix ? $prefix : $defaults['prefix'];
		}

		foreach ( array( 'from_name', 'store_brand_name', 'unsubscribe_endpoint_slug' ) as $str_key ) {
			if ( isset( $input[ $str_key ] ) ) {
				$out[ $str_key ] = function_exists( 'sanitize_text_field' )
					? sanitize_text_field( (string) $input[ $str_key ] )
					: substr( strip_tags( (string) $input[ $str_key ] ), 0, 191 );
			}
		}

		if ( isset( $input['from_email'] ) ) {
			$email = (string) $input['from_email'];
			if ( function_exists( 'is_email' ) && is_email( $email ) ) {
				$out['from_email'] = $email;
			} else {
				$out['from_email'] = filter_var( $email, FILTER_VALIDATE_EMAIL ) ? $email : '';
			}
		}

		// Per-stage source (enum: 'ai' | 'template') + template overrides.
		foreach ( array( 'mail1', 'mail2' ) as $stage ) {
			$src_key = $stage . '_source';
			if ( isset( $input[ $src_key ] ) ) {
				$candidate     = (string) $input[ $src_key ];
				$out[ $src_key ] = in_array( $candidate, array( 'ai', 'template' ), true ) ? $candidate : 'ai';
			}

			foreach ( array( 'subject_template', 'html_template', 'text_template' ) as $tpl_key ) {
				$key = $stage . '_' . $tpl_key;
				if ( isset( $input[ $key ] ) ) {
					$raw = (string) $input[ $key ];
					if ( 'html_template' === $tpl_key ) {
						// Admin-trusted HTML — use wp_kses_post when available so
						// we strip scripts but keep basic formatting tags.
						$out[ $key ] = function_exists( 'wp_kses_post' )
							? wp_kses_post( $raw )
							: strip_tags( $raw, '<p><br><strong><em><a><ul><ol><li><h1><h2><h3><img>' );
					} else {
						$out[ $key ] = function_exists( 'sanitize_textarea_field' )
							? sanitize_textarea_field( $raw )
							: trim( strip_tags( $raw ) );
					}
				}
			}
		}

		return $out;
	}

	/**
	 * Whether the admin has elected to override the AI composer for a
	 * specific stage. Used by the composer to decide path.
	 */
	public static function is_template_mode_for_stage( string $stage ): bool {
		$settings = self::get_settings();
		$key      = $stage . '_source';
		return 'template' === ( $settings[ $key ] ?? 'ai' );
	}

	/**
	 * Return the admin-authored template triplet for a stage. Values
	 * may be empty strings — caller decides how to handle that (fall
	 * back to AI / fallback template).
	 *
	 * @return array{subject: string, html: string, text: string}
	 */
	public static function get_stage_template( string $stage ): array {
		$settings = self::get_settings();
		return array(
			'subject' => (string) ( $settings[ $stage . '_subject_template' ] ?? '' ),
			'html'    => (string) ( $settings[ $stage . '_html_template' ] ?? '' ),
			'text'    => (string) ( $settings[ $stage . '_text_template' ] ?? '' ),
		);
	}

	/**
	 * Return an admin-authored template when it is complete, otherwise
	 * the locale-aware built-in default for that stage. The selection is
	 * based on locale codes, never on words inside the visitor message.
	 *
	 * @return array{subject: string, html: string, text: string}
	 */
	public static function get_stage_template_for_locale( string $stage, string $locale ): array {
		$template = self::get_stage_template( $stage );
		if ( '' !== trim( $template['subject'] ) && ( '' !== trim( $template['html'] ) || '' !== trim( $template['text'] ) ) ) {
			return $template;
		}

		return self::get_default_stage_template( $stage, $locale );
	}

	/**
	 * @return array{subject: string, html: string, text: string}
	 */
	public static function get_default_stage_template( string $stage, string $locale ): array {
		$lang      = self::normalize_template_language( $locale );
		$templates = self::default_stage_templates();
		if ( ! isset( $templates[ $lang ] ) ) {
			$lang = 'en';
		}

		$stage = Niwa_AI_Cart_Recovery_Composition_Context::STAGE_MAIL2 === $stage
			? Niwa_AI_Cart_Recovery_Composition_Context::STAGE_MAIL2
			: Niwa_AI_Cart_Recovery_Composition_Context::STAGE_MAIL1;

		return $templates[ $lang ][ $stage ];
	}

	private static function normalize_template_language( string $locale ): string {
		$locale = strtolower( trim( str_replace( '-', '_', $locale ) ) );
		$parts  = preg_split( '/_+/', $locale );
		$lang   = isset( $parts[0] ) ? preg_replace( '/[^a-z]/', '', (string) $parts[0] ) : '';
		if ( 'bs' === $lang ) {
			$lang = 'sr';
		}
		return in_array( $lang, array( 'en', 'sr', 'hr', 'de', 'es', 'fr' ), true ) ? $lang : 'en';
	}

	/**
	 * @return array<string, array<string, array{subject: string, html: string, text: string}>>
	 */
	private static function default_stage_templates(): array {
		return array(
			'en' => array(
				'mail1' => array(
					'subject' => 'Your cart is still saved',
					'html'    => '<p>Hi {customer_name},</p><p>Niwa AI here, writing from {store_brand}.</p><p>I noticed you were choosing a few things from our shop, and then something probably pulled you away.</p><p>Good news. Your cart is still here, exactly as you left it.</p>{cart_items_html}<p>When you have a minute, you can come back and continue from where you stopped:</p><p><a href="{cart_recovery_url}"><strong>Return to my cart</strong></a></p><p>If you have any questions about size, delivery, payment, or anything else, just reply to this message.</p><p>I am here to help.</p><p>Best,<br>Niwa AI<br>assistant at {store_brand}</p>',
					'text'    => "Hi {customer_name},\n\nNiwa AI here, writing from {store_brand}.\n\nI noticed you were choosing a few things from our shop, and then something probably pulled you away.\n\nGood news. Your cart is still here, exactly as you left it.\n\n{cart_items}\n\nWhen you have a minute, you can come back and continue from where you stopped:\n{cart_recovery_url}\n\nIf you have any questions about size, delivery, payment, or anything else, just reply to this message.\n\nI am here to help.\n\nBest,\nNiwa AI\nassistant at {store_brand}",
				),
				'mail2' => array(
					'subject' => 'Your cart is still here, and I added {coupon_discount} off',
					'html'    => '<p>Hi {customer_name},</p><p>Niwa AI here again from {store_brand}.</p><p>Your cart is still waiting for you, so I added a little thank you gift:</p><p><strong>{coupon_discount} off with code {coupon_code}</strong></p>{cart_items_html}<p>You can use this code at checkout during the next {coupon_ttl_hours} hours.</p><p>After that, the code will no longer be available.</p><p>Click below to return to your cart and use your discount:</p><p><a href="{cart_recovery_url}"><strong>Return to my cart</strong></a></p><p>If you have any questions before ordering, just reply to this message.</p><p>Best,<br>Niwa AI<br>assistant at {store_brand}</p>',
					'text'    => "Hi {customer_name},\n\nNiwa AI here again from {store_brand}.\n\nYour cart is still waiting for you, so I added a little thank you gift:\n{coupon_discount} off with code {coupon_code}\n\n{cart_items}\n\nYou can use this code at checkout during the next {coupon_ttl_hours} hours.\n\nAfter that, the code will no longer be available.\n\nClick below to return to your cart and use your discount:\n{cart_recovery_url}\n\nIf you have any questions before ordering, just reply to this message.\n\nBest,\nNiwa AI\nassistant at {store_brand}",
				),
			),
			'sr' => array(
				'mail1' => array(
					'subject' => 'Vaša korpa je i dalje sačuvana',
					'html'    => '<p>Pozdrav {customer_name},</p><p>Niwa AI ovde, javljam vam se sa sajta {store_brand}.</p><p>Videla sam da ste birali neke stvari kod nas, a onda vas je nešto verovatno prekinulo.</p><p>Dobra vest je da je vaša korpa i dalje tu, tačno onako kako ste je ostavili.</p>{cart_items_html}<p>Kad budete imali minut, možete se vratiti i nastaviti odakle ste stali:</p><p><a href="{cart_recovery_url}"><strong>Vrati me u korpu</strong></a></p><p>Ako imate neku nedoumicu oko veličine, dostave, plaćanja ili bilo čega drugog, slobodno odgovorite na ovu poruku.</p><p>Tu sam da pomognem.</p><p>Pozdrav,<br>Niwa AI<br>asistentkinja na {store_brand}</p>',
					'text'    => "Pozdrav {customer_name},\n\nNiwa AI ovde, javljam vam se sa sajta {store_brand}.\n\nVidela sam da ste birali neke stvari kod nas, a onda vas je nešto verovatno prekinulo.\n\nDobra vest je da je vaša korpa i dalje tu, tačno onako kako ste je ostavili.\n\n{cart_items}\n\nKad budete imali minut, možete se vratiti i nastaviti odakle ste stali:\n{cart_recovery_url}\n\nAko imate neku nedoumicu oko veličine, dostave, plaćanja ili bilo čega drugog, slobodno odgovorite na ovu poruku.\n\nTu sam da pomognem.\n\nPozdrav,\nNiwa AI\nasistentkinja na {store_brand}",
				),
				'mail2' => array(
					'subject' => 'Vaša korpa vas čeka, uz {coupon_discount} popusta',
					'html'    => '<p>Pozdrav {customer_name},</p><p>Niwa AI ponovo ovde iz {store_brand}.</p><p>Vaša korpa je i dalje tu, pa sam vam dodala mali znak pažnje:</p><p><strong>{coupon_discount} popusta uz kod {coupon_code}</strong></p>{cart_items_html}<p>Kod možete iskoristiti na stranici za plaćanje u narednih {coupon_ttl_hours} sati.</p><p>Nakon toga, kod više neće biti dostupan.</p><p>Kliknite ispod da se vratite u korpu i iskoristite popust:</p><p><a href="{cart_recovery_url}"><strong>Vrati me u korpu</strong></a></p><p>Ako imate pitanje pre kupovine, samo odgovorite na ovu poruku.</p><p>Pozdrav,<br>Niwa AI<br>asistentkinja na {store_brand}</p>',
					'text'    => "Pozdrav {customer_name},\n\nNiwa AI ponovo ovde iz {store_brand}.\n\nVaša korpa je i dalje tu, pa sam vam dodala mali znak pažnje:\n{coupon_discount} popusta uz kod {coupon_code}\n\n{cart_items}\n\nKod možete iskoristiti na stranici za plaćanje u narednih {coupon_ttl_hours} sati.\n\nNakon toga, kod više neće biti dostupan.\n\nKliknite ispod da se vratite u korpu i iskoristite popust:\n{cart_recovery_url}\n\nAko imate pitanje pre kupovine, samo odgovorite na ovu poruku.\n\nPozdrav,\nNiwa AI\nasistentkinja na {store_brand}",
				),
			),
			'hr' => array(
				'mail1' => array(
					'subject' => 'Vaša košarica je još uvijek sačuvana',
					'html'    => '<p>Pozdrav {customer_name},</p><p>Niwa AI ovdje, javljam vam se sa stranice {store_brand}.</p><p>Vidjela sam da ste birali neke stvari kod nas, a onda vas je nešto vjerojatno prekinulo.</p><p>Dobra vijest je da je vaša košarica još uvijek tu, točno onako kako ste je ostavili.</p>{cart_items_html}<p>Kad budete imali minutu, možete se vratiti i nastaviti odakle ste stali:</p><p><a href="{cart_recovery_url}"><strong>Vrati me u košaricu</strong></a></p><p>Ako imate neku nedoumicu oko veličine, dostave, plaćanja ili bilo čega drugog, slobodno odgovorite na ovu poruku.</p><p>Tu sam da pomognem.</p><p>Lijep pozdrav,<br>Niwa AI<br>asistentica na {store_brand}</p>',
					'text'    => "Pozdrav {customer_name},\n\nNiwa AI ovdje, javljam vam se sa stranice {store_brand}.\n\nVidjela sam da ste birali neke stvari kod nas, a onda vas je nešto vjerojatno prekinulo.\n\nDobra vijest je da je vaša košarica još uvijek tu, točno onako kako ste je ostavili.\n\n{cart_items}\n\nKad budete imali minutu, možete se vratiti i nastaviti odakle ste stali:\n{cart_recovery_url}\n\nAko imate neku nedoumicu oko veličine, dostave, plaćanja ili bilo čega drugog, slobodno odgovorite na ovu poruku.\n\nTu sam da pomognem.\n\nLijep pozdrav,\nNiwa AI\nasistentica na {store_brand}",
				),
				'mail2' => array(
					'subject' => 'Vaša košarica vas čeka, uz {coupon_discount} popusta',
					'html'    => '<p>Pozdrav {customer_name},</p><p>Niwa AI ponovno ovdje iz {store_brand}.</p><p>Vaša košarica je još uvijek tu, pa sam vam dodala mali znak pažnje:</p><p><strong>{coupon_discount} popusta uz kod {coupon_code}</strong></p>{cart_items_html}<p>Kod možete iskoristiti na blagajni tijekom sljedećih {coupon_ttl_hours} sati.</p><p>Nakon toga, kod više neće biti dostupan.</p><p>Kliknite ispod da se vratite u košaricu i iskoristite popust:</p><p><a href="{cart_recovery_url}"><strong>Vrati me u košaricu</strong></a></p><p>Ako imate pitanje prije kupnje, samo odgovorite na ovu poruku.</p><p>Lijep pozdrav,<br>Niwa AI<br>asistentica na {store_brand}</p>',
					'text'    => "Pozdrav {customer_name},\n\nNiwa AI ponovno ovdje iz {store_brand}.\n\nVaša košarica je još uvijek tu, pa sam vam dodala mali znak pažnje:\n{coupon_discount} popusta uz kod {coupon_code}\n\n{cart_items}\n\nKod možete iskoristiti na blagajni tijekom sljedećih {coupon_ttl_hours} sati.\n\nNakon toga, kod više neće biti dostupan.\n\nKliknite ispod da se vratite u košaricu i iskoristite popust:\n{cart_recovery_url}\n\nAko imate pitanje prije kupnje, samo odgovorite na ovu poruku.\n\nLijep pozdrav,\nNiwa AI\nasistentica na {store_brand}",
				),
			),
			'de' => array(
				'mail1' => array(
					'subject' => 'Ihr Warenkorb ist noch gespeichert',
					'html'    => '<p>Hallo {customer_name},</p><p>Niwa AI hier, ich schreibe Ihnen von {store_brand}.</p><p>Ich habe gesehen, dass Sie einige Artikel ausgewählt haben. Dann ist vermutlich etwas dazwischengekommen.</p><p>Die gute Nachricht: Ihr Warenkorb ist noch da, genau so, wie Sie ihn verlassen haben.</p>{cart_items_html}<p>Wenn Sie einen Moment Zeit haben, können Sie zurückkehren und dort weitermachen, wo Sie aufgehört haben:</p><p><a href="{cart_recovery_url}"><strong>Zurück zu meinem Warenkorb</strong></a></p><p>Falls Sie eine Frage zu Größe, Lieferung, Zahlung oder etwas anderem haben, antworten Sie einfach auf diese Nachricht.</p><p>Ich helfe Ihnen gern.</p><p>Viele Grüße,<br>Niwa AI<br>Assistentin bei {store_brand}</p>',
					'text'    => "Hallo {customer_name},\n\nNiwa AI hier, ich schreibe Ihnen von {store_brand}.\n\nIch habe gesehen, dass Sie einige Artikel ausgewählt haben. Dann ist vermutlich etwas dazwischengekommen.\n\nDie gute Nachricht: Ihr Warenkorb ist noch da, genau so, wie Sie ihn verlassen haben.\n\n{cart_items}\n\nWenn Sie einen Moment Zeit haben, können Sie zurückkehren und dort weitermachen, wo Sie aufgehört haben:\n{cart_recovery_url}\n\nFalls Sie eine Frage zu Größe, Lieferung, Zahlung oder etwas anderem haben, antworten Sie einfach auf diese Nachricht.\n\nIch helfe Ihnen gern.\n\nViele Grüße,\nNiwa AI\nAssistentin bei {store_brand}",
				),
				'mail2' => array(
					'subject' => 'Ihr Warenkorb wartet noch, mit {coupon_discount} Rabatt',
					'html'    => '<p>Hallo {customer_name},</p><p>Niwa AI hier noch einmal von {store_brand}.</p><p>Ihr Warenkorb ist noch da, deshalb habe ich ein kleines Dankeschön für Sie hinzugefügt:</p><p><strong>{coupon_discount} Rabatt mit dem Code {coupon_code}</strong></p>{cart_items_html}<p>Sie können den Code innerhalb der nächsten {coupon_ttl_hours} Stunden an der Kasse verwenden.</p><p>Danach ist der Code nicht mehr verfügbar.</p><p>Klicken Sie unten, um zu Ihrem Warenkorb zurückzukehren und den Rabatt zu nutzen:</p><p><a href="{cart_recovery_url}"><strong>Zurück zu meinem Warenkorb</strong></a></p><p>Falls Sie vor der Bestellung eine Frage haben, antworten Sie einfach auf diese Nachricht.</p><p>Viele Grüße,<br>Niwa AI<br>Assistentin bei {store_brand}</p>',
					'text'    => "Hallo {customer_name},\n\nNiwa AI hier noch einmal von {store_brand}.\n\nIhr Warenkorb ist noch da, deshalb habe ich ein kleines Dankeschön für Sie hinzugefügt:\n{coupon_discount} Rabatt mit dem Code {coupon_code}\n\n{cart_items}\n\nSie können den Code innerhalb der nächsten {coupon_ttl_hours} Stunden an der Kasse verwenden.\n\nDanach ist der Code nicht mehr verfügbar.\n\nKlicken Sie unten, um zu Ihrem Warenkorb zurückzukehren und den Rabatt zu nutzen:\n{cart_recovery_url}\n\nFalls Sie vor der Bestellung eine Frage haben, antworten Sie einfach auf diese Nachricht.\n\nViele Grüße,\nNiwa AI\nAssistentin bei {store_brand}",
				),
			),
			'es' => array(
				'mail1' => array(
					'subject' => 'Tu carrito sigue guardado',
					'html'    => '<p>Hola {customer_name},</p><p>Soy Niwa AI, te escribo desde {store_brand}.</p><p>Vi que estabas eligiendo algunos productos en nuestra tienda, y luego probablemente algo te interrumpió.</p><p>La buena noticia es que tu carrito sigue aquí, exactamente como lo dejaste.</p>{cart_items_html}<p>Cuando tengas un minuto, puedes volver y continuar desde donde lo dejaste:</p><p><a href="{cart_recovery_url}"><strong>Volver a mi carrito</strong></a></p><p>Si tienes alguna duda sobre talla, envío, pago o cualquier otra cosa, puedes responder a este mensaje.</p><p>Estoy aquí para ayudarte.</p><p>Un saludo,<br>Niwa AI<br>asistente en {store_brand}</p>',
					'text'    => "Hola {customer_name},\n\nSoy Niwa AI, te escribo desde {store_brand}.\n\nVi que estabas eligiendo algunos productos en nuestra tienda, y luego probablemente algo te interrumpió.\n\nLa buena noticia es que tu carrito sigue aquí, exactamente como lo dejaste.\n\n{cart_items}\n\nCuando tengas un minuto, puedes volver y continuar desde donde lo dejaste:\n{cart_recovery_url}\n\nSi tienes alguna duda sobre talla, envío, pago o cualquier otra cosa, puedes responder a este mensaje.\n\nEstoy aquí para ayudarte.\n\nUn saludo,\nNiwa AI\nasistente en {store_brand}",
				),
				'mail2' => array(
					'subject' => 'Tu carrito te espera, con {coupon_discount} de descuento',
					'html'    => '<p>Hola {customer_name},</p><p>Soy Niwa AI de nuevo, desde {store_brand}.</p><p>Tu carrito sigue aquí, así que he añadido un pequeño detalle para ti:</p><p><strong>{coupon_discount} de descuento con el código {coupon_code}</strong></p>{cart_items_html}<p>Puedes usar el código al finalizar la compra durante las próximas {coupon_ttl_hours} horas.</p><p>Después de eso, el código ya no estará disponible.</p><p>Haz clic abajo para volver a tu carrito y usar tu descuento:</p><p><a href="{cart_recovery_url}"><strong>Volver a mi carrito</strong></a></p><p>Si tienes alguna pregunta antes de comprar, solo responde a este mensaje.</p><p>Un saludo,<br>Niwa AI<br>asistente en {store_brand}</p>',
					'text'    => "Hola {customer_name},\n\nSoy Niwa AI de nuevo, desde {store_brand}.\n\nTu carrito sigue aquí, así que he añadido un pequeño detalle para ti:\n{coupon_discount} de descuento con el código {coupon_code}\n\n{cart_items}\n\nPuedes usar el código al finalizar la compra durante las próximas {coupon_ttl_hours} horas.\n\nDespués de eso, el código ya no estará disponible.\n\nHaz clic abajo para volver a tu carrito y usar tu descuento:\n{cart_recovery_url}\n\nSi tienes alguna pregunta antes de comprar, solo responde a este mensaje.\n\nUn saludo,\nNiwa AI\nasistente en {store_brand}",
				),
			),
			'fr' => array(
				'mail1' => array(
					'subject' => 'Votre panier est toujours enregistré',
					'html'    => '<p>Bonjour {customer_name},</p><p>Niwa AI ici, je vous écris depuis {store_brand}.</p><p>J’ai vu que vous aviez choisi quelques articles chez nous, puis quelque chose vous a probablement interrompu.</p><p>Bonne nouvelle : votre panier est toujours là, exactement comme vous l’avez laissé.</p>{cart_items_html}<p>Quand vous avez une minute, vous pouvez revenir et reprendre là où vous vous êtes arrêté :</p><p><a href="{cart_recovery_url}"><strong>Retourner à mon panier</strong></a></p><p>Si vous avez une question sur la taille, la livraison, le paiement ou autre chose, répondez simplement à ce message.</p><p>Je suis là pour vous aider.</p><p>Bien à vous,<br>Niwa AI<br>assistante chez {store_brand}</p>',
					'text'    => "Bonjour {customer_name},\n\nNiwa AI ici, je vous écris depuis {store_brand}.\n\nJ’ai vu que vous aviez choisi quelques articles chez nous, puis quelque chose vous a probablement interrompu.\n\nBonne nouvelle : votre panier est toujours là, exactement comme vous l’avez laissé.\n\n{cart_items}\n\nQuand vous avez une minute, vous pouvez revenir et reprendre là où vous vous êtes arrêté :\n{cart_recovery_url}\n\nSi vous avez une question sur la taille, la livraison, le paiement ou autre chose, répondez simplement à ce message.\n\nJe suis là pour vous aider.\n\nBien à vous,\nNiwa AI\nassistante chez {store_brand}",
				),
				'mail2' => array(
					'subject' => 'Votre panier vous attend, avec {coupon_discount} de réduction',
					'html'    => '<p>Bonjour {customer_name},</p><p>Niwa AI de nouveau, depuis {store_brand}.</p><p>Votre panier est toujours là, alors j’ai ajouté un petit geste pour vous :</p><p><strong>{coupon_discount} de réduction avec le code {coupon_code}</strong></p>{cart_items_html}<p>Vous pouvez utiliser ce code au moment du paiement pendant les prochaines {coupon_ttl_hours} heures.</p><p>Après cela, le code ne sera plus disponible.</p><p>Cliquez ci-dessous pour revenir à votre panier et utiliser votre réduction :</p><p><a href="{cart_recovery_url}"><strong>Retourner à mon panier</strong></a></p><p>Si vous avez une question avant de commander, répondez simplement à ce message.</p><p>Bien à vous,<br>Niwa AI<br>assistante chez {store_brand}</p>',
					'text'    => "Bonjour {customer_name},\n\nNiwa AI de nouveau, depuis {store_brand}.\n\nVotre panier est toujours là, alors j’ai ajouté un petit geste pour vous :\n{coupon_discount} de réduction avec le code {coupon_code}\n\n{cart_items}\n\nVous pouvez utiliser ce code au moment du paiement pendant les prochaines {coupon_ttl_hours} heures.\n\nAprès cela, le code ne sera plus disponible.\n\nCliquez ci-dessous pour revenir à votre panier et utiliser votre réduction :\n{cart_recovery_url}\n\nSi vous avez une question avant de commander, répondez simplement à ce message.\n\nBien à vous,\nNiwa AI\nassistante chez {store_brand}",
				),
			),
		);
	}
}
