<?php
/**
 * File: Ecre_Coupon_Sync_Handler.php
 *
 * Handles automatic synchronization of coupon data between WooCommerce's native
 * coupon system and Echo Rewards custom database tables when referral or reward
 * coupons are manually edited through the WordPress admin interface.
 *
 * This class intercepts the save_post_shop_coupon hook to detect coupon edits,
 * identifies whether the coupon is a referral or reward coupon, and updates
 * the corresponding custom tables to maintain data consistency.
 *
 * @package ECRE
 * @since   1.0.0
 */

namespace ECRE;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'ECRE\Ecre_Coupon_Sync_Handler' ) ) {
	/**
	 * Handles synchronization of coupon data to custom database tables.
	 *
	 * This class ensures that when referral or reward coupons are manually edited
	 * in WooCommerce, the changes are automatically reflected in Echo Rewards'
	 * custom database tables (ecre_referrers, ecre_referrals_orders,
	 * ecre_reward_coupons, ecre_rewards_orders).
	 *
	 * @since 1.0.0
	 */
	class Ecre_Coupon_Sync_Handler {

		/**
		 * Constructor.
		 *
		 * Registers WordPress hooks for coupon synchronization.
		 *
		 * @since 1.0.0
		 */
		public function __construct() {
			// Hook into WooCommerce coupon update action (fires AFTER meta is saved).
			add_action( 'woocommerce_update_coupon', array( $this, 'sync_coupon_on_wc_update' ), 10, 1 );

			// Also hook into coupon creation for new coupons.
			add_action( 'woocommerce_new_coupon', array( $this, 'sync_coupon_on_wc_update' ), 10, 1 );
		}

		/**
		 * Main entry point for coupon synchronization (WooCommerce hook).
		 *
		 * Triggered by woocommerce_update_coupon or woocommerce_new_coupon hooks.
		 * These hooks fire AFTER WooCommerce saves the coupon meta data.
		 *
		 * @since 1.0.0
		 *
		 * @param int $coupon_id Coupon post ID.
		 *
		 * @return void
		 */
		public function sync_coupon_on_wc_update( $coupon_id ) {
			try {
				// Identify coupon type (referral, reward, or none).
				$coupon_type_info = $this->identify_coupon_type( $coupon_id );

				// Skip if this is not a referral or reward coupon.
				if ( 'none' === $coupon_type_info['type'] ) {
					return;
				}

				// Extract current coupon data (NOW it will have the latest values).
				$coupon_data = $this->extract_coupon_data( $coupon_id );

				// Sync based on coupon type.
				if ( 'referral' === $coupon_type_info['type'] ) {
					$this->sync_referral_coupon( $coupon_id, $coupon_data, $coupon_type_info['user_id'] );
				} elseif ( 'reward' === $coupon_type_info['type'] ) {
					$this->sync_reward_coupon( $coupon_id, $coupon_data, $coupon_type_info['user_id'] );
				}
			} catch ( Exception $e ) {
				// Silently fail - don't prevent coupon save.
			}
		}

		/**
		 * Main entry point for coupon synchronization (WordPress hook - DEPRECATED).
		 *
		 * Triggered when a shop_coupon post is saved. Identifies the coupon type
		 * (referral/reward) and orchestrates the synchronization process.
		 *
		 * @since 1.0.0
		 * @deprecated Use sync_coupon_on_wc_update() instead
		 *
		 * @param int     $post_id Post ID of the coupon being saved.
		 * @param WP_Post $post    Post object of the coupon.
		 * @param bool    $update  Whether this is an existing post being updated.
		 *
		 * @return void
		 */
		public function sync_coupon_on_save( $post_id, $post, $update ) {
			// Skip if this is an autosave.
			if ( wp_is_post_autosave( $post_id ) ) {
				return;
			}

			// Skip if this is a revision.
			if ( wp_is_post_revision( $post_id ) ) {
				return;
			}

			// Only proceed for updates, not new posts.
			if ( ! $update ) {
				return;
			}

			try {
				// Identify coupon type (referral, reward, or none).
				$coupon_type_info = $this->identify_coupon_type( $post_id );

				// Skip if this is not a referral or reward coupon.
				if ( 'none' === $coupon_type_info['type'] ) {
					return;
				}

				// Extract current coupon data.
				$coupon_data = $this->extract_coupon_data( $post_id );

				// Sync based on coupon type.
				if ( 'referral' === $coupon_type_info['type'] ) {
					$this->sync_referral_coupon( $post_id, $coupon_data, $coupon_type_info['user_id'] );
				} elseif ( 'reward' === $coupon_type_info['type'] ) {
					$this->sync_reward_coupon( $post_id, $coupon_data, $coupon_type_info['user_id'] );
				}
			} catch ( Exception $e ) {
				// Silently fail - don't prevent coupon save.
			}
		}

