<?php
/**
 * WAWP Orders & Status Customizer.
 * Registers custom WooCommerce order statuses and admin list table columns/filters.
 *
 * @package automation-web-platform
 */

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

/**
 * Class WAWP_Orders_Status_Settings
 */
class WAWP_Orders_Status_Settings {
	use WAWP_Settings_Handler;
	use WAWP_Security_Trait;

	/**
	 * Singleton instance.
	 *
	 * @var WAWP_Orders_Status_Settings|null
	 */
	private static $instance = null;

	/**
	 * Get instance.
	 *
	 * @return WAWP_Orders_Status_Settings
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		// Hook to register custom statuses (must run on init).
		add_action( 'init', array( $this, 'register_custom_order_statuses' ), 20 );
		add_filter( 'wc_order_statuses', array( $this, 'add_custom_order_statuses' ) );

		// Custom badges styling.
		add_action( 'admin_head', array( $this, 'output_admin_styles' ) );

		// Register columns for orders list.
		add_filter( 'manage_edit-shop_order_columns', array( $this, 'add_order_columns' ) );
		add_action( 'manage_shop_order_posts_custom_column', array( $this, 'render_order_column_content' ), 10, 2 );

		add_filter( 'manage_woocommerce_page_wc-orders_columns', array( $this, 'add_order_columns' ) );
		add_action( 'manage_woocommerce_page_wc-orders_custom_column', array( $this, 'render_orders_hpos_column_content' ), 10, 2 );

		// Dropdown filters above the table.
		add_action( 'restrict_manage_posts', array( $this, 'add_orders_list_filters' ), 20 );
		add_action( 'woocommerce_order_list_table_restrict_manage_orders', array( $this, 'add_orders_hpos_list_filters' ), 20 );

		// Handle filtering logic in queries.
		add_filter( 'request', array( $this, 'handle_orders_list_filtering' ) );
		add_filter( 'woocommerce_order_list_table_prepare_items_query_args', array( $this, 'handle_orders_hpos_filtering' ) );

		// Add custom statuses to bulk edit dropdown.
		add_filter( 'woocommerce_order_list_table_bulk_actions', array( $this, 'add_custom_statuses_to_bulk_actions' ) );
		add_filter( 'bulk_actions-edit-shop_order', array( $this, 'add_custom_statuses_to_bulk_actions' ) );

		// AJAX: Resend notification from orders list.
		add_action( 'wp_ajax_wawp_resend_order_notification', array( $this, 'ajax_resend_order_notification' ) );

		// Force initial order status on new orders (priority 9999 = runs after payment gateways and other plugins).
		add_action( 'woocommerce_checkout_order_created', array( $this, 'force_initial_order_status' ), 9999 );
		add_action( 'woocommerce_store_api_checkout_order_processed', array( $this, 'force_initial_order_status' ), 9999 );

		// REST endpoint to read the WC default order status for the preview card.
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) );
	}

	/**
	 * Register REST routes.
	 */
	public function register_rest_routes() {
		register_rest_route(
			'wawp/v1',
			'/orders-status/default-status',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'rest_get_default_status' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_woocommerce' );
				},
			)
		);
	}

	/**
	 * REST callback: return the WooCommerce default order status.
	 *
	 * @return \WP_REST_Response
	 */
	public function rest_get_default_status() {
		$default = get_option( 'woocommerce_default_order_status', 'pending' );

		$all_statuses = function_exists( 'wc_get_order_statuses' ) ? wc_get_order_statuses() : array();
		$label        = isset( $all_statuses[ 'wc-' . $default ] ) ? $all_statuses[ 'wc-' . $default ] : $default;

		return rest_ensure_response(
			array(
				'status' => $default,
				'label'  => $label,
			)
		);
	}

	/**
	 * Force the configured initial status on a newly created order.
	 *
	 * Hooked at priority 9999 so it always runs after payment gateways
	 * and any other plugin that modifies the status during checkout.
	 *
	 * @param \WC_Order $order The newly created order.
	 */
	public function force_initial_order_status( $order ) {
		if ( ! $this->is_wc_active() ) {
			return;
		}

		if ( ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FORCE_INITIAL_ENABLED, 0 ) ) {
			return;
		}

		$target = sanitize_key( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FORCE_INITIAL_STATUS, '' ) );
		if ( empty( $target ) ) {
			return;
		}

		if ( ! ( $order instanceof \WC_Order ) ) {
			return;
		}

		$current = $order->get_status();
		if ( $current === $target ) {
			return;
		}

		$order->set_status( $target );
		$order->save();
	}

	/**
	 * Check if WooCommerce is active.
	 *
	 * @return bool
	 */
	private function is_wc_active() {
		return class_exists( 'WooCommerce' );
	}

	/**
	 * Register custom WooCommerce statuses.
	 */
	public function register_custom_order_statuses() {
		if ( ! $this->is_wc_active() || ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ) ) {
			return;
		}

		$custom_statuses = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_CUSTOM_STATUSES, array() ) );
		if ( ! is_array( $custom_statuses ) ) {
			return;
		}

		foreach ( $custom_statuses as $status ) {
			if ( empty( $status['slug'] ) || empty( $status['name'] ) ) {
				continue;
			}
			$slug = sanitize_key( $status['slug'] );
			$name = sanitize_text_field( $status['name'] );

			register_post_status(
				'wc-' . $slug,
				array(
					'label'                     => $name,
					'public'                    => true,
					'exclude_from_search'       => false,
					'show_in_admin_all_list'    => true,
					'show_in_admin_status_list' => true,
					'label_count'               => array(
						$name . ' <span class="count">(%s)</span>',
						$name . ' <span class="count">(%s)</span>',
						'singular' => $name . ' <span class="count">(%s)</span>',
						'plural'   => $name . ' <span class="count">(%s)</span>',
						'context'  => null,
						'domain'   => 'automation-web-platform',
					),
				)
			);
		}
	}

	/**
	 * Add custom statuses to WooCommerce order statuses array.
	 *
	 * @param array $order_statuses Existing statuses.
	 * @return array
	 */
	public function add_custom_order_statuses( $order_statuses ) {
		if ( ! $this->is_wc_active() || ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ) ) {
			return $order_statuses;
		}

		$custom_statuses = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_CUSTOM_STATUSES, array() ) );
		if ( ! is_array( $custom_statuses ) ) {
			return $order_statuses;
		}

		foreach ( $custom_statuses as $status ) {
			if ( empty( $status['slug'] ) || empty( $status['name'] ) ) {
				continue;
			}
			$slug = sanitize_key( $status['slug'] );
			$name = sanitize_text_field( $status['name'] );

			$order_statuses[ 'wc-' . $slug ] = $name;
		}

		return $order_statuses;
	}

	/**
	 * Output inline CSS styles for admin status badges.
	 *
	 * Uses Remix Icons font for icons and generates modern pill-style badges
	 * with light pastel backgrounds derived from the status color.
	 */
	public function output_admin_styles() {
		if ( ! $this->is_wc_active() || ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ) ) {
			return;
		}

		$defaults                  = WAWP_Settings_Registry::get_defaults();
		$default_statuses_fallback = isset( $defaults[ WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES ] ) ? $defaults[ WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES ] : array();

		$custom_statuses  = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_CUSTOM_STATUSES, array() ) );
		$default_statuses = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES, $default_statuses_fallback ) );

		echo '<style>';

		if ( is_array( $custom_statuses ) ) {
			foreach ( $custom_statuses as $status ) {
				if ( empty( $status['slug'] ) ) {
					continue;
				}
				$slug    = sanitize_key( $status['slug'] );
				$color   = ! empty( $status['color'] ) ? sanitize_hex_color( $status['color'] ) : '#64748b';
				$icon    = ! empty( $status['icon'] ) ? sanitize_text_field( $status['icon'] ) : 'ri-price-tag-3-line';
				$unicode = $this->get_remixicon_unicode( $icon );

				if ( $slug && $color ) {
					echo wp_kses( $this->build_status_badge_css( $slug, $color, $unicode ), array() );
				}
			}
		}

		if ( is_array( $default_statuses ) ) {
			foreach ( $default_statuses as $slug => $data ) {
				if ( empty( $slug ) ) {
					continue;
				}
				$clean_slug = sanitize_key( $slug );
				$color      = ! empty( $data['color'] ) ? sanitize_hex_color( $data['color'] ) : '#64748b';
				$icon       = ! empty( $data['icon'] ) ? sanitize_text_field( $data['icon'] ) : 'ri-price-tag-3-line';
				$unicode    = $this->get_remixicon_unicode( $icon );

				if ( $clean_slug && $color ) {
					echo wp_kses( $this->build_status_badge_css( $clean_slug, $color, $unicode ), array() );
				}
			}
		}

		echo '</style>';
	}

	/**
	 * Build CSS for a single status badge.
	 *
	 * Generates a modern pill-style badge with a pastel background
	 * derived from the brand color, and a Remix Icon before the label.
	 *
	 * @param string $slug    Status slug.
	 * @param string $color   Hex brand color.
	 * @param string $unicode Remix Icon CSS unicode escape.
	 * @return string CSS block.
	 */
	private function build_status_badge_css( $slug, $color, $unicode ) {
		$sel   = 'mark.status-' . $slug . ', .order-status.status-' . $slug;
		$bsel  = 'mark.status-' . $slug . '::before, .order-status.status-' . $slug . '::before';
		$rtl_b = '[dir="rtl"] mark.status-' . $slug . '::before, [dir="rtl"] .order-status.status-' . $slug . '::before';

		$css  = $sel . ' {';
		$css .= 'background-color: ' . $color . '1a !important;'; // 10% opacity background.
		$css .= 'color: ' . $color . ' !important;';
		$css .= 'border: 1.5px solid ' . $color . '4d !important;'; // 30% opacity border.
		$css .= 'border-radius: 20px !important;';
		$css .= 'padding: 3px 10px 3px 7px !important;';
		$css .= 'font-weight: 600 !important;';
		$css .= 'font-size: 11px !important;';
		$css .= 'display: inline-flex !important;';
		$css .= 'align-items: center !important;';
		$css .= 'gap: 4px !important;';
		$css .= '}';

		$css .= $bsel . ' {';
		$css .= 'font-family: remixicon !important;';
		$css .= 'content: "' . $unicode . '" !important;';
		$css .= 'font-style: normal !important;';
		$css .= 'font-size: 13px !important;';
		$css .= 'line-height: 1 !important;';
		$css .= 'display: inline-block !important;';
		$css .= 'margin: 0 !important;';
		$css .= '}';

		$css .= '[dir="rtl"] ' . $sel . ' { padding: 3px 7px 3px 10px !important; }';
		$css .= $rtl_b . ' { margin: 0 !important; }';

		return $css;
	}

	/**
	 * Map Remix Icon key to its CSS unicode character.
	 *
	 * Values sourced from the bundled remixicon.css file.
	 *
	 * @param string $icon Remix Icon class key.
	 * @return string CSS unicode escape string.
	 */
	private function get_remixicon_unicode( $icon ) {
		$map = array(
			'ri-checkbox-circle-line' => '\\eb81', // Check / success.
			'ri-time-line'            => '\\f20f', // Clock / pending.
			'ri-loader-4-line'        => '\\eec6', // Spinner / processing.
			'ri-pause-circle-line'    => '\\efd6', // Pause / on-hold.
			'ri-close-circle-line'    => '\\eb97', // Close / cancelled.
			'ri-refund-line'          => '\\f068', // Refund arrow.
			'ri-error-warning-line'   => '\\eca1', // Warning / failed.
			'ri-star-fill'            => '\\f186', // Star / special.
			'ri-price-tag-3-line'     => '\\f023', // Tag / default.
			'ri-truck-line'           => '\\f231', // Truck / shipping.
			'ri-archive-line'         => '\\ea48', // Box / package.
			'ri-heart-fill'           => '\\ee0e', // Heart / favorite.
		);
		return isset( $map[ $icon ] ) ? $map[ $icon ] : '\\f023'; // Default to tag icon.
	}

	/**
	 * Get country code (ISO2) from a phone number.
	 *
	 * @param string $phone Phone number.
	 * @return string ISO2 country code (lowercase) or empty.
	 */
	private function get_country_code_from_phone( $phone ) {
		$digits = preg_replace( '/\D/', '', $phone );
		if ( empty( $digits ) ) {
			return '';
		}

		if ( class_exists( 'WAWP\Vendor\libphonenumber\PhoneNumberUtil' ) ) {
			try {
				$phone_util  = \WAWP\Vendor\libphonenumber\PhoneNumberUtil::getInstance();
				$e164        = '+' . $digits;
				$num         = $phone_util->parse( $e164, null );
				$region_code = $phone_util->getRegionCodeForNumber( $num );
				if ( $region_code ) {
					return strtolower( $region_code );
				}
			} catch ( \Throwable $e ) {
				// Fallback to dial code mapping below.
				unset( $e );
			}
		}

		// Fallback simple dial code mapping.
		if ( function_exists( 'WAWP\wawp_get_all_countries' ) ) {
			$countries = \WAWP\wawp_get_all_countries();
			usort(
				$countries,
				function ( $a, $b ) {
					return strlen( $b['dialCode'] ) - strlen( $a['dialCode'] );
				}
			);
			foreach ( $countries as $c ) {
				if ( strpos( $digits, $c['dialCode'] ) === 0 ) {
					return strtolower( $c['iso2'] );
				}
			}
		}

		return '';
	}

	/**
	 * Convert ISO2 country code to emoji flag.
	 *
	 * @param string $iso ISO2 code.
	 * @return string
	 */
	private function iso2_to_flag( $iso ) {
		$iso  = strtoupper( $iso );
		$flag = '';
		$len  = mb_strlen( $iso );
		for ( $i = 0; $i < $len; $i++ ) {
			$code  = 127397 + ord( $iso[ $i ] );
			$flag .= mb_convert_encoding( '&#' . $code . ';', 'UTF-8', 'HTML-ENTITIES' );
		}
		return $flag;
	}


	/**
	 * Render order list custom column content for legacy Post Type table.
	 *
	 * @param string $column_name Column key.
	 * @param int    $post_id     Post ID.
	 */
	public function render_order_column_content( $column_name, $post_id ) {
		if ( strpos( $column_name, 'wawp_' ) !== 0 ) {
			return;
		}
		$order = wc_get_order( $post_id );
		if ( $order ) {
			$this->render_column_value( $column_name, $order );
		}
	}

	/**
	 * Render order list custom column content for HPOS table.
	 *
	 * @param string    $column_name Column key.
	 * @param \WC_Order $order       Order object.
	 */
	public function render_orders_hpos_column_content( $column_name, $order ) {
		if ( strpos( $column_name, 'wawp_' ) !== 0 ) {
			return;
		}
		$this->render_column_value( $column_name, $order );
	}

	/**
	 * Output the actual value inside list columns.
	 *
	 * @param string    $column_name Column name.
	 * @param \WC_Order $order       Order object.
	 */
	private function render_column_value( $column_name, $order ) {
		switch ( $column_name ) {
			case 'wawp_payment_method':
				echo esc_html( $order->get_payment_method_title() );
				break;
			case 'wawp_shipping_method':
				echo esc_html( $order->get_shipping_method() );
				break;
			case 'wawp_product_names':
				$items = $order->get_items();
				$names = array();
				foreach ( $items as $item ) {
					$names[] = '<span style="white-space: nowrap;">' . esc_html( $item->get_name() ) . '&nbsp;(x' . (int) $item->get_quantity() . ')</span>';
				}
				echo wp_kses_post( implode( ', ', $names ) );
				break;
			case 'wawp_phone_number':
				$phone = $order->get_billing_phone();
				$flag  = '';
				if ( ! empty( $phone ) ) {
					$iso = $this->get_country_code_from_phone( $phone );
					if ( $iso ) {
						if ( 'il' === strtolower( $iso ) ) {
							$iso = 'ps';
						}
						$flag = $this->iso2_to_flag( $iso );
					}
				}
				echo '<span style="display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; vertical-align: middle;">';
				if ( ! empty( $flag ) ) {
					echo '<span style="font-size: 16px; line-height: 1;">' . esc_html( $flag ) . '</span>';
				}
				echo '<span>' . esc_html( $phone ) . '</span>';

				$customer_id = $order->get_customer_id();
				if ( $customer_id ) {
					$phone_verified = WAWP()->user_manager->get_verification_status( $customer_id, 'whatsapp' );
					$badge_color    = $phone_verified ? '#22c55e' : '#ef4444';
					$badge_icon     = $phone_verified ? 'verified' : 'not-verified';
					$svg            = WAWP_UI_Helper::get_svg(
						$badge_icon,
						array(
							'width'  => 16,
							'height' => 16,
							'color'  => $badge_color,
						)
					);
					$allowed_svg    = array(
						'svg'  => array(
							'class'           => true,
							'aria-hidden'     => true,
							'aria-labelledby' => true,
							'role'            => true,
							'viewbox'         => true,
							'width'           => true,
							'height'          => true,
							'fill'            => true,
							'xmlns'           => true,
						),
						'path' => array(
							'd'    => true,
							'fill' => true,
						),
					);
					echo '<span title="' . ( $phone_verified ? esc_attr__( 'WhatsApp Verified', 'automation-web-platform' ) : esc_attr__( 'WhatsApp Not Verified', 'automation-web-platform' ) ) . '" style="display:inline-flex; align-items:center; vertical-align:middle;">' . wp_kses( $svg, $allowed_svg ) . '</span>';
				}
				echo '</span>';
				break;
			case 'wawp_shipping_cost':
				echo wp_kses_post( wc_price( $order->get_shipping_total(), array( 'currency' => $order->get_currency() ) ) );
				break;
			case 'wawp_resend_notif':
				$order_id       = $order->get_id();
				$current_status = $order->get_status();
				$flow_builder   = WAWP_Flow_Builder::get_instance();
				$all_notifs     = $flow_builder->get_all_notifications();
				$notifications  = array();

				foreach ( $all_notifs as $notif ) {
					if ( isset( $notif['trigger_key'] ) && 'wc_status_' . $current_status === $notif['trigger_key'] ) {
						$notifications[] = $notif;
					}
				}

				if ( empty( $notifications ) ) {
					echo '<span style="color: #94a3b8; font-style: italic; font-size: 12px;">' . esc_html__( 'No active rules', 'automation-web-platform' ) . '</span>';
					break;
				}

				$first_notif      = $notifications[0];
				$first_id         = $first_notif['id'];
				$sender_type      = $first_notif['sender_type'] ?? '';
				$whatsapp_enabled = ! empty( $first_notif['whatsapp_enabled'] );
				$is_meta          = str_contains( $sender_type, 'meta' );
				$email_enabled    = ! empty( $first_notif['email_enabled'] );

				$wa_web  = ( $whatsapp_enabled && ! $is_meta );
				$wa_meta = ( $whatsapp_enabled && $is_meta );
				$email   = $email_enabled;
				?>
				<div class="wawp-order-list-actions" style="display: flex; flex-direction: column; gap: 6px; min-width: 140px;">
					<div class="wawp-list-buttons-wrapper" style="display: flex; gap: 4px; align-items: center;">
						<button type="button" class="button button-primary wawp-send-btn whatsapp-web wawp-btn-icon-only<?php echo $wa_web ? '' : ' wawp-hide'; ?>" data-gateway="whatsapp" data-order-id="<?php echo esc_attr( $order_id ); ?>" data-status="<?php echo esc_attr( $first_id ); ?>" title="<?php esc_attr_e( 'Send WhatsApp Web', 'automation-web-platform' ); ?>" style="width: 28px !important; height: 28px !important; min-width: 28px !important; padding: 0 !important; border-radius: 6px !important;">
							<img src="<?php echo esc_url( WAWP_PLUGIN_URL . 'assets/icons/whatsapp.svg' ); ?>" alt="WhatsApp" style="width: 16px; height: 16px; display: inline-block; vertical-align: middle; filter: brightness(0) invert(1);">
						</button>
						<button type="button" class="button button-primary wawp-send-btn whatsapp-meta wawp-btn-icon-only<?php echo $wa_meta ? '' : ' wawp-hide'; ?>" data-gateway="meta" data-order-id="<?php echo esc_attr( $order_id ); ?>" data-status="<?php echo esc_attr( $first_id ); ?>" title="<?php esc_attr_e( 'Send WhatsApp Meta', 'automation-web-platform' ); ?>" style="width: 28px !important; height: 28px !important; min-width: 28px !important; padding: 0 !important; border-radius: 6px !important;">
							<img src="<?php echo esc_url( WAWP_PLUGIN_URL . 'assets/icons/meta.svg' ); ?>" alt="Meta JID" style="width: 16px; height: 16px; display: inline-block; vertical-align: middle; filter: brightness(0) invert(1);">
						</button>
						<button type="button" class="button button-primary wawp-send-btn email wawp-btn-icon-only<?php echo $email ? '' : ' wawp-hide'; ?>" data-gateway="email" data-order-id="<?php echo esc_attr( $order_id ); ?>" data-status="<?php echo esc_attr( $first_id ); ?>" title="<?php esc_attr_e( 'Send Email', 'automation-web-platform' ); ?>" style="width: 28px !important; height: 28px !important; min-width: 28px !important; padding: 0 !important; border-radius: 6px !important;">
							<img src="<?php echo esc_url( WAWP_PLUGIN_URL . 'assets/icons/email.svg' ); ?>" alt="Email" style="width: 16px; height: 16px; display: inline-block; vertical-align: middle; filter: brightness(0) invert(1);">
						</button>
					</div>
					<div class="wawp-action-message" style="display: none; font-size: 11px; margin-top: 2px; padding: 4px; border-radius: 3px;"></div>
				</div>
				<?php
				break;
		}
	}

	/**
	 * Get active payment methods list.
	 *
	 * @return array
	 */
	private function get_payment_methods() {
		if ( ! function_exists( 'WC' ) ) {
			return array();
		}
		$gateways = WC()->payment_gateways->payment_gateways();
		$methods  = array();
		foreach ( $gateways as $gateway ) {
			if ( 'yes' === $gateway->enabled ) {
				$methods[ $gateway->id ] = $gateway->get_title();
			}
		}
		return $methods;
	}

	/**
	 * Add dropdown filters for legacy orders list.
	 */
	public function add_orders_list_filters() {
		global $typenow;
		if ( 'shop_order' !== $typenow ) {
			return;
		}
		$this->render_dropdown_filters();
	}

	/**
	 * Add dropdown filters for HPOS orders list.
	 */
	public function add_orders_hpos_list_filters() {
		$this->render_dropdown_filters();
	}

	/**
	 * Render top filter dropdowns.
	 */
	private function render_dropdown_filters() {
		if ( ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ) ) {
			return;
		}

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PAYMENT_METHOD, 0 ) ) {
			$methods      = $this->get_payment_methods();
			$filter_value = filter_input( INPUT_GET, 'wawp_payment_method_filter', FILTER_DEFAULT );
			$selected     = ! empty( $filter_value ) ? sanitize_text_field( wp_unslash( $filter_value ) ) : '';
			echo '<select name="wawp_payment_method_filter">';
			echo '<option value="">' . esc_html__( 'All Payment Methods', 'automation-web-platform' ) . '</option>';
			foreach ( $methods as $id => $title ) {
				echo '<option value="' . esc_attr( $id ) . '" ' . selected( $selected, $id, false ) . '>' . esc_html( $title ) . '</option>';
			}
			echo '</select>';
		}
	}

	/**
	 * Handle legacy orders list filtering.
	 *
	 * @param array $vars Query vars.
	 * @return array
	 */
	public function handle_orders_list_filtering( $vars ) {
		global $typenow;
		$filter_value = filter_input( INPUT_GET, 'wawp_payment_method_filter', FILTER_DEFAULT );
		if ( 'shop_order' === $typenow && ! empty( $filter_value ) ) {
			$vars['meta_query'][] = array(
				'key'     => '_payment_method',
				'value'   => sanitize_text_field( wp_unslash( $filter_value ) ),
				'compare' => '=',
			);
		}
		return $vars;
	}

	/**
	 * Handle HPOS orders list filtering.
	 *
	 * @param array $args Query arguments.
	 * @return array
	 */
	public function handle_orders_hpos_filtering( $args ) {
		$filter_value = filter_input( INPUT_GET, 'wawp_payment_method_filter', FILTER_DEFAULT );
		if ( ! empty( $filter_value ) ) {
			$args['payment_method'] = sanitize_text_field( wp_unslash( $filter_value ) );
		}
		return $args;
	}

	/**
	 * Get React settings data.
	 *
	 * @return array
	 */
	public function get_react_settings_data() {
		$defaults                  = WAWP_Settings_Registry::get_defaults();
		$default_statuses_fallback = isset( $defaults[ WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES ] ) ? $defaults[ WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES ] : array();

		// Fetch currently saved default statuses colors.
		$saved_defaults = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES, array() ) );
		if ( ! is_array( $saved_defaults ) ) {
			$saved_defaults = array();
		}

		// Dynamically query WooCommerce for all registered statuses.
		$wc_statuses = $this->is_wc_active() ? wc_get_order_statuses() : array();

		// Get our custom status slugs so we exclude them from "default_statuses".
		$custom_statuses  = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_CUSTOM_STATUSES, array() ) );
		$our_custom_slugs = array();
		if ( is_array( $custom_statuses ) ) {
			foreach ( $custom_statuses as $cs ) {
				if ( ! empty( $cs['slug'] ) ) {
					$our_custom_slugs[] = $cs['slug'];
				}
			}
		}

		$final_default_statuses = array();
		foreach ( $wc_statuses as $full_slug => $label ) {
			// Strip 'wc-' prefix.
			$slug = preg_replace( '/^wc-/', '', $full_slug );

			// Exclude our own custom statuses (they have their own list & colors).
			if ( in_array( $slug, $our_custom_slugs, true ) ) {
				continue;
			}

			// If color already saved in DB, use it.
			if ( isset( $saved_defaults[ $slug ]['color'] ) ) {
				$color = $saved_defaults[ $slug ]['color'];
			} elseif ( isset( $default_statuses_fallback[ $slug ]['color'] ) ) {
				// Otherwise, if core status color exists in registry defaults, use it.
				$color = $default_statuses_fallback[ $slug ]['color'];
			} else {
				// Otherwise, default color for custom statuses from other plugins.
				$color = '#64748b';
			}

			// If icon already saved in DB, use it.
			if ( isset( $saved_defaults[ $slug ]['icon'] ) ) {
				$icon = $saved_defaults[ $slug ]['icon'];
			} elseif ( isset( $default_statuses_fallback[ $slug ]['icon'] ) ) {
				// Otherwise, if core status icon exists in registry defaults, use it.
				$icon = $default_statuses_fallback[ $slug ]['icon'];
			} else {
				// Otherwise, default icon.
				$icon = 'ri-price-tag-3-line';
			}

			$translated_label = $label;
			if ( 'pending' === $slug ) {
				$translated_label = __( 'Pending Payment', 'automation-web-platform' );
			} elseif ( 'processing' === $slug ) {
				$translated_label = __( 'Processing', 'automation-web-platform' );
			} elseif ( 'on-hold' === $slug ) {
				$translated_label = __( 'On Hold', 'automation-web-platform' );
			} elseif ( 'completed' === $slug ) {
				$translated_label = __( 'Completed', 'automation-web-platform' );
			} elseif ( 'cancelled' === $slug ) {
				$translated_label = __( 'Cancelled', 'automation-web-platform' );
			} elseif ( 'refunded' === $slug ) {
				$translated_label = __( 'Refunded', 'automation-web-platform' );
			} elseif ( 'failed' === $slug ) {
				$translated_label = __( 'Failed', 'automation-web-platform' );
			} elseif ( 'checkout-draft' === $slug || 'draft' === $slug ) {
				$translated_label = __( 'Draft', 'automation-web-platform' );
			}

			$final_default_statuses[ $slug ] = array(
				'color' => $color,
				'icon'  => $icon,
				'label' => $translated_label,
			);
		}

		return array(
			'settings'    => array(
				'enabled'                => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ),
				'custom_statuses'        => $custom_statuses,
				'default_statuses'       => $final_default_statuses,
				'filter_payment_method'  => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PAYMENT_METHOD, 0 ),
				'filter_shipping_method' => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_SHIPPING_METHOD, 0 ),
				'filter_product_names'   => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PRODUCT_NAMES, 0 ),
				'filter_phone_number'    => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PHONE_NUMBER, 0 ),
				'filter_shipping_cost'   => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_SHIPPING_COST, 0 ),
				'force_initial_enabled'  => (int) $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FORCE_INITIAL_ENABLED, 0 ),
				'force_initial_status'   => $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FORCE_INITIAL_STATUS, '' ),
			),
			'optionNames' => array(
				'enabled'                => WAWP_Settings_Registry::ORDERS_STATUS_ENABLED,
				'custom_statuses'        => WAWP_Settings_Registry::ORDERS_STATUS_CUSTOM_STATUSES,
				'default_statuses'       => WAWP_Settings_Registry::ORDERS_STATUS_DEFAULT_STATUSES,
				'filter_payment_method'  => WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PAYMENT_METHOD,
				'filter_shipping_method' => WAWP_Settings_Registry::ORDERS_STATUS_FILTER_SHIPPING_METHOD,
				'filter_product_names'   => WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PRODUCT_NAMES,
				'filter_phone_number'    => WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PHONE_NUMBER,
				'filter_shipping_cost'   => WAWP_Settings_Registry::ORDERS_STATUS_FILTER_SHIPPING_COST,
				'force_initial_enabled'  => WAWP_Settings_Registry::ORDERS_STATUS_FORCE_INITIAL_ENABLED,
				'force_initial_status'   => WAWP_Settings_Registry::ORDERS_STATUS_FORCE_INITIAL_STATUS,
			),
			'i18n'        => array(
				'pageTitle'               => __( 'Orders & status', 'automation-web-platform' ),
				'pageSubtitle'            => __( 'Customize WooCommerce order statuses and manage custom order columns.', 'automation-web-platform' ),
				'statusName'              => __( 'Status Name', 'automation-web-platform' ),
				'slug'                    => __( 'Slug', 'automation-web-platform' ),
				'color'                   => __( 'Color', 'automation-web-platform' ),
				'addCustomStatus'         => __( 'Add Custom Status', 'automation-web-platform' ),
				'enablePayment'           => __( 'Enable Payment Method filter', 'automation-web-platform' ),
				'enableShipping'          => __( 'Enable Shipping Method filter', 'automation-web-platform' ),
				'enableProducts'          => __( 'Enable Product Names filter', 'automation-web-platform' ),
				'enablePhone'             => __( 'Enable Phone Number filter', 'automation-web-platform' ),
				'enableShippingCost'      => __( 'Enable Shipping Cost filter', 'automation-web-platform' ),
				'customStatuses'          => __( 'Custom Statuses', 'automation-web-platform' ),
				'defaultStatuses'         => __( 'Default Statuses', 'automation-web-platform' ),
				'mainToggleLabel'         => __( 'Activate Orders & Status Features', 'automation-web-platform' ),
				'mainToggleDesc'          => __( 'Enable custom order statuses and custom columns in WooCommerce orders list.', 'automation-web-platform' ),
				'columnConfig'            => __( 'Order List Columns', 'automation-web-platform' ),
				'columnConfigDesc'        => __( 'Select which custom details to show as columns in WooCommerce orders list table.', 'automation-web-platform' ),
				'slugValidationError'     => __( 'Slug must contain only English lowercase letters, numbers, and hyphens/underscores.', 'automation-web-platform' ),
				'allStatuses'             => __( 'All Statuses', 'automation-web-platform' ),
				'forceInitialTitle'       => __( 'Force Initial Order Status', 'automation-web-platform' ),
				'forceInitialDesc'        => __( 'Override the order status assigned by WooCommerce or payment gateways immediately after checkout — regardless of any other plugin.', 'automation-web-platform' ),
				'forceInitialToggleLabel' => __( 'Enable forced initial status', 'automation-web-platform' ),
				'forceInitialToggleDesc'  => __( 'When enabled, the selected status below will be forced on every new order at priority 9999, overriding payment gateways and other plugins.', 'automation-web-platform' ),
				'wcDefaultStatusLabel'    => __( 'WooCommerce currently assigns', 'automation-web-platform' ),
				'forceStatusSelectLabel'  => __( 'Force this status on new orders', 'automation-web-platform' ),
				'forceStatusSelectDesc'   => __( 'Select the status that will be applied to every new order after it is created.', 'automation-web-platform' ),
				'selectStatus'            => __( 'Select a status…', 'automation-web-platform' ),
			),
			'restUrl'     => rest_url( 'wawp/v1/orders-status/default-status' ),
		);
	}

	/**
	 * Add custom statuses to the WooCommerce orders bulk-edit actions dropdown.
	 *
	 * @param array $actions Existing bulk actions.
	 * @return array
	 */
	public function add_custom_statuses_to_bulk_actions( $actions ) {
		if ( ! $this->is_wc_active() || ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ) ) {
			return $actions;
		}

		$custom_statuses = $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_CUSTOM_STATUSES, array() ) );
		if ( ! is_array( $custom_statuses ) ) {
			return $actions;
		}

		foreach ( $custom_statuses as $status ) {
			if ( empty( $status['slug'] ) || empty( $status['name'] ) ) {
				continue;
			}
			$slug = sanitize_key( $status['slug'] );
			$name = sanitize_text_field( $status['name'] );

			// Use the same key format as WC core: mark_order_status-{slug}.
			$actions[ 'mark_' . $slug ] = sprintf(
				/* translators: %s: status name */
				esc_html__( 'Change status to %s', 'automation-web-platform' ),
				$name
			);
		}

		return $actions;
	}

	/**
	 * Add resend notification column to orders list table.
	 *
	 * @param array $columns Existing columns.
	 * @return array
	 */
	public function add_order_columns( $columns ) {
		if ( ! $this->is_wc_active() || ! $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_ENABLED, 1 ) ) {
			return $columns;
		}

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PAYMENT_METHOD, 0 ) ) {
			$columns['wawp_payment_method'] = esc_html__( 'Payment Method', 'automation-web-platform' );
		}
		if ( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_SHIPPING_METHOD, 0 ) ) {
			$columns['wawp_shipping_method'] = esc_html__( 'Shipping Method', 'automation-web-platform' );
		}
		if ( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PRODUCT_NAMES, 0 ) ) {
			$columns['wawp_product_names'] = esc_html__( 'Product Names', 'automation-web-platform' );
		}
		if ( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_PHONE_NUMBER, 0 ) ) {
			$columns['wawp_phone_number'] = esc_html__( 'Phone Number', 'automation-web-platform' );
		}
		if ( $this->get_wawp_setting( WAWP_Settings_Registry::ORDERS_STATUS_FILTER_SHIPPING_COST, 0 ) ) {
			$columns['wawp_shipping_cost'] = esc_html__( 'Shipping Cost', 'automation-web-platform' );
		}

		// Always show resend notification button when the feature is enabled.
		$columns['wawp_resend_notif'] = esc_html__( 'Notification', 'automation-web-platform' );

		return $columns;
	}

	/**
	 * Handle AJAX: resend order notification from the orders list quick-action.
	 *
	 * Calls the WAWP flow builder directly using the same path as the order
	 * edit meta-box "Send Notification" button, so the log entry will show
	 * "Manual Notification Request" with the correct order ID.
	 */
	public function ajax_resend_order_notification() {
		check_ajax_referer( 'wawp_orders_list_nonce', 'nonce' );

		$capability = 'manage_woocommerce';
		if ( ! current_user_can( $capability ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Insufficient permissions.', 'automation-web-platform' ) ) );
			return;
		}

		$order_id       = isset( $_POST['order_id'] ) ? absint( wp_unslash( $_POST['order_id'] ) ) : 0;
		$status_request = isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : '';

		if ( ! $order_id ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid order ID.', 'automation-web-platform' ) ) );
			return;
		}

		if ( ! function_exists( 'wc_get_order' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'WooCommerce is not available.', 'automation-web-platform' ) ) );
			return;
		}

		$order = wc_get_order( $order_id );
		if ( ! $order ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Order not found.', 'automation-web-platform' ) ) );
			return;
		}

		if ( ! class_exists( 'WAWP_Flow_Builder' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Notification system unavailable.', 'automation-web-platform' ) ) );
			return;
		}

		$flow_builder = WAWP_Flow_Builder::get_instance();

		// If a specific status was requested, temporarily use it for the notification.
		// Otherwise fall back to the order's current status (same as the metabox button).
		$status = $status_request ? $status_request : $order->get_status();

		// Use handle_order_status_change directly so the log entry correctly
		// reads "Manual Notification Request (Order #XXXX)" instead of any
		// unrelated trigger (e.g. OTP / new-customer flow).
		$log_label = sprintf(
			/* translators: %s: order number */
			esc_html__( 'Manual Notification Request (Order #%s)', 'automation-web-platform' ),
			$order->get_order_number()
		);

		$flow_builder->handle_order_status_change( $order_id, $status, $status, $order, $log_label );

		wp_send_json_success( array( 'message' => esc_html__( 'Notification sent successfully.', 'automation-web-platform' ) ) );
	}
}