		/**
		 * Identifies whether a coupon is a referral, reward, or regular coupon.
		 *
		 * Checks post meta for referral_user_id or reward_user_id to determine
		 * the coupon type.
		 *
		 * @since 1.0.0
		 *
		 * @param int $coupon_id Coupon post ID.
		 *
		 * @return array {
		 *     Coupon type information.
		 *
		 *     @type string   $type    Coupon type: 'referral', 'reward', or 'none'.
		 *     @type int|null $user_id Associated user ID, or null if not applicable.
		 * }
		 */
		private function identify_coupon_type( $coupon_id ) {
			// Check for referral coupon meta.
			$referral_user_id = get_post_meta( $coupon_id, 'referral_user_id', true );

			if ( ! empty( $referral_user_id ) && is_numeric( $referral_user_id ) ) {
				return array(
					'type'    => 'referral',
					'user_id' => absint( $referral_user_id ),
				);
			}

			// Check for reward coupon meta.
			$reward_user_id = get_post_meta( $coupon_id, 'reward_user_id', true );

			if ( ! empty( $reward_user_id ) && is_numeric( $reward_user_id ) ) {
				return array(
					'type'    => 'reward',
					'user_id' => absint( $reward_user_id ),
				);
			}

			// Not a referral or reward coupon.
			return array(
				'type'    => 'none',
				'user_id' => null,
			);
		}

		/**
		 * Extracts all relevant coupon data from WooCommerce coupon object.
		 *
		 * Retrieves coupon properties including discount details, restrictions,
		 * and usage information.
		 *
		 * @since 1.0.0
		 *
		 * @param int $coupon_id Coupon post ID.
		 *
		 * @return array Associative array of coupon properties.
		 */
		private function extract_coupon_data( $coupon_id ) {
			// Create WooCommerce coupon object.
			$coupon = new \WC_Coupon( $coupon_id );

			// Check if coupon exists.
			if ( ! $coupon || ! $coupon->get_id() ) {
				return array();
			}

			// Extract and sanitize coupon data.
			$coupon_data = array(
				'coupon_code'         => sanitize_text_field( $coupon->get_code() ),
				'discount_type'       => sanitize_text_field( $coupon->get_discount_type() ),
				'discount_amount'     => floatval( $coupon->get_amount() ),
				'usage_limit'         => absint( $coupon->get_usage_limit() ),
				'usage_count'         => absint( $coupon->get_usage_count() ),
				'status'              => $this->determine_coupon_status( $coupon ),
				'expiry_date'         => null,
				'product_ids'         => array(),
				'exclude_product_ids' => array(),
				'product_categories'  => array(),
				'exclude_categories'  => array(),
			);

			// Get expiry date if set.
			$date_expires = $coupon->get_date_expires();
			if ( $date_expires ) {
				$coupon_data['expiry_date'] = $date_expires->date( 'Y-m-d H:i:s' );
			}

			// Get product restrictions.
			$product_ids = $coupon->get_product_ids();
			if ( is_array( $product_ids ) && ! empty( $product_ids ) ) {
				$coupon_data['product_ids'] = array_map( 'absint', $product_ids );
			}

			// Get excluded products.
			$excluded_product_ids = $coupon->get_excluded_product_ids();
			if ( is_array( $excluded_product_ids ) && ! empty( $excluded_product_ids ) ) {
				$coupon_data['exclude_product_ids'] = array_map( 'absint', $excluded_product_ids );
			}

			// Get category restrictions.
			$product_categories = $coupon->get_product_categories();
			if ( is_array( $product_categories ) && ! empty( $product_categories ) ) {
				$coupon_data['product_categories'] = array_map( 'absint', $product_categories );
			}

			// Get excluded categories.
			$excluded_categories = $coupon->get_excluded_product_categories();
			if ( is_array( $excluded_categories ) && ! empty( $excluded_categories ) ) {
				$coupon_data['exclude_categories'] = array_map( 'absint', $excluded_categories );
			}

			return $coupon_data;
		}

		/**
		 * Determines the appropriate status for a coupon.
		 *
		 * Maps WooCommerce coupon status and expiry date to Echo Rewards status values:
		 * - 'draft' for draft coupons
		 * - 'pending' for pending review coupons
		 * - 'expired' for published but expired coupons
		 * - 'available' for published and active coupons
		 *
		 * @since 1.0.0
		 *
		 * @param WC_Coupon $coupon WooCommerce coupon object.
		 *
		 * @return string Coupon status: 'draft', 'pending', 'expired', or 'available'.
		 */
		private function determine_coupon_status( $coupon ) {
			$wc_status = $coupon->get_status();

			// Handle draft status.
			if ( 'draft' === $wc_status ) {
				return 'draft';
			}

			// Handle pending review status.
			if ( 'pending' === $wc_status ) {
				return 'pending';
			}

			// For published coupons, check if expired.
			if ( 'publish' === $wc_status ) {
				$date_expires = $coupon->get_date_expires();
				
				// Check if coupon has expired.
				if ( $date_expires && $date_expires->getTimestamp() < time() ) {
					return 'expired';
				}

				// Published and not expired.
				return 'available';
			}

			// Default to inactive for any other status.
			return 'inactive';
		}

		/**
		 * Orchestrates synchronization for referral coupons.
		 *
		 * Updates ecre_referrers and ecre_referrals_orders tables with current
		 * coupon data.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 * @param int   $user_id     Referral user ID.
		 *
		 * @return bool True on success, false on failure.
		 */
		private function sync_referral_coupon( $coupon_id, $coupon_data, $user_id ) {
			$success = true;

			try {
				// Update ecre_referrers table.
				$referrers_updated = $this->update_referrers_table( $coupon_id, $coupon_data );

				if ( ! $referrers_updated ) {
					$success = false;
				}

				// Update ecre_referrals_orders table.
				$orders_updated = $this->update_referrals_orders_table( $coupon_id, $coupon_data );

				if ( ! $orders_updated ) {
					$success = false;
				}
			} catch ( Exception $e ) {
				$success = false;
			}

			return $success;
		}

		/**
		 * Orchestrates synchronization for reward coupons.
		 *
		 * Updates ecre_reward_coupons and ecre_rewards_orders tables with current
		 * coupon data.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 * @param int   $user_id     Reward user ID.
		 *
		 * @return bool True on success, false on failure.
		 */
		private function sync_reward_coupon( $coupon_id, $coupon_data, $user_id ) {
			$success = true;

			try {
				// Update ecre_reward_coupons table.
				$coupons_updated = $this->update_reward_coupons_table( $coupon_id, $coupon_data );

				if ( ! $coupons_updated ) {
					$success = false;
				}

				// Update ecre_rewards_orders table.
				$orders_updated = $this->update_rewards_orders_table( $coupon_id, $coupon_data );

				if ( ! $orders_updated ) {
					$success = false;
				}
			} catch ( Exception $e ) {
				$success = false;
			}

			return $success;
		}

		/**
		 * Updates the ecre_referrers table with current coupon data.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 *
		 * @return bool True on success, false on failure.
		 */
		private function update_referrers_table( $coupon_id, $coupon_data ) {
			global $wpdb;

			$table_name = $wpdb->prefix . 'ecre_referrers';

			// Check if table exists.
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$wpdb->esc_like( $table_name )
				)
			);

			if ( $table_exists !== $table_name ) {
				return false;
			}

			// Update the referrers table and mark as custom.
			$result = $wpdb->update(
				$table_name,
				array(
					'referral_coupon_code' => sanitize_text_field( $coupon_data['coupon_code'] ),
					'custom_referrals'     => 1,
					'updated_at'           => current_time( 'mysql' ),
				),
				array(
					'referral_coupon_id' => absint( $coupon_id ),
				),
				array( '%s', '%d', '%s' ),
				array( '%d' )
			);

			// Check for database errors.
			if ( false === $result ) {
				return false;
			}

			// Get the user_id from the referrers table to save custom settings.
			$referrer = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT user_id FROM `{$wpdb->prefix}ecre_referrers` WHERE referral_coupon_id = %d",
					absint( $coupon_id )
				)
			);

			if ( $referrer && $referrer->user_id ) {
				// Mark the coupon as custom in post meta.
				update_post_meta( $coupon_id, 'ecre_custom_referral', 1 );

				// Save the coupon data as custom user settings.
				$this->save_custom_referral_settings( $referrer->user_id, $coupon_id, $coupon_data );
			}

			return true;
		}

		/**
		 * Updates the ecre_referrals_orders table with current coupon data.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 *
		 * @return bool True on success, false on failure.
		 */
		private function update_referrals_orders_table( $coupon_id, $coupon_data ) {
			global $wpdb;

			$table_name = $wpdb->prefix . 'ecre_referrals_orders';

			// Check if table exists.
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$wpdb->esc_like( $table_name )
				)
			);

			if ( $table_exists !== $table_name ) {
				return false;
			}

			// Find all orders using this coupon.
			$orders = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT id, order_id FROM `{$wpdb->prefix}ecre_referrals_orders` WHERE coupon_id = %d",
					absint( $coupon_id )
				),
				ARRAY_A
			);

			// Check for database errors.
			if ( null === $orders && ! empty( $wpdb->last_error ) ) {
				return false;
			}

			// If no matching records found, return success.
			if ( empty( $orders ) ) {
				return true;
			}

			// Update each order record.
			$updated_count = 0;
			foreach ( $orders as $order_record ) {
				// Recalculate discount amount for this order.
				$discount_amount = $this->calculate_discount_for_order(
					absint( $order_record['order_id'] ),
					$coupon_data['coupon_code']
				);

				// Update the record.
				$result = $wpdb->update(
					$table_name,
					array(
						'coupon_code'     => sanitize_text_field( $coupon_data['coupon_code'] ),
						'discount_amount' => floatval( $discount_amount ),
						'updated_at'      => current_time( 'mysql' ),
					),
					array(
						'id' => absint( $order_record['id'] ),
					),
					array( '%s', '%f', '%s' ),
					array( '%d' )
				);

				if ( false !== $result ) {
					$updated_count++;
				}
			}

			return true;
		}

		/**
		 * Updates the ecre_reward_coupons table with current coupon data.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 *
		 * @return bool True on success, false on failure.
		 */
		private function update_reward_coupons_table( $coupon_id, $coupon_data ) {
			global $wpdb;

			$table_name = $wpdb->prefix . 'ecre_reward_coupons';

			// Check if table exists.
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$wpdb->esc_like( $table_name )
				)
			);

			if ( $table_exists !== $table_name ) {
				return false;
			}

			// Encode restrictions as JSON.
			$include_products           = ! empty( $coupon_data['product_ids'] ) ? wp_json_encode( $coupon_data['product_ids'] ) : null;
			$exclude_products           = ! empty( $coupon_data['exclude_product_ids'] ) ? wp_json_encode( $coupon_data['exclude_product_ids'] ) : null;
			$include_product_categories = ! empty( $coupon_data['product_categories'] ) ? wp_json_encode( $coupon_data['product_categories'] ) : null;
			$exclude_product_categories = ! empty( $coupon_data['exclude_categories'] ) ? wp_json_encode( $coupon_data['exclude_categories'] ) : null;

			// Update the reward coupons table.
			$result = $wpdb->update(
				$table_name,
				array(
					'coupon_code'                => sanitize_text_field( $coupon_data['coupon_code'] ),
					'discount_type'              => sanitize_text_field( $coupon_data['discount_type'] ),
					'discount_amount'            => floatval( $coupon_data['discount_amount'] ),
					'usage_limit'                => absint( $coupon_data['usage_limit'] ),
					'status'                     => sanitize_text_field( $coupon_data['status'] ),
					'expires_at'                 => $coupon_data['expiry_date'],
					'include_products'           => $include_products,
					'exclude_products'           => $exclude_products,
					'include_product_categories' => $include_product_categories,
					'exclude_product_categories' => $exclude_product_categories,
					'updated_at'                 => current_time( 'mysql' ),
				),
				array(
					'coupon_id' => absint( $coupon_id ),
				),
				array( '%s', '%s', '%f', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ),
				array( '%d' )
			);

			// Check for database errors.
			if ( false === $result ) {
				return false;
			}

			return true;
		}

		/**
		 * Updates the ecre_rewards_orders table with current coupon data.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 *
		 * @return bool True on success, false on failure.
		 */
		private function update_rewards_orders_table( $coupon_id, $coupon_data ) {
			global $wpdb;

			$table_name = $wpdb->prefix . 'ecre_rewards_orders';

			// Check if table exists.
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$wpdb->esc_like( $table_name )
				)
			);

			if ( $table_exists !== $table_name ) {
				return false;
			}

			// Find all orders using this reward coupon.
			$orders = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT id, order_id FROM `{$wpdb->prefix}ecre_rewards_orders` WHERE reward_coupon_id = %d",
					absint( $coupon_id )
				),
				ARRAY_A
			);

			// Check for database errors.
			if ( null === $orders && ! empty( $wpdb->last_error ) ) {
				return false;
			}

			// If no matching records found, return success.
			if ( empty( $orders ) ) {
				return true;
			}

			// Update each order record.
			$updated_count = 0;
			foreach ( $orders as $order_record ) {
				// Recalculate discount amount for this order.
				$discount_amount = $this->calculate_discount_for_order(
					absint( $order_record['order_id'] ),
					$coupon_data['coupon_code']
				);

				// Update the record.
				$result = $wpdb->update(
					$table_name,
					array(
						'reward_coupon_code'     => sanitize_text_field( $coupon_data['coupon_code'] ),
						'reward_discount_amount' => floatval( $discount_amount ),
						'updated_at'             => current_time( 'mysql' ),
					),
					array(
						'id' => absint( $order_record['id'] ),
					),
					array( '%s', '%f', '%s' ),
					array( '%d' )
				);

				if ( false !== $result ) {
					$updated_count++;
				}
			}

			return true;
		}

		/**
		 * Recalculates discount amount for a specific order.
		 *
		 * Uses existing WooCommerce calculation logic to ensure accuracy.
		 *
		 * @since 1.0.0
		 *
		 * @param int    $order_id    WooCommerce order ID.
		 * @param string $coupon_code Coupon code.
		 *
		 * @return float Discount amount.
		 */
		private function calculate_discount_for_order( $order_id, $coupon_code ) {
			// Get the WooCommerce order object.
			$order = wc_get_order( $order_id );

			// Return 0 if order not found.
			if ( ! $order || ! $order->get_id() ) {
				return 0.0;
			}

			// Use existing Echo Rewards function if available.
			if ( function_exists( 'ecre_calculate_coupon_discount_amount' ) ) {
				return floatval( ecre_calculate_coupon_discount_amount( $order, $coupon_code ) );
			}

			// Fallback: Calculate discount manually.
			$discount_amount = 0.0;
			$coupons_used    = $order->get_coupon_codes();

			if ( in_array( $coupon_code, $coupons_used, true ) ) {
				foreach ( $order->get_items( 'coupon' ) as $item ) {
					if ( $item->get_code() === $coupon_code ) {
						$discount_amount = floatval( $item->get_discount() );
						break;
					}
				}
			}

			return $discount_amount;
		}

		/**
		 * Saves custom referral settings to user_reward_settings table.
		 *
		 * When a referral coupon is manually edited, this method saves the coupon
		 * data as custom user settings so the UI can display "Custom Settings" badge.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $user_id     User ID of the referrer.
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 *
		 * @return void
		 */
		private function save_custom_referral_settings( $user_id, $coupon_id, $coupon_data ) {
			global $wpdb;

			$table_name = $wpdb->prefix . 'ecre_user_reward_settings';

			// Check if table exists.
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$wpdb->esc_like( $table_name )
				)
			);

			if ( $table_exists !== $table_name ) {
				return;
			}

			// Convert WooCommerce discount type to Echo Rewards format.
			$ecre_discount_type = $this->convert_wc_to_ecre_discount_type( $coupon_data['discount_type'] );

			// Prepare settings to save.
			$settings = array(
				'referralCouponType' => array(
					'value' => $ecre_discount_type,
					'label' => $this->get_coupon_type_label( $ecre_discount_type ),
				),
				'referralDiscount'   => $coupon_data['discount_amount'],
			);

			// Save each setting.
			foreach ( $settings as $setting_key => $setting_value ) {
				// Check if setting already exists.
				$existing = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT id FROM `{$wpdb->prefix}ecre_user_settings` WHERE user_id = %d AND setting_key = %s",
						absint( $user_id ),
						sanitize_text_field( $setting_key )
					)
				);

				$setting_data = array(
					'user_id'       => absint( $user_id ),
					'setting_key'   => sanitize_text_field( $setting_key ),
					'setting_value' => wp_json_encode( $setting_value ),
					'data_type'     => is_array( $setting_value ) ? 'array' : 'string',
					'is_active'     => 1,
					'updated_at'    => current_time( 'mysql' ),
				);

				if ( $existing ) {
					// Update existing setting.
					$wpdb->update(
						$table_name,
						$setting_data,
						array( 'id' => absint( $existing ) ),
						array( '%d', '%s', '%s', '%s', '%d', '%s' ),
						array( '%d' )
					);
				} else {
					// Insert new setting.
					$setting_data['created_at'] = current_time( 'mysql' );
					$wpdb->insert(
						$table_name,
						$setting_data,
						array( '%d', '%s', '%s', '%s', '%d', '%s', '%s' )
					);
				}
			}
		}

		/**
		 * Saves custom reward settings to user_reward_settings table.
		 *
		 * When a reward coupon is manually edited, this method saves the coupon
		 * data as custom user settings so the UI can display "Custom Settings" badge.
		 *
		 * @since 1.0.0
		 *
		 * @param int   $user_id     User ID of the referrer.
		 * @param int   $coupon_id   Coupon post ID.
		 * @param array $coupon_data Extracted coupon data.
		 *
		 * @return void
		 */
		private function save_custom_reward_settings( $user_id, $coupon_id, $coupon_data ) {
			global $wpdb;

			$table_name = $wpdb->prefix . 'ecre_user_reward_settings';

			// Check if table exists.
			$table_exists = $wpdb->get_var(
				$wpdb->prepare(
					'SHOW TABLES LIKE %s',
					$wpdb->esc_like( $table_name )
				)
			);

			if ( $table_exists !== $table_name ) {
				return;
			}

			// Convert WooCommerce discount type to Echo Rewards format.
			$ecre_discount_type = $this->convert_wc_to_ecre_discount_type( $coupon_data['discount_type'] );

			// Prepare settings to save.
			$settings = array(
				'rewardType'     => array(
					'value' => $ecre_discount_type,
					'label' => $this->get_coupon_type_label( $ecre_discount_type ),
				),
				'rewardDiscount' => $coupon_data['discount_amount'],
			);

			// Save each setting.
			foreach ( $settings as $setting_key => $setting_value ) {
				// Check if setting already exists.
				$existing = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT id FROM `{$wpdb->prefix}ecre_user_settings` WHERE user_id = %d AND setting_key = %s",
						absint( $user_id ),
						sanitize_text_field( $setting_key )
					)
				);

				$setting_data = array(
					'user_id'       => absint( $user_id ),
					'setting_key'   => sanitize_text_field( $setting_key ),
					'setting_value' => wp_json_encode( $setting_value ),
					'data_type'     => is_array( $setting_value ) ? 'array' : 'string',
					'is_active'     => 1,
					'updated_at'    => current_time( 'mysql' ),
				);

				if ( $existing ) {
					// Update existing setting.
					$wpdb->update(
						$table_name,
						$setting_data,
						array( 'id' => absint( $existing ) ),
						array( '%d', '%s', '%s', '%s', '%d', '%s' ),
						array( '%d' )
					);
				} else {
					// Insert new setting.
					$setting_data['created_at'] = current_time( 'mysql' );
					$wpdb->insert(
						$table_name,
						$setting_data,
						array( '%d', '%s', '%s', '%s', '%d', '%s', '%s' )
					);
				}
			}
		}

		/**
		 * Converts WooCommerce discount type to Echo Rewards format.
		 *
		 * @since 1.0.0
		 *
		 * @param string $wc_discount_type WooCommerce discount type.
		 *
		 * @return string Echo Rewards discount type.
		 */
		private function convert_wc_to_ecre_discount_type( $wc_discount_type ) {
			$type_map = array(
				'percent'       => 'percent',
				'fixed_cart'    => 'fixed',
				'fixed_product' => 'fixed',
			);

			return isset( $type_map[ $wc_discount_type ] ) ? $type_map[ $wc_discount_type ] : $wc_discount_type;
		}

		/**
		 * Gets the human-readable label for a coupon discount type.
		 *
		 * @since 1.0.0
		 *
		 * @param string $discount_type Coupon discount type.
		 *
		 * @return string Human-readable label.
		 */
		private function get_coupon_type_label( $discount_type ) {
			$labels = array(
				'percent'             => __( 'Percentage', 'echo-rewards' ),
				'fixed'               => __( 'Fixed', 'echo-rewards' ),
				'fixed_cart'          => __( 'Fixed', 'echo-rewards' ),
				'fixed_product'       => __( 'Fixed', 'echo-rewards' ),
				'sign_up_fee'         => __( 'Sign Up Fee Discount', 'echo-rewards' ),
				'sign_up_fee_percent' => __( 'Sign Up Fee % Discount', 'echo-rewards' ),
				'recurring_fee'       => __( 'Recurring Product Discount', 'echo-rewards' ),
				'recurring_percent'   => __( 'Recurring Product % Discount', 'echo-rewards' ),
			);

			return isset( $labels[ $discount_type ] ) ? $labels[ $discount_type ] : ucfirst( $discount_type );
		}
	}
}
