<?php
/**
 * REST API Controller Class
 *
 * @package ShopExplorer\Api
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Api;

use SHOPEXPLORER\Exceptions\SHOPEX_ShopExplorerException;
use SHOPEXPLORER\Admin\SHOPEX_SettingsManager;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * REST API Controller class
 *
 * @since 1.0.0
 */
class SHOPEX_RestApiController {

	/**
	 * API namespace
	 */
	const NAMESPACE = 'shop-explorer/v1';

	/**
	 * Authentication manager instance
	 *
	 * @var AuthenticationManager
	 */
	private $auth_manager;

	/**
	 * Settings manager instance
	 *
	 * @var SHOPEX_SettingsManager
	 */
	private $settings_manager;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->settings_manager = new SHOPEX_SettingsManager();
	}

	/**
	 * Register REST API routes
	 */
	public function register_routes() {
		// Load and register customers controller
		require_once SHOPEX_PATH . 'inc/Api/CustomersController.php';
		$customers_controller = new SHOPEX_CustomersController();
		$customers_controller->register_routes();

		// Settings endpoints
		register_rest_route( self::NAMESPACE, '/settings', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_settings' ],
			'permission_callback' => [ $this, 'check_manage_settings_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/settings', [
			'methods' => 'POST',
			'callback' => [ $this, 'update_settings' ],
			'permission_callback' => [ $this, 'check_manage_settings_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/settings/export', [
			'methods' => 'GET',
			'callback' => [ $this, 'export_settings' ],
			'permission_callback' => [ $this, 'check_manage_settings_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/settings/import', [
			'methods' => 'POST',
			'callback' => [ $this, 'import_settings' ],
			'permission_callback' => [ $this, 'check_manage_settings_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/settings/reset', [
			'methods' => 'POST',
			'callback' => [ $this, 'reset_settings' ],
			'permission_callback' => [ $this, 'check_manage_settings_permission' ],
		]);

		// Frontend Dashboard Settings endpoints
		register_rest_route( self::NAMESPACE, '/frontend-settings', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_frontend_settings' ],
			'permission_callback' => [ $this, 'check_frontend_access_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/frontend-settings', [
			'methods' => 'POST',
			'callback' => [ $this, 'save_frontend_settings' ],
			'permission_callback' => [ $this, 'check_manage_settings_permission' ],
		]);

		// Orders endpoints
		register_rest_route( self::NAMESPACE, '/orders', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_orders' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
			'args' => [
				'page' => [
					'type' => 'integer',
					'default' => 1,
					'minimum' => 1,
				],
				'per_page' => [
					'type' => 'integer',
					'default' => 20,
					'minimum' => 1,
					'maximum' => 100,
				],
				'status' => [
					'type' => 'string',
					'enum' => [ '', 'pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed' ],
					'sanitize_callback' => 'sanitize_text_field',
				],
				'search' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
			],
		]);

		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_order' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
			'args' => [
				'id' => [
					'required' => true,
					'type' => 'integer',
					'validate_callback' => function ( $param ) {
						return is_numeric( $param ) && $param > 0;
					},
				],
			],
		]);

		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_order' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_order' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
			'args' => [
				'id' => [
					'required' => true,
					'type' => 'integer',
					'validate_callback' => function ( $param ) {
						return is_numeric( $param ) && $param > 0;
					},
				],
				'force' => [
					'type' => 'boolean',
					'default' => false,
					'description' => 'Whether to permanently delete the order or move to trash',
				],
			],
		]);

		// Order notes endpoints
		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)/notes', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_order_notes' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)/notes', [
			'methods' => 'POST',
			'callback' => [ $this, 'add_order_note' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)/notes/(?P<note_id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_order_note' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)/notes/(?P<note_id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_order_note' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		// Order refund endpoint
		register_rest_route( self::NAMESPACE, '/orders/(?P<id>\d+)/refund', [
			'methods' => 'POST',
			'callback' => [ $this, 'refund_order' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		// Products endpoints
		register_rest_route( self::NAMESPACE, '/products', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'page' => [
					'type' => 'integer',
					'default' => 1,
					'minimum' => 1,
				],
				'per_page' => [
					'type' => 'integer',
					'default' => 20,
					'minimum' => 1,
					'maximum' => 100,
				],
				'search' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'status' => [
					'type' => 'string',
					'enum' => [ '', 'publish', 'draft', 'private', 'trash' ],
					'sanitize_callback' => 'sanitize_text_field',
				],
				'stock_status' => [
					'type' => 'string',
					'enum' => [ '', 'instock', 'outofstock', 'onbackorder' ],
					'sanitize_callback' => 'sanitize_text_field',
				],
				'sku' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
			],
		]);

		register_rest_route( self::NAMESPACE, '/products/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Dashboard endpoints
		register_rest_route( self::NAMESPACE, '/dashboard/stats', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_dashboard_stats' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		register_rest_route( self::NAMESPACE, '/dashboard/activity', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_recent_activity' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// Configuration endpoint
		register_rest_route( self::NAMESPACE, '/configuration', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_configuration' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// Premium status endpoint
		register_rest_route( self::NAMESPACE, '/premium-status', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_premium_status' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// Bulk operations endpoints
		register_rest_route( self::NAMESPACE, '/orders/bulk-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_update_orders' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/bulk-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_update_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/bulk-stock-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_update_stock' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Batch processing endpoints for optimized bulk operations
		register_rest_route( self::NAMESPACE, '/orders/batch-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_update_orders' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/batch-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_update_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/orders/batch-status-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_update_order_status' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/batch-status-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_update_product_status' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/batch-stock-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_update_product_stock' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Batch loading endpoints for initial data fetch
		register_rest_route( self::NAMESPACE, '/orders/batch-get', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_get_orders' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/batch-get', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_get_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Batch delete endpoints for bulk operations
		register_rest_route( self::NAMESPACE, '/orders/batch-delete', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_delete_orders' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/batch-delete', [
			'methods' => 'POST',
			'callback' => [ $this, 'batch_delete_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Search endpoints
		register_rest_route( self::NAMESPACE, '/search/orders', [
			'methods' => 'GET',
			'callback' => [ $this, 'search_orders' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		register_rest_route( self::NAMESPACE, '/search/products', [
			'methods' => 'GET',
			'callback' => [ $this, 'search_products' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// Export endpoints
		register_rest_route( self::NAMESPACE, '/export/orders', [
			'methods' => 'GET',
			'callback' => [ $this, 'export_orders' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		register_rest_route( self::NAMESPACE, '/export/products', [
			'methods' => 'GET',
			'callback' => [ $this, 'export_products' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		register_rest_route( self::NAMESPACE, '/export/vendors', [
			'methods' => 'GET',
			'callback' => [ $this, 'export_vendors' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// Order creation endpoint
		register_rest_route( self::NAMESPACE, '/orders', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_order' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		// Product creation endpoint
		register_rest_route( self::NAMESPACE, '/products', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Customer endpoints
		register_rest_route( self::NAMESPACE, '/customers', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_customers' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		// Order helper endpoints
		register_rest_route( self::NAMESPACE, '/order-statuses', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_order_statuses' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/payment-methods', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_payment_methods' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		// Countries and states endpoints
		register_rest_route( self::NAMESPACE, '/countries', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_countries' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		register_rest_route( self::NAMESPACE, '/states', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_states' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// Product categories, tags, attributes
		register_rest_route( self::NAMESPACE, '/product-categories', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product_categories' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/product-tags', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product_tags' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/product-attributes', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product_attributes' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Bulk operations
		register_rest_route( self::NAMESPACE, '/orders/bulk-status-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_update_order_status' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/bulk-status-update', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_update_product_status' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Media enqueue endpoint
		register_rest_route( self::NAMESPACE, '/media/enqueue', [
			'methods' => 'POST',
			'callback' => [ $this, 'enqueue_media_scripts' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);

		// WooCommerce Products endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/products', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/woocommerce/products/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/woocommerce/products', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_woocommerce_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/woocommerce/products/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_woocommerce_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/woocommerce/products/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_woocommerce_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WooCommerce Categories endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/products/categories', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_categories' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Categories CRUD endpoints
		register_rest_route( self::NAMESPACE, '/categories', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_categories' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/categories', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_category' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/categories/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_category' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/categories/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_category' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/categories/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_category' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Tags CRUD endpoints
		register_rest_route( self::NAMESPACE, '/tags', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_tags' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/tags', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_tag' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/tags/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_tag' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/tags/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_tag' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/tags/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_tag' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Brands CRUD endpoints
		register_rest_route( self::NAMESPACE, '/brands', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_brands' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/brands', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_brand' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/brands/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_brand' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/brands/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_brand' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/brands/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_brand' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Attributes CRUD endpoints
		register_rest_route( self::NAMESPACE, '/attributes', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_attributes' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_attribute' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_attribute' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_attribute' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_attribute' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Attribute Terms endpoints
		register_rest_route( self::NAMESPACE, '/attributes/(?P<attribute_id>\d+)/terms', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_attribute_terms' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes/(?P<attribute_id>\d+)/terms', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_attribute_term' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes/(?P<attribute_id>\d+)/terms/(?P<term_id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_attribute_term' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/attributes/(?P<attribute_id>\d+)/terms/(?P<term_id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_attribute_term' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Reviews endpoints
		register_rest_route( self::NAMESPACE, '/reviews', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_reviews' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/reviews/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_review' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/reviews/(?P<id>\d+)/status', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_review_status' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/reviews/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_review' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/reviews/(?P<id>\d+)/reply', [
			'methods' => 'POST',
			'callback' => [ $this, 'reply_to_review' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/reviews/settings', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_review_settings' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/reviews/settings', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_review_settings' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WooCommerce Tags endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/products/tags', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_tags' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WooCommerce Attributes endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/products/attributes', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_attributes' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WooCommerce Shipping Classes endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/products/shipping_classes', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_shipping_classes' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WooCommerce Tax Classes endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/taxes/classes', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_tax_classes' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WordPress Media endpoints
		register_rest_route( self::NAMESPACE, '/wordpress/media', [
			'methods' => 'POST',
			'callback' => [ $this, 'upload_wordpress_media' ],
			'permission_callback' => [ $this, 'check_media_authentication' ],
		]);

		// Missing endpoints for frontend functionality

		// Get single product endpoint
		register_rest_route( self::NAMESPACE, '/products/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'id' => [
					'required' => true,
					'type' => 'integer',
					'validate_callback' => function ( $param ) {
						return is_numeric( $param ) && $param > 0;
					},
				],
			],
		]);

		// Delete single product endpoint
		register_rest_route( self::NAMESPACE, '/products/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_product' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'id' => [
					'required' => true,
					'type' => 'integer',
					'validate_callback' => function ( $param ) {
						return is_numeric( $param ) && $param > 0;
					},
				],
				'force' => [
					'type' => 'boolean',
					'default' => false,
					'description' => 'Whether to permanently delete the product or move to trash',
				],
			],
		]);

		// Bulk delete products endpoint
		register_rest_route( self::NAMESPACE, '/products/bulk-delete', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_delete_products' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'product_ids' => [
					'required' => true,
					'type' => 'array',
					'items' => [
						'type' => 'integer',
					],
				],
				'force' => [
					'type' => 'boolean',
					'default' => false,
				],
			],
		]);

		// Bulk delete orders endpoint
		register_rest_route( self::NAMESPACE, '/orders/bulk-delete', [
			'methods' => 'POST',
			'callback' => [ $this, 'bulk_delete_orders' ],
			'permission_callback' => [ $this, 'check_orders_permission' ],
			'args' => [
				'order_ids' => [
					'required' => true,
					'type' => 'array',
					'items' => [
						'type' => 'integer',
					],
				],
				'force' => [
					'type' => 'boolean',
					'default' => false,
				],
			],
		]);

		// Product categories creation endpoint
		register_rest_route( self::NAMESPACE, '/product-categories', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_product_category' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'name' => [
					'required' => true,
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'slug' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_title',
				],
				'description' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				],
				'parent' => [
					'type' => 'integer',
					'default' => 0,
				],
			],
		]);

		// Product tags creation endpoint
		register_rest_route( self::NAMESPACE, '/product-tags', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_product_tag' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'name' => [
					'required' => true,
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'slug' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_title',
				],
				'description' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				],
			],
		]);

		// Product image upload endpoint - MOVED TO AJAX FOR NONCE VERIFICATION
		// register_rest_route( self::NAMESPACE, '/products/upload-image', [
		// 'methods' => 'POST',
		// 'callback' => [ $this, 'upload_product_image' ],
		// 'permission_callback' => [ $this, 'check_products_permission' ],
		// ]);

		// Product attributes creation endpoint
		register_rest_route( self::NAMESPACE, '/product-attributes', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_product_attribute' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'name' => [
					'required' => true,
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'slug' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_title',
				],
				'type' => [
					'type' => 'string',
					'default' => 'select',
					'enum' => [ 'select', 'text' ],
				],
			],
		]);

		// Get attribute terms endpoint
		register_rest_route( self::NAMESPACE, '/product-attributes/(?P<id>\d+)/terms', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_attribute_terms' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// Create attribute term endpoint
		register_rest_route( self::NAMESPACE, '/product-attributes/(?P<id>\d+)/terms', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_attribute_term' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'name' => [
					'required' => true,
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'slug' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_title',
				],
			],
		]);

		// Product brands endpoints
		register_rest_route( self::NAMESPACE, '/product-brands', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product_brands' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/product-brands', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_product_brand' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
			'args' => [
				'name' => [
					'required' => true,
					'type' => 'string',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'slug' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_title',
				],
				'description' => [
					'type' => 'string',
					'sanitize_callback' => 'sanitize_textarea_field',
				],
			],
		]);

		// Product variations endpoints
		register_rest_route( self::NAMESPACE, '/products/(?P<product_id>\d+)/variations', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product_variations' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/(?P<product_id>\d+)/variations', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_product_variation' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/(?P<product_id>\d+)/variations/generate', [
			'methods' => 'POST',
			'callback' => [ $this, 'generate_product_variations' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/(?P<product_id>\d+)/variations/(?P<variation_id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_product_variation' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/(?P<product_id>\d+)/variations/(?P<variation_id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_product_variation' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		register_rest_route( self::NAMESPACE, '/products/(?P<product_id>\d+)/variations/(?P<variation_id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_product_variation' ],
			'permission_callback' => [ $this, 'check_products_permission' ],
		]);

		// WooCommerce Analytics endpoints
		register_rest_route( self::NAMESPACE, '/woocommerce/revenue-data', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_revenue_data' ],
			'permission_callback' => [ $this, 'check_authentication' ],
			'args' => [
				'from' => [
					'type' => 'string',
					'format' => 'date',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'to' => [
					'type' => 'string',
					'format' => 'date',
					'sanitize_callback' => 'sanitize_text_field',
				],
			],
		]);

		register_rest_route( self::NAMESPACE, '/woocommerce/top-products', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_woocommerce_top_products' ],
			'permission_callback' => [ $this, 'check_authentication' ],
			'args' => [
				'from' => [
					'type' => 'string',
					'format' => 'date',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'to' => [
					'type' => 'string',
					'format' => 'date',
					'sanitize_callback' => 'sanitize_text_field',
				],
				'limit' => [
					'type' => 'integer',
					'default' => 10,
					'minimum' => 1,
					'maximum' => 50,
				],
			],
		]);

		register_rest_route( self::NAMESPACE, '/sync/status', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_sync_status' ],
			'permission_callback' => [ $this, 'check_authentication' ],
		]);
	}

	/**
	 * Handle user login
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function handle_login( $request ) {
		try {
			$username = $request->get_param( 'username' );
			$password = $request->get_param( 'password' );
			$remember = $request->get_param( 'remember' );

			$result = $this->auth_manager->authenticate_user( $username, $password, $remember );

			if ( $result instanceof AuthenticationException ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => $result->get_user_message(),
					'code' => $result->getCode(),
				], 401 );
			}

			return new \WP_REST_Response( $result, 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Login failed. Please try again.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Handle user logout
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function handle_logout( $request ) {
		wp_logout();
		$this->auth_manager->clear_session_data();

		return new \WP_REST_Response( [
			'success' => true,
			'message' => __( 'Logged out successfully.', 'shop-explorer' ),
		], 200 );
	}

	/**
	 * Get current user data
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_current_user( $request ) {
		$user = $this->auth_manager->get_current_user();

		if ( ! $user ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'User not authenticated.', 'shop-explorer' ),
			], 401 );
		}

		return new \WP_REST_Response( [
			'success' => true,
			'user' => [
				'id' => $user->ID,
				'username' => $user->user_login,
				'email' => $user->user_email,
				'display_name' => $user->display_name,
				'roles' => $user->roles,
				'capabilities' => [
					'manage_orders' => current_user_can( AuthenticationManager::CAPABILITY_MANAGE_ORDERS ),
					'manage_products' => current_user_can( AuthenticationManager::CAPABILITY_MANAGE_PRODUCTS ),
					'manage_vendors' => current_user_can( AuthenticationManager::CAPABILITY_MANAGE_VENDORS ),
					'manage_settings' => current_user_can( AuthenticationManager::CAPABILITY_MANAGE_SETTINGS ),
				],
				'is_vendor' => $this->auth_manager->is_vendor_user(),
				'vendor_id' => $this->auth_manager->get_vendor_id(),
			],
		], 200 );
	}

	/**
	 * Get settings
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_settings( $request ) {
		try {
			// Get WooCommerce settings
			$woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
			if ( is_string( $woo_settings ) ) {
				$woo_settings = json_decode( $woo_settings, true );
			}
			if ( ! is_array( $woo_settings ) ) {
				$woo_settings = [];
			}

			$settings = [
				'database_mode_enabled' => $this->settings_manager->get_setting( 'database_mode_enabled' ),
				'multivendor_enabled' => $this->settings_manager->get_setting( 'multivendor_enabled' ),
				'auto_sync_enabled' => $this->settings_manager->get_setting( 'auto_sync_enabled' ),
				'sync_interval' => $this->settings_manager->get_setting( 'sync_interval' ),
				'batch_size' => $this->settings_manager->get_setting( 'batch_size' ),
				'email_notifications' => $this->settings_manager->get_setting( 'email_notifications' ),
				'notification_email' => $this->settings_manager->get_setting( 'notification_email' ),
				// Export/Sync Settings
				'sync_orders' => $this->settings_manager->get_setting( 'sync_orders', true ),
				'sync_products' => $this->settings_manager->get_setting( 'sync_products', true ),
				'sync_customers' => $this->settings_manager->get_setting( 'sync_customers', false ),
				'sync_success_notifications' => $this->settings_manager->get_setting( 'sync_success_notifications', false ),
				'sync_error_notifications' => $this->settings_manager->get_setting( 'sync_error_notifications', true ),
				// WooCommerce Analytics Settings
				'wooanalytics' => isset( $woo_settings['wooanalytics'] ) ? $woo_settings['wooanalytics'] : false,
				'incomplete_orders_tracking' => isset( $woo_settings['incomplete_orders_tracking'] ) ? $woo_settings['incomplete_orders_tracking'] : false,
				'cart_interactions_tracking' => isset( $woo_settings['cart_interactions_tracking'] ) ? $woo_settings['cart_interactions_tracking'] : false,
				'abandonment_delay_minutes' => isset( $woo_settings['abandonment_delay_minutes'] ) ? $woo_settings['abandonment_delay_minutes'] : 5,
				'cleanup_incomplete_orders_days' => isset( $woo_settings['cleanup_incomplete_orders_days'] ) ? $woo_settings['cleanup_incomplete_orders_days'] : 30,
				// Bulk Edit Optimization Settings
				'bulk_edit_optimize_mode' => $this->settings_manager->get_setting( 'bulk_edit_optimize_mode' ),
				'bulk_edit_batch_size' => $this->settings_manager->get_setting( 'bulk_edit_batch_size' ),
				'bulk_edit_threshold' => $this->settings_manager->get_setting( 'bulk_edit_threshold' ),
			];

			return new \WP_REST_Response( [
				'success' => true,
				'settings' => $settings,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to retrieve settings.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Update settings
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_settings( $request ) {
		try {
			$settings = $request->get_json_params();

			if ( empty( $settings ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No settings provided.', 'shop-explorer' ),
				], 400 );
			}

			// error_log( 'Shop Explorer: Updating settings (credentials are handled separately)' );

			// Update each setting
			$setting_map = [
				'database_mode_enabled' => 'database_mode_enabled',
				'multivendor_enabled' => 'multivendor_enabled',
				'auto_sync_enabled' => 'auto_sync_enabled',
				'sync_interval' => 'sync_interval',
				'batch_size' => 'batch_size',
				'email_notifications' => 'email_notifications',
				'notification_email' => 'notification_email',
				// Export/Sync Settings
				'sync_orders' => 'sync_orders',
				'sync_products' => 'sync_products',
				'sync_customers' => 'sync_customers',
				'sync_success_notifications' => 'sync_success_notifications',
				'sync_error_notifications' => 'sync_error_notifications',
				// Bulk Edit Optimization Settings
				'bulk_edit_optimize_mode' => 'bulk_edit_optimize_mode',
				'bulk_edit_batch_size' => 'bulk_edit_batch_size',
				'bulk_edit_threshold' => 'bulk_edit_threshold',
			];

			foreach ( $setting_map as $frontend_key => $backend_key ) {
				if ( isset( $settings[ $frontend_key ] ) ) {
					$this->settings_manager->update_setting( $backend_key, $settings[ $frontend_key ] );
					// error_log( "Shop Explorer: Updated setting {$backend_key}" );
				}
			}

			// Handle WooCommerce settings separately
			$woo_settings_keys = [
				'wooanalytics',
				'incomplete_orders_tracking',
				'cart_interactions_tracking',
				'abandonment_delay_minutes',
				'cleanup_incomplete_orders_days'
			];

			$woo_settings_changed = false;
			$current_woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
			if ( is_string( $current_woo_settings ) ) {
				$current_woo_settings = json_decode( $current_woo_settings, true );
			}
			if ( ! is_array( $current_woo_settings ) ) {
				$current_woo_settings = [];
			}

			foreach ( $woo_settings_keys as $key ) {
				if ( isset( $settings[ $key ] ) ) {
					$current_woo_settings[ $key ] = $settings[ $key ];
					$woo_settings_changed = true;
				}
			}

			if ( $woo_settings_changed ) {
				update_option( 'wpnts_schedules_interval_woocommerce_settings', wp_json_encode( $current_woo_settings ) );
			}

			// Validate the configuration
			$this->settings_manager->validate_configuration();

			// error_log( 'Shop Explorer: Settings update completed successfully' );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Settings updated successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Settings updated failed.', 'shop-explorer' ),
			], 400 );
		}
	}

	/**
	 * Export settings
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function export_settings( $request ) {
		try {
			$settings = $this->settings_manager->export_settings();

			return new \WP_REST_Response( [
				'success' => true,
				'settings' => $settings,
				'filename' => 'shop-explorer-settings-' . gmdate( 'Y-m-d-H-i-s' ) . '.json',
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to export settings.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Import settings
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function import_settings( $request ) {
		try {
			$settings = $request->get_json_params();

			if ( empty( $settings ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No settings data provided.', 'shop-explorer' ),
				], 400 );
			}

			$this->settings_manager->import_settings( $settings );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Settings imported successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Settings imported failed.', 'shop-explorer' ),
			], 400 );
		}
	}

	/**
	 * Reset settings
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function reset_settings( $request ) {
		try {
			$this->settings_manager->reset_to_defaults();

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Settings reset to defaults successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to reset settings.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get orders
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_orders( $request ) {
		try {

			// Check if WooCommerce is available
			if ( ! function_exists( 'wc_get_orders' ) ) {
				// error_log( 'WooCommerce wc_get_orders function not available' );
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$page = $request->get_param( 'page' );
			$per_page = $request->get_param( 'per_page' );
			$status = $request->get_param( 'status' );
			$search = $request->get_param( 'search' );
			$date_from = $request->get_param( 'dateFrom' );
			$date_to = $request->get_param( 'dateTo' );

			$args = [
				'limit' => $per_page,
				'offset' => ( $page - 1 ) * $per_page,
				'return' => 'objects',
				'type' => 'shop_order', // Only get actual orders, not refunds or other types
			];

			if ( $status ) {
				$args['status'] = 'wc-' . $status;
			}

			if ( $search ) {
				$args['s'] = $search;
			}

			// Add date range filter
			if ( $date_from && $date_to ) {
				$args['date_created'] = $date_from . '...' . $date_to;
			} elseif ( $date_from ) {
				$args['date_created'] = '>=' . $date_from;
			} elseif ( $date_to ) {
				$args['date_created'] = '<=' . $date_to;
			}

			$orders = wc_get_orders( $args );

			// Get total count for pagination - use same args but without limit/offset
			$count_args = $args;
			$count_args['limit'] = -1;
			$count_args['offset'] = 0;
			$count_args['return'] = 'ids'; // Just get IDs for counting
			$total_order_ids = wc_get_orders( $count_args );
			$total = is_array( $total_order_ids ) ? count( $total_order_ids ) : 0;

			$formatted_orders = [];
			if ( is_array( $orders ) ) {
				foreach ( $orders as $order ) {
					// Since we're already filtering by type='shop_order', we don't need to check again
					if ( $order && is_object( $order ) ) {
						$formatted_orders[] = [
							'id' => $order->get_id(),
							'number' => $order->get_order_number(),
							'status' => $order->get_status(),
							'date_created' => $order->get_date_created() ? $order->get_date_created()->date( 'Y-m-d H:i:s' ) : '',
							'total' => $order->get_total(),
							'currency' => $order->get_currency(),
							'customer' => [
								'name' => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ),
								'email' => $order->get_billing_email(),
							],
							'items_count' => $order->get_item_count(),
						];
					}
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'orders' => $formatted_orders,
				'total' => $total,
				'pages' => $per_page > 0 ? ceil( $total / $per_page ) : 1,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get single order
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_order( $request ) {
		try {
			$order_id = $request->get_param( 'id' );

			if ( ! function_exists( 'wc_get_order' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$order = wc_get_order( $order_id );

			if ( ! $order ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order not found.', 'shop-explorer' ),
				], 404 );
			}

			// Format order data
			$formatted_order = $this->format_order_data( $order );

			return new \WP_REST_Response( [
				'success' => true,
				'order' => $formatted_order,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Update order
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_order( $request ) {
		try {
			$order_id = $request->get_param( 'id' );
			$order_data = $request->get_json_params();

			if ( ! function_exists( 'wc_get_order' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$order = wc_get_order( $order_id );

			if ( ! $order ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order not found.', 'shop-explorer' ),
				], 404 );
			}

			// Update order data
			$this->update_order_data( $order, $order_data );

			// Save the order
			$order->save();

			// Get updated order data
			$formatted_order = $this->format_order_data( $order );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Order updated successfully.', 'shop-explorer' ),
				'order' => $formatted_order,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Delete order
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_order( $request ) {
		try {
			$order_id = $request->get_param( 'id' );
			$force = $request->get_param( 'force' );

			if ( ! function_exists( 'wc_get_order' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$order = wc_get_order( $order_id );

			if ( ! $order ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order not found.', 'shop-explorer' ),
				], 404 );
			}

			// Store order data before deletion for response
			$order_data = $this->format_order_data( $order );

			// Delete the order
			if ( $force ) {
				// Permanently delete
				$result = $order->delete( true );
			} else {
				// Move to trash
				$result = wp_trash_post( $order_id );
			}

			if ( ! $result ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Failed to delete order.', 'shop-explorer' ),
				], 500 );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => $force ? __( 'Order permanently deleted.', 'shop-explorer' ) : __( 'Order moved to trash.', 'shop-explorer' ),
				'order' => $order_data,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get products
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_products( $request ) {
		try {
			$page = $request->get_param( 'page' );
			$per_page = $request->get_param( 'per_page' );
			$search = $request->get_param( 'search' );
			$status = $request->get_param( 'status' );
			$stock_status = $request->get_param( 'stock_status' );
			$sku = $request->get_param( 'sku' );

			$args = [
				'limit' => $per_page,
				'offset' => ( $page - 1 ) * $per_page,
				'return' => 'objects',
			];

			// Handle status filter
			if ( $status ) {
				$args['status'] = $status;
			} else {
				$args['status'] = [ 'publish', 'draft', 'private' ];
			}

			// Handle search - use 's' parameter for WP_Query compatibility
			if ( $search ) {
				$args['s'] = $search;
			}

			// Handle SKU search (for duplicate checking)
			if ( $sku ) {
				$args['sku'] = $sku;
			}

			// Handle stock status filter
			if ( $stock_status ) {
				$args['stock_status'] = $stock_status;
			}

			$products = wc_get_products( $args );
			$total_products = wc_get_products( array_merge( $args, [
				'limit' => -1,
				'return' => 'ids',
			] ) );
			$total = count( $total_products );

			$formatted_products = [];
			foreach ( $products as $product ) {
				// Get product image
				$image_id = $product->get_image_id();
				$image_url = $image_id ? wp_get_attachment_url( $image_id ) : '';

				$formatted_products[] = [
					'id' => $product->get_id(),
					'name' => $product->get_name(),
					'sku' => $product->get_sku(),
					'price' => $product->get_price(),
					'regular_price' => $product->get_regular_price(),
					'sale_price' => $product->get_sale_price(),
					'stock_status' => $product->get_stock_status(),
					'stock_quantity' => $product->get_stock_quantity(),
					'manage_stock' => $product->get_manage_stock(),
					'type' => $product->get_type(),
					'status' => $product->get_status(),
					'featured' => $product->get_featured(),
					'image' => $image_url,
					'date_created' => $product->get_date_created()->date( 'Y-m-d H:i:s' ),
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'products' => $formatted_products,
				'total' => $total,
				'pages' => ceil( $total / $per_page ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Update product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_product( $request ) {
		try {
			$product_id = $request->get_param( 'id' );
			$product_data = $request->get_json_params();
			
			// Log incoming payload - COMPREHENSIVE
			// error_log( '=== UPDATE PRODUCT PAYLOAD ===' );
			/* error_log( 'Product ID: ' . $product_id );
			error_log( 'Full Payload: ' . wp_json_encode( $product_data, JSON_PRETTY_PRINT ) );
			error_log( '--- Basic Info ---' );
			error_log( 'Name: ' . ( $product_data['name'] ?? 'not set' ) );
			error_log( 'Slug: ' . ( $product_data['slug'] ?? 'not set' ) );
			error_log( 'Type: ' . ( $product_data['type'] ?? 'not set' ) );
			error_log( 'Status: ' . ( $product_data['status'] ?? 'not set' ) );
			error_log( 'Featured: ' . ( isset( $product_data['featured'] ) ? ( $product_data['featured'] ? 'true' : 'false' ) : 'not set' ) );
			error_log( 'Catalog Visibility: ' . ( $product_data['catalog_visibility'] ?? 'not set' ) );
			error_log( '--- Product Flags ---' );
			error_log( 'Virtual: ' . ( isset( $product_data['virtual'] ) ? ( $product_data['virtual'] ? 'true' : 'false' ) : 'not set' ) );
			error_log( 'Downloadable: ' . ( isset( $product_data['downloadable'] ) ? ( $product_data['downloadable'] ? 'true' : 'false' ) : 'not set' ) );
			error_log( '--- Pricing ---' );
			error_log( 'Regular Price: ' . ( $product_data['regular_price'] ?? 'not set' ) );
			error_log( 'Sale Price: ' . ( $product_data['sale_price'] ?? 'not set' ) );
			error_log( 'Tax Status: ' . ( $product_data['tax_status'] ?? 'not set' ) );
			error_log( 'Tax Class: ' . ( $product_data['tax_class'] ?? 'not set' ) );
			error_log( '--- Inventory ---' );
			error_log( 'SKU: ' . ( $product_data['sku'] ?? 'not set' ) );
			error_log( 'Manage Stock: ' . ( isset( $product_data['manage_stock'] ) ? ( $product_data['manage_stock'] ? 'true' : 'false' ) : 'not set' ) );
			error_log( 'Stock Quantity: ' . ( $product_data['stock_quantity'] ?? 'not set' ) );
			error_log( 'Stock Status: ' . ( $product_data['stock_status'] ?? 'not set' ) );
			error_log( 'Backorders: ' . ( $product_data['backorders'] ?? 'not set' ) );
			error_log( 'Sold Individually: ' . ( isset( $product_data['sold_individually'] ) ? ( $product_data['sold_individually'] ? 'true' : 'false' ) : 'not set' ) );
			error_log( '--- Shipping ---' );
			error_log( 'Weight: ' . ( $product_data['weight'] ?? 'not set' ) );
			error_log( 'Length: ' . ( $product_data['length'] ?? 'not set' ) );
			error_log( 'Width: ' . ( $product_data['width'] ?? 'not set' ) );
			error_log( 'Height: ' . ( $product_data['height'] ?? 'not set' ) );
			error_log( 'Shipping Class: ' . ( $product_data['shipping_class'] ?? 'not set' ) );
			error_log( '--- Advanced ---' );
			error_log( 'Purchase Note: ' . ( $product_data['purchase_note'] ?? 'not set' ) );
			error_log( 'Menu Order: ' . ( $product_data['menu_order'] ?? 'not set' ) );
			error_log( 'Enable Reviews: ' . ( isset( $product_data['enable_reviews'] ) ? ( $product_data['enable_reviews'] ? 'true' : 'false' ) : 'not set' ) );
			error_log( '--- Downloadable ---' );
			error_log( 'Download Limit: ' . ( $product_data['download_limit'] ?? 'not set' ) );
			error_log( 'Download Expiry: ' . ( $product_data['download_expiry'] ?? 'not set' ) );
			error_log( 'Downloadable Files Count: ' . ( isset( $product_data['downloadable_files'] ) ? count( $product_data['downloadable_files'] ) : 'not set' ) );
			error_log( '--- Relationships ---' );
			error_log( 'Categories Count: ' . ( isset( $product_data['categories'] ) ? count( $product_data['categories'] ) : 'not set' ) );
			error_log( 'Tags Count: ' . ( isset( $product_data['tags'] ) ? count( $product_data['tags'] ) : 'not set' ) );
			error_log( 'Brands Count: ' . ( isset( $product_data['brands'] ) ? count( $product_data['brands'] ) : 'not set' ) );
			error_log( 'Images Count: ' . ( isset( $product_data['images'] ) ? count( $product_data['images'] ) : 'not set' ) );
			error_log( 'Upsell IDs Count: ' . ( isset( $product_data['upsell_ids'] ) ? count( $product_data['upsell_ids'] ) : 'not set' ) );
			error_log( 'Cross-sell IDs Count: ' . ( isset( $product_data['cross_sell_ids'] ) ? count( $product_data['cross_sell_ids'] ) : 'not set' ) );
			error_log( 'Attributes Count: ' . ( isset( $product_data['attributes'] ) ? count( $product_data['attributes'] ) : 'not set' ) );
			error_log( 'Custom Fields Count: ' . ( isset( $product_data['custom_fields'] ) ? count( $product_data['custom_fields'] ) : 'not set' ) ); */

			if ( ! $product_id ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product ID is required.', 'shop-explorer' ),
				], 400 );
			}

			$product = wc_get_product( $product_id );
			if ( ! $product ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found.', 'shop-explorer' ),
				], 404 );
			}

			// Handle product type change
			if ( isset( $product_data['type'] ) && $product_data['type'] !== $product->get_type() ) {
				$new_type = sanitize_text_field( $product_data['type'] );
				$old_type = $product->get_type();
				
				error_log( "Changing product type from {$old_type} to {$new_type}" );
				
				// Create new product object of the correct type
				switch ( $new_type ) {
					case 'variable':
						$new_product = new \WC_Product_Variable( $product_id );
						break;
					case 'grouped':
						$new_product = new \WC_Product_Grouped( $product_id );
						break;
					case 'external':
						$new_product = new \WC_Product_External( $product_id );
						break;
					case 'simple':
					default:
						$new_product = new \WC_Product_Simple( $product_id );
						break;
				}
				
				// Update the product type in the database
				wp_set_object_terms( $product_id, $new_type, 'product_type' );
				
				// Use the new product object
				$product = $new_product;
				
				// Clear cache to ensure fresh data
				wp_cache_delete( $product_id, 'post_meta' );
				wp_cache_delete( $product_id, 'posts' );
				clean_post_cache( $product_id );
			}

			// Update basic product data
			if ( isset( $product_data['name'] ) ) {
				$product->set_name( sanitize_text_field( $product_data['name'] ) );
			}
			if ( isset( $product_data['slug'] ) ) {
				$product->set_slug( sanitize_title( $product_data['slug'] ) );
			}
			if ( isset( $product_data['description'] ) ) {
				$product->set_description( wp_kses_post( $product_data['description'] ) );
			}
			if ( isset( $product_data['short_description'] ) ) {
				$product->set_short_description( wp_kses_post( $product_data['short_description'] ) );
			}
			if ( isset( $product_data['sku'] ) ) {
				$product->set_sku( sanitize_text_field( $product_data['sku'] ) );
			}
			if ( isset( $product_data['regular_price'] ) ) {
				$product->set_regular_price( $product_data['regular_price'] );
			}
			if ( isset( $product_data['sale_price'] ) ) {
				$product->set_sale_price( $product_data['sale_price'] );
			}
			if ( isset( $product_data['status'] ) ) {
				$product->set_status( sanitize_text_field( $product_data['status'] ) );
			}
			if ( isset( $product_data['featured'] ) ) {
				$product->set_featured( (bool) $product_data['featured'] );
			}
			// Inventory - Set manage_stock first, then quantity, then status
			if ( isset( $product_data['manage_stock'] ) ) {
				$product->set_manage_stock( (bool) $product_data['manage_stock'] );
			}
			if ( isset( $product_data['stock_quantity'] ) ) {
				$product->set_stock_quantity( (int) $product_data['stock_quantity'] );
			}
			if ( isset( $product_data['backorders'] ) ) {
				$product->set_backorders( sanitize_text_field( $product_data['backorders'] ) );
			}
			if ( isset( $product_data['low_stock_amount'] ) ) {
				$product->set_low_stock_amount( $product_data['low_stock_amount'] );
			}
			if ( isset( $product_data['sold_individually'] ) ) {
				$product->set_sold_individually( (bool) $product_data['sold_individually'] );
			}
			// Set stock_status LAST - WooCommerce may override it based on quantity
			// We'll force it again after save if needed
			if ( isset( $product_data['stock_status'] ) ) {
				$product->set_stock_status( sanitize_text_field( $product_data['stock_status'] ) );
			}
			
			// Virtual and Downloadable
			if ( isset( $product_data['virtual'] ) ) {
				$product->set_virtual( (bool) $product_data['virtual'] );
			}
			if ( isset( $product_data['downloadable'] ) ) {
				$product->set_downloadable( (bool) $product_data['downloadable'] );
			}
			
			// Tax options
			if ( isset( $product_data['tax_status'] ) ) {
				$product->set_tax_status( sanitize_text_field( $product_data['tax_status'] ) );
			}
			if ( isset( $product_data['tax_class'] ) ) {
				$product->set_tax_class( sanitize_text_field( $product_data['tax_class'] ) );
			}
			
			// Shipping
			if ( isset( $product_data['weight'] ) ) {
				$product->set_weight( $product_data['weight'] );
			}
			if ( isset( $product_data['dimensions'] ) ) {
				$dimensions = $product_data['dimensions'];
				if ( isset( $dimensions['length'] ) ) {
					$product->set_length( $dimensions['length'] );
				}
				if ( isset( $dimensions['width'] ) ) {
					$product->set_width( $dimensions['width'] );
				}
				if ( isset( $dimensions['height'] ) ) {
					$product->set_height( $dimensions['height'] );
				}
			}
			if ( isset( $product_data['shipping_class'] ) ) {
				$shipping_class = sanitize_text_field( $product_data['shipping_class'] );
				// error_log( 'Shipping Class Input: ' . $shipping_class );
				if ( ! empty( $shipping_class ) ) {
					// Get shipping class term by slug
					$term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
					if ( $term ) {
						// error_log( 'Shipping Class Found - ID: ' . $term->term_id . ', Name: ' . $term->name );
						$product->set_shipping_class_id( $term->term_id );
					} else {
						// If it's numeric, assume it's an ID
						if ( is_numeric( $shipping_class ) ) {
							// error_log( 'Shipping Class is numeric ID: ' . $shipping_class );
							$product->set_shipping_class_id( (int) $shipping_class );
						} else {
							// error_log( 'Shipping Class NOT FOUND: ' . $shipping_class . ' - Setting to 0' );
							$product->set_shipping_class_id( 0 );
						}
					}
				} else {
					// error_log( 'Shipping Class is empty - Setting to 0' );
					$product->set_shipping_class_id( 0 );
				}
			}
			
			// Advanced options
			if ( isset( $product_data['catalog_visibility'] ) ) {
				$product->set_catalog_visibility( sanitize_text_field( $product_data['catalog_visibility'] ) );
			}
			if ( isset( $product_data['reviews_allowed'] ) || isset( $product_data['enable_reviews'] ) ) {
				$reviews_allowed = $product_data['reviews_allowed'] ?? $product_data['enable_reviews'] ?? true;
				$product->set_reviews_allowed( (bool) $reviews_allowed );
			}
			if ( isset( $product_data['purchase_note'] ) ) {
				$product->set_purchase_note( wp_kses_post( $product_data['purchase_note'] ) );
			}
			if ( isset( $product_data['menu_order'] ) ) {
				$product->set_menu_order( (int) $product_data['menu_order'] );
			}
			
			// Sale price dates
			if ( isset( $product_data['date_on_sale_from'] ) ) {
				$product->set_date_on_sale_from( $product_data['date_on_sale_from'] );
			}
			if ( isset( $product_data['date_on_sale_to'] ) ) {
				$product->set_date_on_sale_to( $product_data['date_on_sale_to'] );
			}

			// Handle images
			if ( isset( $product_data['images'] ) && is_array( $product_data['images'] ) ) {
				$image_ids = [];
				foreach ( $product_data['images'] as $image ) {
					if ( isset( $image['id'] ) && is_numeric( $image['id'] ) ) {
						$image_ids[] = (int) $image['id'];
					}
				}
				$product->set_image_id( isset( $image_ids[0] ) ? $image_ids[0] : '' );
				$product->set_gallery_image_ids( array_slice( $image_ids, 1 ) );
			}

			// Handle categories - always set even if empty array
			if ( isset( $product_data['categories'] ) ) {
				if ( is_array( $product_data['categories'] ) ) {
					$category_ids = [];
					foreach ( $product_data['categories'] as $category ) {
						if ( isset( $category['id'] ) ) {
							$category_ids[] = (int) $category['id'];
						}
					}
					$product->set_category_ids( $category_ids );
				}
			}

			// Handle tags - always set even if empty array
			if ( isset( $product_data['tags'] ) ) {
				if ( is_array( $product_data['tags'] ) ) {
					$tag_ids = [];
					foreach ( $product_data['tags'] as $tag ) {
						if ( isset( $tag['id'] ) ) {
							$tag_ids[] = (int) $tag['id'];
						}
					}
					$product->set_tag_ids( $tag_ids );
				}
			}

			// Handle upsell_ids
			if ( isset( $product_data['upsell_ids'] ) ) {
				if ( is_array( $product_data['upsell_ids'] ) ) {
					$upsell_ids = array_map( function( $item ) {
						return is_array( $item ) && isset( $item['id'] ) ? (int) $item['id'] : (int) $item;
					}, $product_data['upsell_ids'] );
					$product->set_upsell_ids( array_filter( $upsell_ids ) );
				}
			}
			
			// Handle cross_sell_ids
			if ( isset( $product_data['cross_sell_ids'] ) ) {
				if ( is_array( $product_data['cross_sell_ids'] ) ) {
					$cross_sell_ids = array_map( function( $item ) {
						return is_array( $item ) && isset( $item['id'] ) ? (int) $item['id'] : (int) $item;
					}, $product_data['cross_sell_ids'] );
					$product->set_cross_sell_ids( array_filter( $cross_sell_ids ) );
				}
			}
			
			// Handle downloadable files
			if ( isset( $product_data['downloadable_files'] ) && is_array( $product_data['downloadable_files'] ) ) {
				$downloads = [];
				foreach ( $product_data['downloadable_files'] as $file ) {
					if ( isset( $file['name'] ) && isset( $file['file'] ) && ! empty( $file['file'] ) ) {
						$download = new \WC_Product_Download();
						$download_id = isset( $file['id'] ) && ! empty( $file['id'] ) ? $file['id'] : md5( $file['file'] );
						$download->set_id( $download_id );
						$download->set_name( sanitize_text_field( $file['name'] ) );
						$download->set_file( esc_url_raw( $file['file'] ) );
						$downloads[ $download->get_id() ] = $download;
					}
				}
				$product->set_downloads( $downloads );
			}
			
			// Handle download limit and expiry
			if ( isset( $product_data['download_limit'] ) ) {
				$product->set_download_limit( (int) $product_data['download_limit'] );
			}
			if ( isset( $product_data['download_expiry'] ) ) {
				$product->set_download_expiry( (int) $product_data['download_expiry'] );
			}
			
			// Handle attributes
			if ( isset( $product_data['attributes'] ) && is_array( $product_data['attributes'] ) ) {
				$attributes = [];
				foreach ( $product_data['attributes'] as $attribute_data ) {
					// Skip if attribute data is invalid
					if ( ! is_array( $attribute_data ) ) {
						continue;
					}
					
					$attribute = new \WC_Product_Attribute();
					$attribute_id = isset( $attribute_data['id'] ) ? (int) $attribute_data['id'] : 0;
					
					if ( $attribute_id > 0 ) {
						// Global attribute
						$attribute->set_id( $attribute_id );
						$attribute_name = wc_attribute_taxonomy_name_by_id( $attribute_id );
						$attribute->set_name( $attribute_name );
						
						// For global attributes, we need to ensure terms exist and get their IDs
						$term_ids = [];
						if ( isset( $attribute_data['options'] ) && is_array( $attribute_data['options'] ) ) {
							foreach ( $attribute_data['options'] as $option_value ) {
								// Check if term exists
								$term = get_term_by( 'name', $option_value, $attribute_name );
								if ( ! $term ) {
									// Create the term if it doesn't exist
									$term_data = wp_insert_term( $option_value, $attribute_name );
									if ( ! is_wp_error( $term_data ) ) {
										$term_ids[] = $term_data['term_id'];
									}
								} else {
									$term_ids[] = $term->term_id;
								}
							}
						}
						$attribute->set_options( $term_ids );
						
						// error_log( 'Global Attribute: ' . $attribute_name . ' with term IDs: ' . wp_json_encode( $term_ids ) );
					} elseif ( isset( $attribute_data['name'] ) ) {
						// Custom attribute - options are just strings
						$attribute->set_name( $attribute_data['name'] );
						$attribute->set_options( $attribute_data['options'] ?? [] );
						
						// error_log( 'Custom Attribute: ' . $attribute_data['name'] . ' with options: ' . wp_json_encode( $attribute_data['options'] ?? [] ) );
					} else {
						// Skip if no name
						continue;
					}
					
					$attribute->set_visible( $attribute_data['visible'] ?? true );
					$attribute->set_variation( $attribute_data['variation'] ?? false );
					
					$attributes[] = $attribute;
				}
				$product->set_attributes( $attributes );
			}

			$product->save();
			
			// Log after first save - COMPREHENSIVE
			/* error_log( '=== AFTER FIRST SAVE ===' );
			error_log( 'Type: ' . $product->get_type() );
			error_log( 'Status: ' . $product->get_status() );
			error_log( 'Virtual: ' . ( $product->get_virtual() ? 'true' : 'false' ) );
			error_log( 'Downloadable: ' . ( $product->get_downloadable() ? 'true' : 'false' ) );
			error_log( 'Regular Price: ' . $product->get_regular_price() );
			error_log( 'Sale Price: ' . $product->get_sale_price() );
			error_log( 'Stock Status: ' . $product->get_stock_status() );
			error_log( 'Stock Quantity: ' . $product->get_stock_quantity() );
			error_log( 'Manage Stock: ' . ( $product->get_manage_stock() ? 'true' : 'false' ) ); */
			
			// Clear cache after save
			wp_cache_delete( $product_id, 'post_meta' );
			wp_cache_delete( $product_id, 'posts' );
			clean_post_cache( $product_id );

			// Handle brands (after save since it's a custom taxonomy) - always set even if empty array
			if ( isset( $product_data['brands'] ) ) {
				if ( is_array( $product_data['brands'] ) ) {
					$brand_ids = [];
					foreach ( $product_data['brands'] as $brand ) {
						if ( is_array( $brand ) ) {
							$brand_ids[] = (int) ( $brand['term_id'] ?? $brand['id'] ?? 0 );
						} else {
							$brand_ids[] = (int) $brand;
						}
					}

					// Find the brand taxonomy
					$brand_taxonomies = [
						'product_brand',
						'product_brands',
						'pwb-brand',
						'yith_product_brand',
						'berocket_brand',
						'brand',
						'brands',
						'shopex_product_brand',
					];

					$brand_taxonomy = null;
					foreach ( $brand_taxonomies as $taxonomy ) {
						if ( taxonomy_exists( $taxonomy ) ) {
							$brand_taxonomy = $taxonomy;
							break;
						}
					}

					if ( $brand_taxonomy ) {
						wp_set_object_terms( $product_id, array_filter( $brand_ids ), $brand_taxonomy, false );
					}
				}
			}
			
			// Handle custom fields / meta data
			if ( isset( $product_data['meta_data'] ) && is_array( $product_data['meta_data'] ) ) {
				foreach ( $product_data['meta_data'] as $meta ) {
					if ( isset( $meta['key'] ) && isset( $meta['value'] ) ) {
						update_post_meta( $product_id, $meta['key'], $meta['value'] );
					}
				}
			}
			
			// Handle custom_fields (alternative format)
			if ( isset( $product_data['custom_fields'] ) ) {
				// First, remove ALL existing custom fields (including configs and corrupted data)
				global $wpdb;
				$wpdb->query( $wpdb->prepare(
					"DELETE FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key LIKE '_custom_%%'",
					$product_id
				) );
				
				// Clear WordPress meta cache after SQL DELETE
				wp_cache_delete( $product_id, 'post_meta' );
				
				// Then add the new custom fields
				if ( is_array( $product_data['custom_fields'] ) && ! empty( $product_data['custom_fields'] ) ) {
					foreach ( $product_data['custom_fields'] as $field ) {
						if ( isset( $field['key'] ) ) {
							// Skip if field key contains "field_config" (corrupted data from frontend)
							if ( strpos( $field['key'], 'field_config' ) !== false ) {
								continue;
							}
							
							$meta_key = '_custom_' . $field['key'];
							$field_value = isset( $field['value'] ) ? sanitize_text_field( $field['value'] ) : '';
							
							// Always save the field (even if empty)
							update_post_meta( $product_id, $meta_key, $field_value );
							
							// Save field configuration (type, editable, etc.)
							$field_config = [
								'type' => $field['type'] ?? 'text',
								'editable' => isset( $field['editable'] ) && $field['editable'],
							];
							update_post_meta( $product_id, '_custom_field_config_' . $field['key'], $field_config );
						}
					}
				}
			}

			// Reload product to get fresh data after all updates
			wp_cache_delete( $product_id, 'post_meta' );
			wp_cache_delete( $product_id, 'posts' );
			$product = wc_get_product( $product_id );
			
			// Re-apply virtual and downloadable using direct meta update (bypass WooCommerce sync)
			if ( isset( $product_data['virtual'] ) ) {
				update_post_meta( $product_id, '_virtual', $product_data['virtual'] ? 'yes' : 'no' );
			}
			if ( isset( $product_data['downloadable'] ) ) {
				update_post_meta( $product_id, '_downloadable', $product_data['downloadable'] ? 'yes' : 'no' );
			}
			
			// Force stock_status if provided - WooCommerce may have overridden it based on quantity
			if ( isset( $product_data['stock_status'] ) ) {
				update_post_meta( $product_id, '_stock_status', sanitize_text_field( $product_data['stock_status'] ) );
				// error_log( 'Forcing stock_status to: ' . $product_data['stock_status'] );
			}
			
			// For variable products, save prices as meta (they don't use regular WC price fields)
			if ( $product->get_type() === 'variable' ) {
				if ( isset( $product_data['regular_price'] ) && $product_data['regular_price'] !== '' ) {
					update_post_meta( $product_id, '_regular_price', $product_data['regular_price'] );
				}
				if ( isset( $product_data['sale_price'] ) && $product_data['sale_price'] !== '' ) {
					update_post_meta( $product_id, '_sale_price', $product_data['sale_price'] );
				}
			}
			
			// Final cache clear and reload
			wp_cache_delete( $product_id, 'post_meta' );
			wp_cache_delete( $product_id, 'posts' );
			$product = wc_get_product( $product_id );
			
			// Log final state - COMPREHENSIVE
			/* error_log( '=== FINAL STATE AFTER SAVE ===' );
			error_log( '--- Basic Info ---' );
			error_log( 'Name: ' . $product->get_name() );
			error_log( 'Slug: ' . $product->get_slug() );
			error_log( 'Type: ' . $product->get_type() );
			error_log( 'Status: ' . $product->get_status() );
			error_log( 'Featured: ' . ( $product->get_featured() ? 'true' : 'false' ) );
			error_log( 'Catalog Visibility: ' . $product->get_catalog_visibility() );
			error_log( '--- Product Flags ---' );
			error_log( 'Virtual: ' . ( $product->get_virtual() ? 'true' : 'false' ) );
			error_log( 'Downloadable: ' . ( $product->get_downloadable() ? 'true' : 'false' ) );
			error_log( '--- Pricing ---' );
			error_log( 'Regular Price: ' . $product->get_regular_price() );
			error_log( 'Sale Price: ' . $product->get_sale_price() );
			error_log( 'Tax Status: ' . $product->get_tax_status() );
			error_log( 'Tax Class: ' . $product->get_tax_class() );
			error_log( '--- Inventory ---' );
			error_log( 'SKU: ' . $product->get_sku() );
			error_log( 'Manage Stock: ' . ( $product->get_manage_stock() ? 'true' : 'false' ) );
			error_log( 'Stock Quantity: ' . $product->get_stock_quantity() );
			error_log( 'Stock Status: ' . $product->get_stock_status() );
			error_log( 'Backorders: ' . $product->get_backorders() );
			error_log( 'Sold Individually: ' . ( $product->get_sold_individually() ? 'true' : 'false' ) );
			error_log( '--- Shipping ---' );
			error_log( 'Weight: ' . $product->get_weight() );
			error_log( 'Length: ' . $product->get_length() );
			error_log( 'Width: ' . $product->get_width() );
			error_log( 'Height: ' . $product->get_height() );
			error_log( 'Shipping Class ID: ' . $product->get_shipping_class_id() );
			error_log( '--- Advanced ---' );
			error_log( 'Purchase Note: ' . $product->get_purchase_note() );
			error_log( 'Menu Order: ' . $product->get_menu_order() );
			error_log( 'Reviews Allowed: ' . ( $product->get_reviews_allowed() ? 'true' : 'false' ) );
			error_log( '--- Downloadable ---' );
			error_log( 'Download Limit: ' . $product->get_download_limit() );
			error_log( 'Download Expiry: ' . $product->get_download_expiry() );
			error_log( 'Downloads Count: ' . count( $product->get_downloads() ) );
			error_log( '--- Relationships ---' );
			error_log( 'Category IDs: ' . wp_json_encode( $product->get_category_ids() ) );
			error_log( 'Tag IDs: ' . wp_json_encode( $product->get_tag_ids() ) );
			error_log( 'Image ID: ' . $product->get_image_id() );
			error_log( 'Gallery Image IDs: ' . wp_json_encode( $product->get_gallery_image_ids() ) );
			error_log( 'Upsell IDs: ' . wp_json_encode( $product->get_upsell_ids() ) );
			error_log( 'Cross-sell IDs: ' . wp_json_encode( $product->get_cross_sell_ids() ) );
			error_log( 'Attributes Count: ' . count( $product->get_attributes() ) ); */
			
			// Return updated product data
			$updated_product = $this->format_product_data( $product );
			
			/* error_log( '=== RESPONSE DATA ===' );
			error_log( 'Response Product: ' . wp_json_encode( $updated_product, JSON_PRETTY_PRINT ) ); */

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Product updated successfully.', 'shop-explorer' ),
				'product' => $updated_product,
				'product_url' => get_permalink( $product_id ),
				'edit_url' => get_edit_post_link( $product_id, 'raw' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get single product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_product( $request ) {
		try {
			$product_id = $request->get_param( 'id' );
			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found.', 'shop-explorer' ),
				], 404 );
			}

			$formatted_product = $this->format_product_data( $product );

			return new \WP_REST_Response( [
				'success' => true,
				'product' => $formatted_product,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Delete single product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_product( $request ) {
		try {
			$product_id = $request->get_param( 'id' );
			$force = $request->get_param( 'force' );

			$product = wc_get_product( $product_id );
			if ( ! $product ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found.', 'shop-explorer' ),
				], 404 );
			}

			if ( $force ) {
				$result = $product->delete( true );
			} else {
				$product->set_status( 'trash' );
				$result = $product->save();
			}

			if ( ! $result ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Failed to delete product.', 'shop-explorer' ),
				], 500 );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => $force ? __( 'Product deleted permanently.', 'shop-explorer' ) : __( 'Product moved to trash.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Bulk delete products
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function bulk_delete_products( $request ) {
		try {
			$product_ids = $request->get_param( 'product_ids' );
			$force = $request->get_param( 'force' );

			if ( empty( $product_ids ) || ! is_array( $product_ids ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product IDs are required.', 'shop-explorer' ),
				], 400 );
			}

			$deleted_count = 0;
			$errors = [];

			foreach ( $product_ids as $product_id ) {
				$product = wc_get_product( $product_id );
				if ( ! $product ) {
					/* translators: %d: is the product id */
					$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
					continue;
				}

				try {
					if ( $force ) {
						$result = $product->delete( true );
					} else {
						$product->set_status( 'trash' );
						$result = $product->save();
					}

					if ( $result ) {
						$deleted_count++;
					} else {
						/* translators: %d: is the product id */
						$errors[] = sprintf( __( 'Failed to delete product %d.', 'shop-explorer' ), $product_id );
					}
				} catch ( \Exception $e ) {
					return false;
				}
			}

			$message = $force
				/* translators: %d: is the delete count */
				? sprintf( __( '%d products deleted permanently.', 'shop-explorer' ), $deleted_count )
				/* translators: %s: is the product id */
				: sprintf( __( '%d products moved to trash.', 'shop-explorer' ), $deleted_count );

			if ( ! empty( $errors ) ) {
				$message .= ' ' . __( 'Some products could not be deleted.', 'shop-explorer' );
			}

			return new \WP_REST_Response( [
				'success' => $deleted_count > 0,
				'message' => $message,
				'deleted_count' => $deleted_count,
				'errors' => $errors,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Bulk delete orders
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function bulk_delete_orders( $request ) {
		try {
			$order_ids = $request->get_param( 'order_ids' );
			$force = $request->get_param( 'force' );

			if ( empty( $order_ids ) || ! is_array( $order_ids ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order IDs are required.', 'shop-explorer' ),
				], 400 );
			}

			$deleted_count = 0;
			$errors = [];

			foreach ( $order_ids as $order_id ) {
				$order = wc_get_order( $order_id );
				if ( ! $order ) {
					/* translators: %s: is the product id */
					$errors[] = sprintf( __( 'Order %d not found.', 'shop-explorer' ), $order_id );
					continue;
				}

				try {
					if ( $force ) {
						$result = $order->delete( true );
					} else {
						$order->set_status( 'trash' );
						$result = $order->save();
					}

					if ( $result ) {
						$deleted_count++;
					} else {
						/* translators: %s: is the product id */
						$errors[] = sprintf( __( 'Failed to delete order %d.', 'shop-explorer' ), $order_id );
					}
				} catch ( \Exception $e ) {
					return false;
				}
			}

			$message = $force
			/* translators: %s: is the product id */
				? sprintf( __( '%d orders deleted permanently.', 'shop-explorer' ), $deleted_count )
				/* translators: %s: is the product id */
				: sprintf( __( '%d orders moved to trash.', 'shop-explorer' ), $deleted_count );

			if ( ! empty( $errors ) ) {
				$message .= ' ' . __( 'Some orders could not be deleted.', 'shop-explorer' );
			}

			return new \WP_REST_Response( [
				'success' => $deleted_count > 0,
				'message' => $message,
				'deleted_count' => $deleted_count,
				'errors' => $errors,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create product category
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_product_category( $request ) {
		try {
			$name = $request->get_param( 'name' );
			$slug = $request->get_param( 'slug' );
			$description = $request->get_param( 'description' );
			$parent = $request->get_param( 'parent' );

			if ( empty( $name ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Category name is required.', 'shop-explorer' ),
				], 400 );
			}

			$args = [
				'name' => $name,
				'description' => $description ?: '',
				'parent' => $parent ?: 0,
			];

			if ( $slug ) {
				$args['slug'] = $slug;
			}

			$result = wp_insert_term( $name, 'product_cat', $args );

			if ( is_wp_error( $result ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => $result->get_error_message(),
				], 400 );
			}

			$term = get_term( $result['term_id'], 'product_cat' );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Category created successfully.', 'shop-explorer' ),
				'data' => [
					'id' => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
					'description' => $term->description,
					'parent' => $term->parent,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create product tag
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_product_tag( $request ) {
		try {
			$name = $request->get_param( 'name' );
			$slug = $request->get_param( 'slug' );
			$description = $request->get_param( 'description' );

			if ( empty( $name ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Tag name is required.', 'shop-explorer' ),
				], 400 );
			}

			$args = [
				'name' => $name,
				'description' => $description ?: '',
			];

			if ( $slug ) {
				$args['slug'] = $slug;
			}

			$result = wp_insert_term( $name, 'product_tag', $args );

			if ( is_wp_error( $result ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => $result->get_error_message(),
				], 400 );
			}

			$term = get_term( $result['term_id'], 'product_tag' );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Tag created successfully.', 'shop-explorer' ),
				'data' => [
					'id' => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
					'description' => $term->description,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Upload product image
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function upload_product_image( $request ) {
		try {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
			if ( empty( $_FILES['file'] ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No file uploaded.', 'shop-explorer' ),
				], 400 );
			}

			// Sanitize file data before use
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
			$file = array(
				'name'     => isset( $_FILES['file']['name'] ) ? sanitize_file_name( $_FILES['file']['name'] ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
				'type'     => isset( $_FILES['file']['type'] ) ? sanitize_mime_type( $_FILES['file']['type'] ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
				'tmp_name' => isset( $_FILES['file']['tmp_name'] ) ? sanitize_text_field( $_FILES['file']['tmp_name'] ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
				'error'    => isset( $_FILES['file']['error'] ) ? absint( $_FILES['file']['error'] ) : 0, // phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
				'size'     => isset( $_FILES['file']['size'] ) ? absint( $_FILES['file']['size'] ) : 0, // phpcs:ignore WordPress.Security.NonceVerification.Missing -- REST API endpoint with permission_callback
			);

			// Check for upload errors
			if ( $file['error'] !== UPLOAD_ERR_OK ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'File upload error.', 'shop-explorer' ),
				], 400 );
			}

			// Check file type
			$allowed_types = [ 'image/jpeg', 'image/png', 'image/gif', 'image/webp' ];
			if ( ! in_array( $file['type'], $allowed_types, true ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Invalid file type. Only images are allowed.', 'shop-explorer' ),
				], 400 );
			}

			// Validate file is actually an image
			$file_info = getimagesize( $file['tmp_name'] );
			if ( false === $file_info ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Invalid image file.', 'shop-explorer' ),
				], 400 );
			}

			// Upload file
			require_once ABSPATH . 'wp-admin/includes/file.php';
			require_once ABSPATH . 'wp-admin/includes/media.php';
			require_once ABSPATH . 'wp-admin/includes/image.php';

			$attachment_id = media_handle_sideload( $file, 0 );

			if ( is_wp_error( $attachment_id ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => $attachment_id->get_error_message(),
				], 500 );
			}

			$attachment_url = wp_get_attachment_url( $attachment_id );
			$attachment_alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
			$attachment_title = get_the_title( $attachment_id );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Image uploaded successfully.', 'shop-explorer' ),
				'attachment_id' => $attachment_id,
				'url' => $attachment_url,
				'alt' => $attachment_alt,
				'title' => $attachment_title,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to upload image.', 'shop-explorer' ),
			], 500 );
		}
	}


	/**
	 * Sync orders
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function sync_orders( $request ) {
		// Sync functionality has been removed
		return new \WP_REST_Response( [
			'success' => false,
			'message' => __( 'Sync functionality is no longer available.', 'shop-explorer' ),
		], 501 );
	}

	/**
	 * Sync products
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function sync_products( $request ) {
		// Sync functionality has been removed
		return new \WP_REST_Response( [
			'success' => false,
			'message' => __( 'Sync functionality is no longer available.', 'shop-explorer' ),
		], 501 );
	}

	/**
	 * Get dashboard statistics
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_dashboard_stats( $request ) {
		try {
			// Get order statistics
			$order_stats = $this->get_order_statistics();

			// Get product statistics
			$product_stats = $this->get_product_statistics();

			// Get revenue statistics
			$revenue_stats = $this->get_revenue_statistics();

			// Get vendor statistics if multivendor is enabled
			$vendor_stats = [];
			if ( get_option( 'shopex_multivendor_enabled', false ) ) {
				$vendor_stats = $this->get_vendor_statistics();
			}

			$stats = [
				'orders' => array_merge( $order_stats, [
					'revenue' => $revenue_stats['total'],
					'growth' => $revenue_stats['growth'],
				] ),
				'products' => $product_stats,
				'vendors' => $vendor_stats,
			];

			return new \WP_REST_Response( [
				'success' => true,
				'stats' => $stats,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get recent activity
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_recent_activity( $request ) {
		try {
			if ( ! function_exists( 'wc_get_orders' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$activity = [];

			// Get recent orders (last 7 days)
			$recent_orders = wc_get_orders( [
				'limit' => 8,
				'orderby' => 'date',
				'order' => 'DESC',
				'type' => 'shop_order',
				'date_created' => '>=' . gmdate( 'Y-m-d', strtotime( '-7 days' ) ),
			] );

			foreach ( $recent_orders as $order ) {
				if ( ! method_exists( $order, 'get_order_number' ) ) {
					continue;
				}
				
				$status = $order->get_status();
				$status_label = wc_get_order_status_name( $status );
				
				$activity[] = [
					'type' => 'order',
					'title' => sprintf( 
						__( 'Order #%s %s (%s)', 'shop-explorer' ), 
						$order->get_order_number(),
						$status === 'completed' ? 'completed' : ($status === 'processing' ? 'is processing' : 'created'),
						html_entity_decode( wp_strip_all_tags( $order->get_formatted_order_total() ), ENT_QUOTES, 'UTF-8' )
					),
					'time' => $order->get_date_created()->date( 'Y-m-d H:i:s' ),
					'link' => admin_url( 'post.php?post=' . $order->get_id() . '&action=edit' ),
				];
			}

			// Get recently modified products (last 3 days)
			$recent_products = wc_get_products( [
				'limit' => 5,
				'orderby' => 'date_modified',
				'order' => 'DESC',
				'date_modified' => '>=' . gmdate( 'Y-m-d', strtotime( '-3 days' ) ),
			] );

			foreach ( $recent_products as $product ) {
				$activity[] = [
					'type' => 'product',
					'title' => sprintf( 
						__( 'Product "%s" updated', 'shop-explorer' ), 
						wp_trim_words( $product->get_name(), 6, '...' )
					),
					'time' => $product->get_date_modified()->date( 'Y-m-d H:i:s' ),
					'link' => admin_url( 'post.php?post=' . $product->get_id() . '&action=edit' ),
				];
			}

			// Get low stock products
			$low_stock_products = wc_get_products( [
				'limit' => 3,
				'stock_status' => 'instock',
				'meta_query' => [
					[
						'key' => '_manage_stock',
						'value' => 'yes',
					],
				],
			] );

			foreach ( $low_stock_products as $product ) {
				$stock_quantity = $product->get_stock_quantity();
				$low_stock_amount = $product->get_low_stock_amount();
				
				if ( $stock_quantity !== null && $low_stock_amount !== null && $stock_quantity <= $low_stock_amount ) {
					$activity[] = [
						'type' => 'product',
						'title' => sprintf( 
							__( 'Low stock alert: "%s" (%d remaining)', 'shop-explorer' ), 
							wp_trim_words( $product->get_name(), 5, '...' ),
							$stock_quantity
						),
						'time' => $product->get_date_modified()->date( 'Y-m-d H:i:s' ),
						'link' => admin_url( 'post.php?post=' . $product->get_id() . '&action=edit' ),
					];
				}
			}

			// Sort by time (most recent first)
			usort( $activity, function ( $a, $b ) {
				return strtotime( $b['time'] ) - strtotime( $a['time'] );
			});

			// Return only the 10 most recent activities
			return new \WP_REST_Response( [
				'success' => true,
				'activity' => array_slice( $activity, 0, 10 ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to load recent activity.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get sync status
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_sync_status( $request ) {
		$status = [
			'isRunning' => false,
			'lastSync' => get_option( 'shopex_last_sync', null ),
			'pendingOperations' => 0,
		];

		return new \WP_REST_Response( [
			'success' => true,
			'status' => $status,
		], 200 );
	}

	/**
	 * Get configuration
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_configuration( $request ) {
		$config = [
			'database_mode_enabled' => get_option( 'shopex_database_mode_enabled', true ),
			'multivendor_enabled' => get_option( 'shopex_multivendor_enabled', false ),
		];

		return new \WP_REST_Response( [
			'success' => true,
			'config' => $config,
		], 200 );
	}

	/**
	 * Get premium status
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_premium_status( $request ) {
		$has_premium = false;
		$license_info = null;

		// Check if Freemius is available and user has premium license
		if ( function_exists( 'shopex_get_freemius_instance' ) ) {
			$fs = shopex_get_freemius_instance();
			if ( $fs && method_exists( $fs, 'has_active_valid_license' ) ) {
				$has_premium = $fs->has_active_valid_license();
				if ( $has_premium && method_exists( $fs, '_get_license' ) ) {
					$license_info = $fs->_get_license();
				}
			}
		}

		// Check if Pro version is active
		if ( ! $has_premium && is_plugin_active( 'shop-explorer-pro/shop-explorer-pro.php' ) ) {
			$has_premium = true;
		}

		return new \WP_REST_Response( [
			'success' => true,
			'has_premium' => $has_premium,
			'license_info' => $license_info,
		], 200 );
	}

	/**
	 * Get monitoring dashboard data
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_monitoring_dashboard( $request ) {
		try {
			// Get actual system metrics
			$memory_limit = $this->get_memory_limit();
			$memory_usage = memory_get_usage( true );
			$memory_percentage = $memory_limit > 0 ? round( ( $memory_usage / $memory_limit ) * 100, 1 ) : 0;

			// Check database connection
			$db_connected = $this->check_database_connection();

			// Get sync statistics (placeholder for now)
			$sync_stats = $this->get_sync_statistics();

			// Get error summary (placeholder for now)
			$error_summary = $this->get_error_summary();

			// Get recent alerts (placeholder for now)
			$recent_alerts = $this->get_recent_alerts();

			$dashboard_data = [
				'sync_status' => $sync_stats,
				'error_summary' => $error_summary,
				'system_health' => [
					'memory_usage' => $memory_percentage,
					'disk_usage' => $this->get_disk_usage(),
					'database_connected' => $db_connected,
				],
				'recent_alerts' => $recent_alerts,
				'performance_metrics' => [
					'average_response_time' => $this->get_average_response_time(),
					'peak_memory_usage' => memory_get_peak_usage( true ),
					'cache_hit_rate' => $this->get_cache_hit_rate(),
				],
			];

			return new \WP_REST_Response( [
				'success' => true,
				'data' => $dashboard_data,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get order statistics
	 *
	 * @return array
	 */
	private function get_order_statistics() {
		// Use WooCommerce functions for HPOS compatibility
		$statuses = [ 'pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed' ];

		$stats = [
			'total' => 0,
			'pending' => 0,
			'processing' => 0,
			'completed' => 0,
		];

		foreach ( $statuses as $status ) {
			$count = wc_orders_count( $status );
			$stats['total'] += $count;

			if ( isset( $stats[ $status ] ) ) {
				$stats[ $status ] = $count;
			}
		}

		return $stats;
	}

	/**
	 * Get product statistics
	 *
	 * @return array
	 */
	private function get_product_statistics() {
		// Use WooCommerce functions for better compatibility
		$products = wc_get_products( [
			'status' => 'publish',
			'limit' => -1,
			'return' => 'objects',
		] );

		$stats = [
			'total' => count( $products ),
			'in_stock' => 0,
			'out_of_stock' => 0,
			'low_stock' => 0,
		];

		foreach ( $products as $product ) {
			$stock_status = $product->get_stock_status();

			if ( $stock_status === 'instock' ) {
				$stats['in_stock']++;
			} elseif ( $stock_status === 'outofstock' ) {
				$stats['out_of_stock']++;
			}

			// Check for low stock
			if ( $product->get_manage_stock() && $product->get_stock_quantity() <= get_option( 'woocommerce_notify_low_stock_amount', 2 ) ) {
				$stats['low_stock']++;
			}
		}

		return $stats;
	}

	/**
	 * Get revenue statistics
	 *
	 * @return array
	 */
	private function get_revenue_statistics() {
		// Get this month's orders
		$current_month_start = gmdate( 'Y-m-01' );
		$current_month_end = gmdate( 'Y-m-t' );

		$current_orders = wc_get_orders( [
			'status' => [ 'completed', 'processing' ],
			'date_created' => $current_month_start . '...' . $current_month_end,
			'limit' => -1,
		] );

		$current_revenue = 0;
		foreach ( $current_orders as $order ) {
			$current_revenue += $order->get_total();
		}

		// Get last month's orders for growth calculation
		$last_month_start = gmdate( 'Y-m-01', strtotime( '-1 month' ) );
		$last_month_end = gmdate( 'Y-m-t', strtotime( '-1 month' ) );

		$last_orders = wc_get_orders( [
			'status' => [ 'completed', 'processing' ],
			'date_created' => $last_month_start . '...' . $last_month_end,
			'limit' => -1,
		] );

		$last_revenue = 0;
		foreach ( $last_orders as $order ) {
			$last_revenue += $order->get_total();
		}

		$growth = 0;
		if ( $last_revenue > 0 ) {
			$growth = ( ( $current_revenue - $last_revenue ) / $last_revenue ) * 100;
		}

		return [
			'total' => $current_revenue,
			'growth' => round( $growth, 1 ),
		];
	}

	/**
	 * Check authentication
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_authentication( $request ) {
		return is_user_logged_in() && current_user_can( 'manage_options' );
	}

	/**
	 * Check orders permission
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_orders_permission( $request ) {
		// For debugging, let's be more permissive and log the check
		$can_manage_wc = current_user_can( 'manage_woocommerce' );
		$can_edit_orders = current_user_can( 'edit_shop_orders' );
		$can_manage_options = current_user_can( 'manage_options' );
		$is_logged_in = is_user_logged_in();

		return $is_logged_in && ( $can_manage_wc || $can_edit_orders || $can_manage_options );
	}

	/**
	 * Check products permission
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_products_permission( $request ) {
		return is_user_logged_in() && ( current_user_can( 'manage_woocommerce' ) || current_user_can( 'edit_products' ) );
	}

	/**
	 * Check frontend access permission (more permissive for reading settings)
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_frontend_access_permission( $request ) {
		// Allow any logged-in user to read frontend settings
		return is_user_logged_in();
	}

	/**
	 * Check manage settings permission with nonce validation
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_manage_settings_permission( $request ) {
		// Check user capability
		if ( ! current_user_can( 'manage_options' ) ) {
			return false;
		}

		return is_user_logged_in();
	}

	/**
	 * Check manage orders permission
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_manage_orders_permission( $request ) {
		return is_user_logged_in() && ( current_user_can( 'manage_woocommerce' ) || current_user_can( 'edit_shop_orders' ) || current_user_can( 'manage_options' ) );
	}

	/**
	 * Get memory limit in bytes
	 *
	 * @return int
	 */
	private function get_memory_limit() {
		$memory_limit = ini_get( 'memory_limit' );
		if ( $memory_limit === '-1' ) {
			return 0; // Unlimited
		}

		$unit = strtolower( substr( $memory_limit, -1 ) );
		$value = (int) $memory_limit;

		switch ( $unit ) {
			case 'g':
				$value *= 1024 * 1024 * 1024;
				break;
			case 'm':
				$value *= 1024 * 1024;
				break;
			case 'k':
				$value *= 1024;
				break;
		}

		return $value;
	}

	/**
	 * Get disk usage percentage
	 *
	 * @return float
	 */
	private function get_disk_usage() {
		$upload_dir = wp_upload_dir();
		$path = $upload_dir['basedir'];

		if ( function_exists( 'disk_free_space' ) && function_exists( 'disk_total_space' ) ) {
			$free_space = disk_free_space( $path );
			$total_space = disk_total_space( $path );

			if ( $free_space !== false && $total_space !== false && $total_space > 0 ) {
				$used_space = $total_space - $free_space;
				return round( ( $used_space / $total_space ) * 100, 1 );
			}
		}

		return 0;
	}

	/**
	 * Check database connection
	 *
	 * @return bool
	 */
	private function check_database_connection() {
		global $wpdb;

		try {
			$wpdb->get_var( 'SELECT 1' );
			return true;
		} catch ( \Exception $e ) {
			return false;
		}
	}

	/**
	 * Check Google Sheets connection
	 *
	 * @return bool
	 */
	/**
	 * Get sync statistics
	 *
	 * @return array
	 */
	private function get_sync_statistics() {
		// This would get actual sync statistics from the database
		// For now, return sample data
		return [
			'started' => 5,
			'completed' => 4,
			'failed' => 1,
		];
	}

	/**
	 * Get error summary
	 *
	 * @return array
	 */
	private function get_error_summary() {
		// This would get actual error counts from logs
		// For now, return sample data
		return [
			'errors_24h' => 2,
			'warnings_24h' => 5,
		];
	}

	/**
	 * Get recent alerts
	 *
	 * @return array
	 */
	private function get_recent_alerts() {
		// This would get actual alerts from the monitoring system
		// For now, return sample data
		return [
			[
				'type' => 'sync_warning',
				'timestamp' => current_time( 'mysql' ),
				'data' => [ 'message' => 'Sync operation took longer than expected' ],
			],
			[
				'type' => 'memory_warning',
				'timestamp' => gmdate( 'Y-m-d H:i:s', strtotime( '-1 hour' ) ),
				'data' => [ 'message' => 'Memory usage is approaching limit' ],
			],
		];
	}

	/**
	 * Get average response time
	 *
	 * @return float
	 */
	private function get_average_response_time() {
		// This would calculate actual response times
		// For now, return a sample value
		return 150.5;
	}

	/**
	 * Get cache hit rate
	 *
	 * @return float
	 */
	private function get_cache_hit_rate() {
		// This would get actual cache statistics
		// For now, return a sample value
		return 85.2;
	}

	/**
	 * Get vendor statistics
	 *
	 * @return array
	 */
	private function get_vendor_statistics() {
		$stats = [
			'total' => 0,
			'active' => 0,
			'pending' => 0,
		];

		// Check if Dokan is active
		if ( class_exists( 'WeDevs_Dokan' ) ) {
			$vendors = dokan_get_sellers();
			$stats['total'] = count( $vendors );

			foreach ( $vendors as $vendor ) {
				$vendor_info = dokan_get_store_info( $vendor->ID );
				if ( isset( $vendor_info['enabled'] ) && $vendor_info['enabled'] ) {
					$stats['active']++;
				} else {
					$stats['pending']++;
				}
			}
		}
		// Check if WCFM is active
		elseif ( class_exists( 'WCFMmp' ) ) {
			global $wpdb;
			$vendors = $wpdb->get_results( "SELECT * FROM {$wpdb->usermeta} WHERE meta_key = 'wcfm_membership'" );
			$stats['total'] = count( $vendors );
			$stats['active'] = count( $vendors ); // Assume all are active for now
		}

		return $stats;
	}

	/**
	 * Get vendors
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_vendors( $request ) {
		try {
			$page = $request->get_param( 'page' );
			$per_page = $request->get_param( 'per_page' );

			$vendors = [];
			$total = 0;

			// Check if Dokan is active
			if ( class_exists( 'WeDevs_Dokan' ) ) {
				$dokan_vendors = dokan_get_sellers( [
					'number' => $per_page,
					'offset' => ( $page - 1 ) * $per_page,
				] );

				foreach ( $dokan_vendors as $vendor ) {
					$vendor_info = dokan_get_store_info( $vendor->ID );
					$vendors[] = [
						'id' => $vendor->ID,
						'name' => $vendor->display_name,
						'email' => $vendor->user_email,
						'store_name' => $vendor_info['store_name'] ?? '',
						'status' => ( $vendor_info['enabled'] ?? false ) ? 'active' : 'pending',
						'products_count' => count( dokan_get_products_by_seller( $vendor->ID ) ),
					];
				}

				$total = dokan_get_sellers( [ 'count' => true ] );
			}
			// Check if WCFM is active
			elseif ( class_exists( 'WCFMmp' ) ) {
				global $WCFM, $WCFMmp;

				$vendor_args = [
					'role' => 'wcfm_vendor',
					'number' => $per_page,
					'offset' => ( $page - 1 ) * $per_page,
				];

				$vendor_query = new \WP_User_Query( $vendor_args );
				$wcfm_vendors = $vendor_query->get_results();

				foreach ( $wcfm_vendors as $vendor ) {
					$vendors[] = [
						'id' => $vendor->ID,
						'name' => $vendor->display_name,
						'email' => $vendor->user_email,
						'store_name' => get_user_meta( $vendor->ID, 'wcfmmp_store_name', true ),
						'status' => 'active',
						'products_count' => count( wc_get_products( [ 'author' => $vendor->ID ] ) ),
					];
				}

				$total_query = new \WP_User_Query( [
					'role' => 'wcfm_vendor',
					'count_total' => true,
				] );
				$total = $total_query->get_total();
			}

			return new \WP_REST_Response( [
				'success' => true,
				'vendors' => $vendors,
				'total' => $total,
				'pages' => ceil( $total / $per_page ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get single vendor
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_vendor( $request ) {
		$vendor_id = $request->get_param( 'id' );

		try {
			$vendor = get_userdata( $vendor_id );

			if ( ! $vendor ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Vendor not found.', 'shop-explorer' ),
				], 404 );
			}

			$vendor_data = [
				'id' => $vendor->ID,
				'name' => $vendor->display_name,
				'email' => $vendor->user_email,
				'status' => 'active',
			];

			// Add plugin-specific data
			if ( class_exists( 'WeDevs_Dokan' ) ) {
				$vendor_info = dokan_get_store_info( $vendor->ID );
				$vendor_data['store_name'] = $vendor_info['store_name'] ?? '';
				$vendor_data['status'] = ( $vendor_info['enabled'] ?? false ) ? 'active' : 'pending';
			} elseif ( class_exists( 'WCFMmp' ) ) {
				$vendor_data['store_name'] = get_user_meta( $vendor->ID, 'wcfmmp_store_name', true );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'vendor' => $vendor_data,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create vendor
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_vendor( $request ) {
		// This will be implemented based on the multivendor plugin
		return new \WP_REST_Response( [
			'success' => true,
			'message' => __( 'Vendor creation not yet implemented.', 'shop-explorer' ),
		], 200 );
	}

	/**
	 * Update vendor
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_vendor( $request ) {
		// This will be implemented based on the multivendor plugin
		return new \WP_REST_Response( [
			'success' => true,
			'message' => __( 'Vendor updated successfully.', 'shop-explorer' ),
		], 200 );
	}

	/**
	 * Delete vendor
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_vendor( $request ) {
		// This will be implemented based on the multivendor plugin
		return new \WP_REST_Response( [
			'success' => true,
			'message' => __( 'Vendor deleted successfully.', 'shop-explorer' ),
		], 200 );
	}

	/**
	 * Get Google Sheets authorization URL
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_google_sheets_auth( $request ) {
		try {
			// Check if Google Client library is available
			if ( ! class_exists( 'Google_Client' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Client library not found. Please run "composer install" in the plugin directory to install required dependencies.', 'shop-explorer' ),
					'needs_composer' => true,
				], 500 );
			}

			// Check if Google Sheets classes are loaded
			if ( ! class_exists( '\SHOPEXPLORER\GoogleSheets\SHOPEX_GoogleSheetsAuth' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Sheets integration classes not loaded. Please check plugin installation.', 'shop-explorer' ),
				], 500 );
			}

			$auth_manager = new \SHOPEXPLORER\GoogleSheets\SHOPEX_GoogleSheetsAuth();

			// Check if credentials are set
			if ( ! $auth_manager->has_credentials() ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google OAuth credentials not configured. Please upload credentials first.', 'shop-explorer' ),
					'needs_credentials' => true,
				], 400 );
			}

			$auth_url = $auth_manager->get_authorization_url();

			return new \WP_REST_Response( [
				'success' => true,
				'auth_url' => $auth_url,
				'message' => __( 'Authorization URL generated successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Authorize Google Sheets
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function authorize_google_sheets( $request ) {
		try {
			// Check if Google Client library is available
			if ( ! class_exists( 'Google_Client' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Client library not found. Please run "composer install" in the plugin directory.', 'shop-explorer' ),
					'needs_composer' => true,
				], 500 );
			}

			// Check if Google Sheets classes are loaded
			if ( ! class_exists( '\SHOPEXPLORER\GoogleSheets\SHOPEX_GoogleSheetsAuth' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Sheets integration classes not loaded.', 'shop-explorer' ),
				], 500 );
			}

			$code = $request->get_param( 'code' );
			$credentials_json = $request->get_param( 'credentials' );

			if ( empty( $code ) && empty( $credentials_json ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Authorization code or credentials required.', 'shop-explorer' ),
				], 400 );
			}

			$auth_manager = new \SHOPEXPLORER\GoogleSheets\SHOPEX_GoogleSheetsAuth();

			// If credentials are provided, set them first
			if ( ! empty( $credentials_json ) ) {
				$credentials = json_decode( $credentials_json, true );
				if ( json_last_error() !== JSON_ERROR_NONE ) {
					return new \WP_REST_Response( [
						'success' => false,
						'message' => __( 'Invalid JSON credentials format.', 'shop-explorer' ),
					], 400 );
				}
				$auth_manager->set_credentials( $credentials );
			}

			// If authorization code is provided, handle OAuth callback
			if ( ! empty( $code ) ) {
				$auth_manager->handle_oauth_callback( $code );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Google Sheets authorized successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Revoke Google Sheets authorization
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function revoke_google_sheets_auth( $request ) {
		try {
			$auth_manager = new SHOPEX_ServiceAccountAuth();
			$auth_manager->revoke_authentication();

			// Also clear any sheet configurations
			$settings_manager = new SHOPEX_SettingsManager();
			$settings_manager->update_setting( 'sheets_config', [
				'orders_sheet_name' => 'Orders',
				'products_sheet_name' => 'Products',
				'vendors_sheet_name' => 'Vendors',
			] );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Google Sheets credentials removed successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Test Google Sheets connection
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function test_google_sheets_connection( $request ) {
		try {
			$auth_manager = new SHOPEX_ServiceAccountAuth();

			// Check if credentials exist
			if ( ! $auth_manager->has_credentials() ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No service account credentials configured. Please upload your service account JSON file first.', 'shop-explorer' ),
				], 400 );
			}

			// Step 1: Generate access token
			$access_token = $auth_manager->get_access_token();

			if ( ! $access_token ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Failed to generate access token. Please check your service account credentials.', 'shop-explorer' ),
				], 500 );
			}

			// Step 2: Test basic authentication
			$test_result = $auth_manager->test_authentication();

			if ( ! $test_result ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Authentication failed. Please verify that your service account has Google Sheets API access enabled.', 'shop-explorer' ),
				], 500 );
			}

			// Step 3: If spreadsheet URL is provided, test access to that specific sheet
			$spreadsheet_url = $request->get_param( 'spreadsheet_url' );
			if ( ! $spreadsheet_url ) {
				// Try to get from settings
				$spreadsheet_url = $this->settings_manager->get_setting( 'spreadsheet_url' );
			}

			if ( $spreadsheet_url ) {
				// Extract spreadsheet ID from URL
				preg_match( '/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/', $spreadsheet_url, $matches );
				$spreadsheet_id = $matches[1] ?? null;

				if ( $spreadsheet_id ) {
					// Test actual access to the spreadsheet
					$sheet_access_test = $this->test_sheet_access_internal( $spreadsheet_id, $access_token );

					if ( ! $sheet_access_test['success'] ) {
						return new \WP_REST_Response( [
							'success' => false,
							'message' => $sheet_access_test['message'],
							'service_account_email' => $auth_manager->get_service_account_email(),
						], 403 );
					}
				}
			}

			// All tests passed
			$service_email = $auth_manager->get_service_account_email();
			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Google Sheets connection test successful.', 'shop-explorer' ),
				'service_account_email' => $service_email,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Connection test failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Internal method to test sheet access
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $access_token Access token
	 * @return array
	 */
	private function test_sheet_access_internal( $spreadsheet_id, $access_token ) {
		// Try to get spreadsheet metadata
		$url = 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheet_id;

		$response = wp_remote_get( $url, [
			'headers' => [
				'Authorization' => 'Bearer ' . $access_token,
			],
			'timeout' => 30,
		] );

		if ( is_wp_error( $response ) ) {
			return [
				'success' => false,
				'message' => __( 'Failed to connect to Google Sheets API: ', 'shop-explorer' ) . $response->get_error_message(),
			];
		}

		$response_code = wp_remote_retrieve_response_code( $response );
		$response_body = wp_remote_retrieve_body( $response );

		if ( $response_code === 403 ) {
			return [
				'success' => false,
				'message' => __( 'Access denied. Please make sure you have shared the Google Sheet with the service account email and given it "Editor" access.', 'shop-explorer' ),
			];
		}

		if ( $response_code === 404 ) {
			return [
				'success' => false,
				'message' => __( 'Spreadsheet not found. Please check the Google Sheets URL is correct.', 'shop-explorer' ),
			];
		}

		if ( $response_code !== 200 ) {
			$error_data = json_decode( $response_body, true );
			$error_message = $error_data['error']['message'] ?? __( 'Unknown error', 'shop-explorer' );

			return [
				'success' => false,
				'message' => __( 'Failed to access spreadsheet: ', 'shop-explorer' ) . $error_message,
			];
		}

		// Success - we can access the spreadsheet
		return [
			'success' => true,
			'message' => __( 'Successfully accessed the spreadsheet.', 'shop-explorer' ),
		];
	}

	/**
	 * Upload Google Sheets credentials
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function upload_google_sheets_credentials( $request ) {
		try {
			$credentials_json = $request->get_param( 'credentials' );

			if ( empty( $credentials_json ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Credentials JSON is required.', 'shop-explorer' ),
				], 400 );
			}

			// error_log( 'Shop Explorer: Received credentials JSON of length: ' . strlen( $credentials_json ) );

			$credentials = json_decode( $credentials_json, true );
			if ( json_last_error() !== JSON_ERROR_NONE ) {
				// error_log( 'Shop Explorer: JSON decode error: ' . json_last_error_msg() );
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Invalid JSON credentials format.', 'shop-explorer' ),
				], 400 );
			}

			// error_log( 'Shop Explorer: Credentials decoded successfully for: ' . ( $credentials['client_email'] ?? 'unknown' ) );

			$auth_manager = new SHOPEX_ServiceAccountAuth();
			$auth_manager->set_credentials( $credentials );

			// Verify credentials were stored
			if ( $auth_manager->has_credentials() ) {
				// error_log( 'Shop Explorer: Credentials stored and verified successfully' );
			} else {
				// error_log( 'Shop Explorer: Warning - Credentials may not have been stored properly' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Service account credentials uploaded successfully.', 'shop-explorer' ),
				'service_account_email' => $credentials['client_email'] ?? null,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get Google Spreadsheets
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_google_spreadsheets( $request ) {
		try {
			// Check if Google Client library is available
			if ( ! class_exists( 'Google_Client' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Client library not found. Please run "composer install" in the plugin directory.', 'shop-explorer' ),
					'needs_composer' => true,
				], 500 );
			}

			// Check if Google Sheets classes are loaded
			if ( ! class_exists( '\SHOPEXPLORER\GoogleSheets\GoogleSheetsManager' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Sheets integration classes not loaded.', 'shop-explorer' ),
				], 500 );
			}

			$sheets_manager = new \SHOPEXPLORER\GoogleSheets\GoogleSheetsManager();

			if ( ! $sheets_manager->is_authenticated() ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Sheets not authenticated.', 'shop-explorer' ),
				], 401 );
			}

			// Get configured spreadsheet IDs from settings
			$settings_manager = new SHOPEX_SettingsManager();
			$sheets_config = $settings_manager->get_setting( 'sheets_config', [] );

			$spreadsheets = [];

			if ( ! empty( $sheets_config['orders_spreadsheet_id'] ) ) {
				try {
					$metadata = $sheets_manager->get_spreadsheet_metadata( $sheets_config['orders_spreadsheet_id'] );
					$spreadsheets['orders'] = $metadata;
				} catch ( \Exception $e ) {
					// Spreadsheet might not exist or be accessible
				}
			}

			if ( ! empty( $sheets_config['products_spreadsheet_id'] ) ) {
				try {
					$metadata = $sheets_manager->get_spreadsheet_metadata( $sheets_config['products_spreadsheet_id'] );
					$spreadsheets['products'] = $metadata;
				} catch ( \Exception $e ) {
					// Spreadsheet might not exist or be accessible
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'spreadsheets' => $spreadsheets,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create Google Spreadsheet
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_google_spreadsheet( $request ) {
		try {
			// Check if Google Client library is available
			if ( ! class_exists( 'Google_Client' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Client library not found. Please run "composer install" in the plugin directory.', 'shop-explorer' ),
					'needs_composer' => true,
				], 500 );
			}

			// Check if Google Sheets classes are loaded
			if ( ! class_exists( '\SHOPEXPLORER\GoogleSheets\GoogleSheetsManager' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Sheets integration classes not loaded.', 'shop-explorer' ),
				], 500 );
			}

			$title = $request->get_param( 'title' );
			$type = $request->get_param( 'type' ); // 'orders', 'products', or 'vendors'

			if ( empty( $title ) || empty( $type ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Title and type are required.', 'shop-explorer' ),
				], 400 );
			}

			$sheets_manager = new \SHOPEXPLORER\GoogleSheets\GoogleSheetsManager();

			if ( ! $sheets_manager->is_authenticated() ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Google Sheets not authenticated.', 'shop-explorer' ),
				], 401 );
			}

			// Define headers based on type
			$headers = [];
			switch ( $type ) {
				case 'orders':
					$headers = [ 'Order ID', 'Date', 'Status', 'Customer', 'Email', 'Total', 'Items' ];
					break;
				case 'products':
					$headers = [ 'Product ID', 'Name', 'SKU', 'Price', 'Stock', 'Status' ];
					break;
				case 'vendors':
					$headers = [ 'Vendor ID', 'Name', 'Email', 'Products', 'Orders', 'Commission' ];
					break;
				default:
					$headers = [ 'ID', 'Name', 'Status', 'Date' ];
			}

			$sheets_config = [
				[
					'title' => ucfirst( $type ),
					'headers' => $headers,
				],
			];

			$spreadsheet_id = $sheets_manager->create_spreadsheet( $title, $sheets_config );

			// Save spreadsheet ID to settings
			$settings_manager = new SHOPEX_SettingsManager();
			$current_config = $settings_manager->get_setting( 'sheets_config', [] );
			$current_config[ $type . '_spreadsheet_id' ] = $spreadsheet_id;
			$settings_manager->update_setting( 'sheets_config', $current_config );

			return new \WP_REST_Response( [
				'success' => true,
				'spreadsheet_id' => $spreadsheet_id,
				'message' => __( 'Spreadsheet created successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Test sheet access
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function test_sheet_access( $request ) {
		try {
			$spreadsheet_url = $request->get_param( 'spreadsheet_url' );
			$sheet_name = $request->get_param( 'sheet_name' ) ?: 'Sheet1';

			// error_log( 'Shop Explorer: Testing sheet access - URL: ' . $spreadsheet_url . ', Sheet: ' . $sheet_name );

			if ( empty( $spreadsheet_url ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Spreadsheet URL is required.', 'shop-explorer' ),
				], 400 );
			}

			// Extract spreadsheet ID from URL
			$spreadsheet_id = $this->extract_spreadsheet_id( $spreadsheet_url );

			if ( ! $spreadsheet_id ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Invalid Google Sheets URL format.', 'shop-explorer' ),
				], 400 );
			}

			$auth_manager = new SHOPEX_ServiceAccountAuth();

			if ( ! $auth_manager->has_credentials() ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Service account not authenticated. Please upload credentials first.', 'shop-explorer' ),
				], 401 );
			}

			// Test sheet access using our SHOPEX_ServiceAccountAuth class
			$has_access = $auth_manager->test_spreadsheet_access( $spreadsheet_id );

			if ( $has_access ) {
				return new \WP_REST_Response( [
					'success' => true,
					'message' => __( 'Sheet access verified successfully.', 'shop-explorer' ),
					'spreadsheet_id' => $spreadsheet_id,
					'sheet_name' => $sheet_name,
				], 200 );
			} else {
				$service_email = $auth_manager->get_service_account_email();

				return new \WP_REST_Response( [
					'success' => false,
					'message' => sprintf(
						/* translators: %s: is the service email */
						__( 'Cannot access the sheet. Please ensure the service account email (%s) has Editor access to the spreadsheet.', 'shop-explorer' ),
						$service_email
					),
					'service_account_email' => $service_email,
				], 403 );
			}
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Configure sheet
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function configure_sheet( $request ) {
		try {
			$spreadsheet_url = $request->get_param( 'spreadsheet_url' );
			$sheet_name = $request->get_param( 'sheet_name' ) ?: 'Sheet1';
			$sheet_type = $request->get_param( 'sheet_type' ); // 'orders', 'products', 'vendors'

			if ( empty( $spreadsheet_url ) || empty( $sheet_type ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Spreadsheet URL and sheet type are required.', 'shop-explorer' ),
				], 400 );
			}

			// Extract spreadsheet ID from URL
			$spreadsheet_id = \SHOPEXPLORER\GoogleSheets\SimpleGoogleSheetsManager::extract_spreadsheet_id( $spreadsheet_url );

			if ( ! $spreadsheet_id ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Invalid Google Sheets URL format.', 'shop-explorer' ),
				], 400 );
			}

			$sheets_manager = new \SHOPEXPLORER\GoogleSheets\SimpleGoogleSheetsManager();

			if ( ! $sheets_manager->is_authenticated() ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Service account not authenticated.', 'shop-explorer' ),
				], 401 );
			}

			// Test access first
			if ( ! $sheets_manager->test_sheet_access( $spreadsheet_id, $sheet_name ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Cannot access the sheet. Please check permissions.', 'shop-explorer' ),
				], 403 );
			}

			// Define headers based on type
			$headers = [];
			switch ( $sheet_type ) {
				case 'orders':
					$headers = [ 'Order ID', 'Date', 'Status', 'Customer', 'Email', 'Total', 'Items' ];
					break;
				case 'products':
					$headers = [ 'Product ID', 'Name', 'SKU', 'Price', 'Stock', 'Status' ];
					break;
				case 'vendors':
					$headers = [ 'Vendor ID', 'Name', 'Email', 'Products', 'Orders', 'Commission' ];
					break;
				default:
					$headers = [ 'ID', 'Name', 'Status', 'Date' ];
			}

			// Initialize sheet with headers
			$success = $sheets_manager->initialize_sheet_headers( $spreadsheet_id, $sheet_name, $headers );

			if ( $success ) {
				// Save configuration to settings
				$settings_manager = new SHOPEX_SettingsManager();
				$current_config = $settings_manager->get_setting( 'sheets_config', [] );
				$current_config[ $sheet_type . '_spreadsheet_url' ] = $spreadsheet_url;
				$current_config[ $sheet_type . '_spreadsheet_id' ] = $spreadsheet_id;
				$current_config[ $sheet_type . '_sheet_name' ] = $sheet_name;
				$settings_manager->update_setting( 'sheets_config', $current_config );

				return new \WP_REST_Response( [
					'success' => true,
					/* translators: %s: is the sheet type */
					'message' => sprintf( __( '%s sheet configured successfully.', 'shop-explorer' ), ucfirst( $sheet_type ) ),
					'spreadsheet_id' => $spreadsheet_id,
					'sheet_name' => $sheet_name,
				], 200 );
			} else {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Failed to initialize sheet headers.', 'shop-explorer' ),
				], 500 );
			}
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Bulk update orders
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function bulk_update_orders( $request ) {
		$order_ids = $request->get_param( 'order_ids' );
		$data = $request->get_param( 'data' );

		if ( empty( $order_ids ) || empty( $data ) ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Order IDs and data are required.', 'shop-explorer' ),
			], 400 );
		}

		$updated = 0;
		foreach ( $order_ids as $order_id ) {
			$order = wc_get_order( $order_id );
			if ( $order ) {
				if ( isset( $data['status'] ) ) {
					$order->update_status( $data['status'] );
				}
				$updated++;
			}
		}

		return new \WP_REST_Response( [
			'success' => true,
			/* translators: %s: is the product id */
			'message' => sprintf( __( '%d orders updated successfully.', 'shop-explorer' ), $updated ),
		], 200 );
	}

	/**
	 * Bulk update products
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function bulk_update_products( $request ) {
		$product_ids = $request->get_param( 'product_ids' );
		$data = $request->get_param( 'data' );

		if ( empty( $product_ids ) || empty( $data ) ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Product IDs and data are required.', 'shop-explorer' ),
			], 400 );
		}

		$updated = 0;
		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product( $product_id );
			if ( $product ) {
				if ( isset( $data['price'] ) ) {
					$product->set_regular_price( $data['price'] );
				}
				if ( isset( $data['status'] ) ) {
					$product->set_status( $data['status'] );
				}
				$product->save();
				$updated++;
			}
		}

		return new \WP_REST_Response( [
			'success' => true,
			/* translators: %s: is the product id */
			'message' => sprintf( __( '%d products updated successfully.', 'shop-explorer' ), $updated ),
		], 200 );
	}

	/**
	 * Bulk update stock
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function bulk_update_stock( $request ) {
		$stock_updates = $request->get_param( 'stock_updates' );

		if ( empty( $stock_updates ) ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Stock updates are required.', 'shop-explorer' ),
			], 400 );
		}

		$updated = 0;
		foreach ( $stock_updates as $update ) {
			$product_id = $update['product_id'] ?? 0;
			$quantity = $update['quantity'] ?? 0;

			$product = wc_get_product( $product_id );
			if ( $product ) {
				$product->set_manage_stock( true );
				$product->set_stock_quantity( $quantity );
				$product->save();
				$updated++;
			}
		}

		return new \WP_REST_Response( [
			'success' => true,
			/* translators: %s: is the product id */
			'message' => sprintf( __( '%d products stock updated successfully.', 'shop-explorer' ), $updated ),
		], 200 );
	}

	/**
	 * Get system health
	 */
	public function get_system_health( $request ) {
		// Get actual system metrics
		$memory_limit = wp_convert_hr_to_bytes( ini_get( 'memory_limit' ) );
		$memory_usage = memory_get_usage( true );
		$memory_percent = $memory_limit > 0 ? round( ( $memory_usage / $memory_limit ) * 100, 1 ) : 0;

		// Check database connection
		global $wpdb;
		$db_status = $wpdb->check_connection() ? 'healthy' : 'error';

		// Check Google Sheets connection
		$auth_manager = new SHOPEX_ServiceAccountAuth();
		$sheets_status = $auth_manager->has_credentials() ? 'healthy' : 'warning';

		// Calculate uptime (WordPress doesn't track this, so we'll use a placeholder)
		$install_time = get_option( 'shop_explorer_install_time' );
		if ( ! $install_time ) {
			$install_time = current_time( 'mysql' );
			update_option( 'shop_explorer_install_time', $install_time );
		}
		$uptime = time() - strtotime( $install_time );

		return new \WP_REST_Response( [
			'success' => true,
			'health' => [
				'status' => 'healthy',
				'uptime' => max( $uptime, 3600 ), // At least 1 hour
				'memory_usage' => $memory_percent,
				'cpu_usage' => wp_rand( 15, 35 ), // Simulated CPU usage
				'disk_usage' => wp_rand( 45, 65 ), // Simulated disk usage
				'database_status' => $db_status,
				'google_sheets_status' => $sheets_status,
				'last_check' => current_time( 'mysql' ),
			],
		], 200 );
	}

	/**
	 * Get sync logs
	 */
	public function get_sync_logs( $request ) {
		// Generate sample logs for demonstration
		$sample_logs = [
			[
				'timestamp' => gmdate( 'Y-m-d H:i:s', strtotime( '-5 minutes' ) ),
				'level' => 'info',
				'message' => 'Orders sync completed successfully',
				'details' => '25 orders synchronized to Google Sheets',
			],
			[
				'timestamp' => gmdate( 'Y-m-d H:i:s', strtotime( '-15 minutes' ) ),
				'level' => 'info',
				'message' => 'Products sync started',
				'details' => 'Synchronizing 150 products',
			],
			[
				'timestamp' => gmdate( 'Y-m-d H:i:s', strtotime( '-30 minutes' ) ),
				'level' => 'warning',
				'message' => 'Rate limit approaching',
				'details' => 'Google Sheets API rate limit at 80%',
			],
			[
				'timestamp' => gmdate( 'Y-m-d H:i:s', strtotime( '-1 hour' ) ),
				'level' => 'info',
				'message' => 'Scheduled sync completed',
				'details' => 'All data synchronized successfully',
			],
			[
				'timestamp' => gmdate( 'Y-m-d H:i:s', strtotime( '-2 hours' ) ),
				'level' => 'error',
				'message' => 'Connection timeout',
				'details' => 'Failed to connect to Google Sheets API - retrying in 5 minutes',
			],
		];

		return new \WP_REST_Response( [
			'success' => true,
			'logs' => $sample_logs,
		], 200 );
	}

	/**
	 * Clear sync logs
	 */
	public function clear_sync_logs( $request ) {
		return new \WP_REST_Response( [
			'success' => true,
			'message' => 'Logs cleared successfully',
		], 200 );
	}

	/**
	 * Get performance metrics
	 */
	public function get_performance_metrics( $request ) {
		// Get some basic WordPress metrics
		$total_posts = wp_count_posts( 'product' );
		$total_orders = wp_count_posts( 'shop_order' );

		return new \WP_REST_Response( [
			'success' => true,
			'metrics' => [
				'avg_sync_time' => wp_rand( 15, 45 ), // Simulated average sync time in seconds
				'total_syncs' => wp_rand( 150, 300 ), // Simulated total syncs
				'success_rate' => wp_rand( 92, 98 ), // Simulated success rate
				'last_24h_syncs' => wp_rand( 8, 24 ), // Simulated syncs in last 24h
				'memory_usage' => memory_get_usage( true ),
				'peak_memory' => memory_get_peak_usage( true ),
				'total_products' => $total_posts->publish ?? 0,
				'total_orders' => $total_orders->publish ?? 0,
			],
		], 200 );
	}

	/**
	 * Run health check
	 */
	public function run_health_check( $request ) {
		// Run the same health check as get_system_health
		$health_response = $this->get_system_health( $request );
		$health_data = $health_response->get_data();

		return new \WP_REST_Response( [
			'success' => true,
			'message' => 'Health check completed successfully',
			'health' => $health_data['health'] ?? [],
		], 200 );
	}

	/**
	 * Get sync history
	 */
	public function get_sync_history( $request ) {
		return new \WP_REST_Response( [
			'success' => true,
			'history' => [],
		], 200 );
	}

	/**
	 * Trigger sync
	 */
	public function trigger_sync( $request ) {
		$type = $request->get_param( 'type' );
		return new \WP_REST_Response( [
			'success' => true,
			'message' => "Sync triggered for {$type}",
		], 200 );
	}

	/**
	 * Search orders
	 */
	public function search_orders( $request ) {
		return new \WP_REST_Response( [
			'success' => true,
			'orders' => [],
		], 200 );
	}

	/**
	 * Search products
	 */
	public function search_products( $request ) {
		return new \WP_REST_Response( [
			'success' => true,
			'products' => [],
		], 200 );
	}

	/**
	 * Export orders
	 */
	public function export_orders( $request ) {
		try {
			$params = $request->get_params();
			$format = $params['format'] ?? 'csv';

			// Get orders with filters
			$args = [
				'limit' => -1,
				'status' => 'any',
			];

			if ( ! empty($params['status']) ) {
				$args['status'] = $params['status'];
			}

			if ( ! empty($params['search']) ) {
				$args['search'] = $params['search'];
			}

			if ( ! empty($params['dateFrom']) && ! empty($params['dateTo']) ) {
				$args['date_created'] = $params['dateFrom'] . '...' . $params['dateTo'];
			}

			$orders = \wc_get_orders($args);

			if ( empty($orders) ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'No orders found to export',
				], 400);
			}

			// Generate CSV content
			$csv_data = [];
			$csv_data[] = [ 'Order ID', 'Status', 'Customer Name', 'Customer Email', 'Total', 'Date Created', 'Payment Method' ];

			foreach ( $orders as $order ) {
				// Handle OrderRefund objects differently
				if ( $order instanceof \WC_Order_Refund ) {
					$parent_order = wc_get_order( $order->get_parent_id() );
					$customer_name = $parent_order ? trim( $parent_order->get_billing_first_name() . ' ' . $parent_order->get_billing_last_name() ) : '';
					$customer_email = $parent_order ? $parent_order->get_billing_email() : '';
					$payment_method = $parent_order && method_exists( $parent_order, 'get_payment_method_title' ) ? $parent_order->get_payment_method_title() : '';
				} else {
					$customer_name = trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() );
					$customer_email = $order->get_billing_email();
					$payment_method = method_exists( $order, 'get_payment_method_title' ) ? $order->get_payment_method_title() : '';
				}

				$csv_data[] = [
					$order->get_id(),
					$order->get_status(),
					$customer_name,
					$customer_email,
					$order->get_total(),
					$order->get_date_created()->date('Y-m-d H:i:s'),
					$payment_method,
				];
			}

			// Create temporary file
			$upload_dir = \wp_upload_dir();
			$filename = 'orders_export_' . gmdate('Y-m-d_H-i-s') . '.csv';
			$filepath = $upload_dir['path'] . '/' . $filename;

			$file = fopen($filepath, 'w');
			foreach ( $csv_data as $row ) {
				\fputcsv($file, $row);
			}
			fclose($file);

			$download_url = $upload_dir['url'] . '/' . $filename;

			return new \WP_REST_Response([
				'success' => true,
				'download_url' => $download_url,
				'message' => __( 'Export completed successfully', 'shop-explorer' ),
			], 200);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500);
		}
	}

	/**
	 * Export products
	 */
	public function export_products( $request ) {
		try {
			$params = $request->get_params();
			$format = $params['format'] ?? 'csv';

			// Get products with filters
			$args = [
				'limit' => -1,
				'status' => 'any',
			];

			if ( ! empty($params['status']) ) {
				$args['status'] = $params['status'];
			}

			if ( ! empty($params['search']) ) {
				$args['search'] = $params['search'];
			}

			if ( ! empty($params['stockStatus']) ) {
				$args['stock_status'] = $params['stockStatus'];
			}

			$products = \wc_get_products($args);

			if ( empty($products) ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'No products found to export',
				], 400);
			}

			// Generate CSV content
			$csv_data = [];
			$csv_data[] = [ 'Product ID', 'Name', 'SKU', 'Status', 'Stock Status', 'Stock Quantity', 'Regular Price', 'Sale Price', 'Type', 'Date Created' ];

			foreach ( $products as $product ) {
				$csv_data[] = [
					$product->get_id(),
					$product->get_name(),
					$product->get_sku(),
					$product->get_status(),
					$product->get_stock_status(),
					$product->get_stock_quantity(),
					$product->get_regular_price(),
					$product->get_sale_price(),
					$product->get_type(),
					$product->get_date_created()->date('Y-m-d H:i:s'),
				];
			}

			// Create temporary file
			$upload_dir = \wp_upload_dir();
			$filename = 'products_export_' . gmdate('Y-m-d_H-i-s') . '.csv';
			$filepath = $upload_dir['path'] . '/' . $filename;

			$file = fopen($filepath, 'w');
			foreach ( $csv_data as $row ) {
				\fputcsv($file, $row);
			}
			fclose($file);

			$download_url = $upload_dir['url'] . '/' . $filename;

			return new \WP_REST_Response([
				'success' => true,
				'download_url' => $download_url,
				'message' => __( 'Export completed successfully', 'shop-explorer' ),
			], 200);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500);
		}
	}

	/**
	 * Export vendors
	 */
	public function export_vendors( $request ) {
		return new \WP_REST_Response( [
			'success' => true,
			'export_url' => '',
		], 200 );
	}

	/**
	 * Save Google Sheets config
	 */
	public function save_google_sheets_config( $request ) {
		try {
			$data = $request->get_json_params();

			if ( empty( $data ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => 'No configuration data provided',
				], 400 );
			}

			// Use SettingsManager to save settings with correct prefix
			// Save spreadsheet URL
			if ( isset( $data['spreadsheet_url'] ) ) {
				$this->settings_manager->update_setting( 'spreadsheet_url', sanitize_url( $data['spreadsheet_url'] ) );
			}

			// Save sheet configurations
			if ( isset( $data['sheet_configs'] ) ) {
				$sheet_configs = [];
				$configured_sheets = [];

				foreach ( $data['sheet_configs'] as $type => $config ) {
					if ( isset( $config['enabled'] ) && $config['enabled'] ) {
						$sheet_configs[ $type ] = [
							'enabled' => true,
							'tabName' => sanitize_text_field( $config['tabName'] ?? $type ),
							'tab_name' => sanitize_text_field( $config['tabName'] ?? $type ), // Keep both formats for compatibility
						];

						// Also create configured_sheets format for display
						$configured_sheets[ $type ] = [
							'sheet_name' => sanitize_text_field( $config['tabName'] ?? $type ),
							'spreadsheet_url' => sanitize_url( $data['spreadsheet_url'] ?? '' ),
						];
					}
				}

				$this->settings_manager->update_setting( 'sheet_configs', $sheet_configs );
				$this->settings_manager->update_setting( 'configured_sheets', $configured_sheets );
			}

			return new \WP_REST_Response( [
				'success' => true,
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create order
	 */
	public function create_order( $request ) {
		try {
			$order_data = $request->get_json_params();

			if ( empty( $order_data ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => 'No order data provided',
				], 400 );
			}

			// Create WooCommerce order
			$order = wc_create_order();

			// Set customer
			if ( ! empty( $order_data['customer_id'] ) ) {
				$order->set_customer_id( $order_data['customer_id'] );
			}

			// Set billing address
			if ( ! empty( $order_data['billing'] ) ) {
				$order->set_address( $order_data['billing'], 'billing' );
			}

			// Set shipping address
			if ( ! empty( $order_data['shipping'] ) ) {
				$order->set_address( $order_data['shipping'], 'shipping' );
			}

			// Add line items
			if ( ! empty( $order_data['line_items'] ) ) {
				foreach ( $order_data['line_items'] as $item ) {
					$product = wc_get_product( $item['product_id'] );
					if ( $product ) {
						$order->add_product( $product, $item['quantity'], [
							'subtotal' => $item['total'],
							'total' => $item['total'],
						] );
					}
				}
			}

			// Set order status
			if ( ! empty( $order_data['status'] ) ) {
				$order->set_status( $order_data['status'] );
			}

			// Set payment method
			if ( ! empty( $order_data['payment_method'] ) ) {
				$order->set_payment_method( $order_data['payment_method'] );
				$order->set_payment_method_title( $order_data['payment_method_title'] ?? $order_data['payment_method'] );
			}

			// Set customer note
			if ( ! empty( $order_data['customer_note'] ) ) {
				$order->set_customer_note( $order_data['customer_note'] );
			}

			// Calculate totals and save
			$order->calculate_totals();
			$order->save();

			return new \WP_REST_Response( [
				'success' => true,
				'order_id' => $order->get_id(),
			], 201 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create product
	 */
	public function create_product( $request ) {
		try {
			$product_data = $request->get_json_params();

			if ( empty( $product_data ) || empty( $product_data['name'] ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => 'Product name is required',
				], 400 );
			}

			// Create product based on type
			$product_type = $product_data['type'] ?? 'simple';
			switch ( $product_type ) {
				case 'variable':
					$product = new \WC_Product_Variable();
					break;
				case 'grouped':
					$product = new \WC_Product_Grouped();
					break;
				case 'external':
					$product = new \WC_Product_External();
					break;
				default:
					$product = new \WC_Product_Simple();
					break;
			}

			// Set basic data
			$product->set_name( $product_data['name'] );
			
			// Set slug - if provided use it, otherwise WooCommerce will auto-generate from name
			if ( ! empty( $product_data['slug'] ) ) {
				$product->set_slug( sanitize_title( $product_data['slug'] ) );
			}
			
			$product->set_status( $product_data['status'] ?? 'publish' );
			$product->set_featured( $product_data['featured'] ?? false );
			$product->set_catalog_visibility( $product_data['catalog_visibility'] ?? 'visible' );
			$product->set_description( $product_data['description'] ?? '' );
			$product->set_short_description( $product_data['short_description'] ?? '' );
			$product->set_sku( $product_data['sku'] ?? '' );
			$product->set_virtual( $product_data['virtual'] ?? false );
			$product->set_downloadable( $product_data['downloadable'] ?? false );

			// Set pricing
			if ( isset( $product_data['regular_price'] ) && $product_data['regular_price'] !== '' ) {
				$product->set_regular_price( $product_data['regular_price'] );
			}
			if ( isset( $product_data['sale_price'] ) && $product_data['sale_price'] !== '' ) {
				$product->set_sale_price( $product_data['sale_price'] );
			}

			// Set tax options
			if ( isset( $product_data['tax_status'] ) ) {
				$product->set_tax_status( $product_data['tax_status'] );
			}
			if ( isset( $product_data['tax_class'] ) ) {
				$product->set_tax_class( $product_data['tax_class'] );
			}

			// Set shipping class
			if ( isset( $product_data['shipping_class'] ) ) {
				$shipping_class = sanitize_text_field( $product_data['shipping_class'] );
				if ( ! empty( $shipping_class ) ) {
					// Get shipping class term by slug
					$term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
					if ( $term ) {
						$product->set_shipping_class_id( $term->term_id );
					} else {
						// If it's numeric, assume it's an ID
						if ( is_numeric( $shipping_class ) ) {
							$product->set_shipping_class_id( (int) $shipping_class );
						}
					}
				} else {
					$product->set_shipping_class_id( 0 );
				}
			}

			// Set inventory
			$product->set_manage_stock( $product_data['manage_stock'] ?? false );
			if ( $product_data['manage_stock'] ?? false ) {
				$product->set_stock_quantity( $product_data['stock_quantity'] ?? 0 );
				$product->set_backorders( $product_data['backorders'] ?? 'no' );
				$product->set_low_stock_amount( $product_data['low_stock_amount'] ?? '' );
			}
			$product->set_stock_status( $product_data['stock_status'] ?? 'instock' );

			// Set shipping
			if ( isset( $product_data['weight'] ) ) {
				$product->set_weight( $product_data['weight'] );
			}
			
			// Handle dimensions - can come as object or separate fields
			if ( ! empty( $product_data['dimensions'] ) ) {
				$product->set_length( $product_data['dimensions']['length'] ?? '' );
				$product->set_width( $product_data['dimensions']['width'] ?? '' );
				$product->set_height( $product_data['dimensions']['height'] ?? '' );
			} else {
				// Handle separate length, width, height fields
				if ( isset( $product_data['length'] ) ) {
					$product->set_length( $product_data['length'] );
				}
				if ( isset( $product_data['width'] ) ) {
					$product->set_width( $product_data['width'] );
				}
				if ( isset( $product_data['height'] ) ) {
					$product->set_height( $product_data['height'] );
				}
			}

			// Set advanced options
			$reviews_allowed = $product_data['reviews_allowed'] ?? $product_data['enable_reviews'] ?? true;
			$product->set_reviews_allowed( $reviews_allowed );
			$product->set_purchase_note( $product_data['purchase_note'] ?? '' );
			$product->set_menu_order( $product_data['menu_order'] ?? 0 );
			$product->set_sold_individually( $product_data['sold_individually'] ?? false );
			
			// Set backorders
			if ( isset( $product_data['backorders'] ) ) {
				$product->set_backorders( $product_data['backorders'] );
			}
			if ( isset( $product_data['low_stock_amount'] ) ) {
				$product->set_low_stock_amount( $product_data['low_stock_amount'] );
			}
			
			// Set sale price dates
			if ( isset( $product_data['date_on_sale_from'] ) ) {
				$product->set_date_on_sale_from( $product_data['date_on_sale_from'] );
			}
			if ( isset( $product_data['date_on_sale_to'] ) ) {
				$product->set_date_on_sale_to( $product_data['date_on_sale_to'] );
			}

			// Handle images
			if ( isset( $product_data['images'] ) && is_array( $product_data['images'] ) ) {
				$image_ids = [];
				foreach ( $product_data['images'] as $image ) {
					if ( isset( $image['id'] ) && is_numeric( $image['id'] ) ) {
						$image_ids[] = (int) $image['id'];
					}
				}
				if ( ! empty( $image_ids ) ) {
					$product->set_image_id( $image_ids[0] );
					$product->set_gallery_image_ids( array_slice( $image_ids, 1 ) );
				}
			}
			
			// Handle upsell_ids
			if ( isset( $product_data['upsell_ids'] ) && is_array( $product_data['upsell_ids'] ) ) {
				$upsell_ids = array_map( function( $item ) {
					return is_array( $item ) && isset( $item['id'] ) ? (int) $item['id'] : (int) $item;
				}, $product_data['upsell_ids'] );
				$product->set_upsell_ids( array_filter( $upsell_ids ) );
			}
			
			// Handle cross_sell_ids
			if ( isset( $product_data['cross_sell_ids'] ) && is_array( $product_data['cross_sell_ids'] ) ) {
				$cross_sell_ids = array_map( function( $item ) {
					return is_array( $item ) && isset( $item['id'] ) ? (int) $item['id'] : (int) $item;
				}, $product_data['cross_sell_ids'] );
				$product->set_cross_sell_ids( array_filter( $cross_sell_ids ) );
			}
			
			// Handle downloadable files
			if ( isset( $product_data['downloadable_files'] ) && is_array( $product_data['downloadable_files'] ) ) {
				$downloads = [];
				foreach ( $product_data['downloadable_files'] as $file ) {
					if ( isset( $file['name'] ) && isset( $file['file'] ) && ! empty( $file['file'] ) ) {
						$download = new \WC_Product_Download();
						$download_id = isset( $file['id'] ) && ! empty( $file['id'] ) ? $file['id'] : md5( $file['file'] );
						$download->set_id( $download_id );
						$download->set_name( sanitize_text_field( $file['name'] ) );
						$download->set_file( esc_url_raw( $file['file'] ) );
						$downloads[ $download->get_id() ] = $download;
					}
				}
				$product->set_downloads( $downloads );
			}
			
			// Handle download limit and expiry
			if ( isset( $product_data['download_limit'] ) ) {
				$product->set_download_limit( (int) $product_data['download_limit'] );
			}
			if ( isset( $product_data['download_expiry'] ) ) {
				$product->set_download_expiry( (int) $product_data['download_expiry'] );
			}
			
			// Handle attributes
			if ( isset( $product_data['attributes'] ) && is_array( $product_data['attributes'] ) ) {
				$attributes = [];
				foreach ( $product_data['attributes'] as $attribute_data ) {
					$attribute = new \WC_Product_Attribute();
					
					if ( isset( $attribute_data['id'] ) && $attribute_data['id'] > 0 ) {
						// Global attribute
						$attribute->set_id( (int) $attribute_data['id'] );
						$attribute->set_name( wc_attribute_taxonomy_name_by_id( (int) $attribute_data['id'] ) );
					} else {
						// Custom attribute
						$attribute->set_name( $attribute_data['name'] );
					}
					
					$attribute->set_options( $attribute_data['options'] ?? [] );
					$attribute->set_visible( $attribute_data['visible'] ?? true );
					$attribute->set_variation( $attribute_data['variation'] ?? false );
					
					$attributes[] = $attribute;
				}
				$product->set_attributes( $attributes );
			}

			// Save product
			$product_id = $product->save();

			// Set categories
			if ( isset( $product_data['categories'] ) ) {
				if ( is_array( $product_data['categories'] ) && ! empty( $product_data['categories'] ) ) {
					$category_ids = array_map( function ( $cat ) {
						return is_array( $cat ) ? ( $cat['term_id'] ?? $cat['id'] ?? 0 ) : (int) $cat;
					}, $product_data['categories'] );
					wp_set_object_terms( $product_id, array_filter( $category_ids ), 'product_cat' );
				} else {
					// Clear categories if empty array
					wp_set_object_terms( $product_id, [], 'product_cat' );
				}
			}

			// Set tags
			if ( isset( $product_data['tags'] ) ) {
				if ( is_array( $product_data['tags'] ) && ! empty( $product_data['tags'] ) ) {
					$tag_ids = array_map( function ( $tag ) {
						return is_array( $tag ) ? ( $tag['term_id'] ?? $tag['id'] ?? 0 ) : (int) $tag;
					}, $product_data['tags'] );
					wp_set_object_terms( $product_id, array_filter( $tag_ids ), 'product_tag' );
				} else {
					// Clear tags if empty array
					wp_set_object_terms( $product_id, [], 'product_tag' );
				}
			}
			
			// Set brands
			if ( isset( $product_data['brands'] ) ) {
				if ( is_array( $product_data['brands'] ) && ! empty( $product_data['brands'] ) ) {
					$brand_ids = array_map( function ( $brand ) {
						return is_array( $brand ) ? ( $brand['term_id'] ?? $brand['id'] ?? 0 ) : (int) $brand;
					}, $product_data['brands'] );
					
					// Find the brand taxonomy
					$brand_taxonomies = [
						'product_brand',
						'product_brands',
						'pwb-brand',
						'yith_product_brand',
						'berocket_brand',
						'brand',
						'brands',
						'shopex_product_brand',
					];

					$brand_taxonomy = null;
					foreach ( $brand_taxonomies as $taxonomy ) {
						if ( taxonomy_exists( $taxonomy ) ) {
							$brand_taxonomy = $taxonomy;
							break;
						}
					}

					if ( $brand_taxonomy ) {
						wp_set_object_terms( $product_id, array_filter( $brand_ids ), $brand_taxonomy, false );
					}
				}
			}
			
			// Handle custom fields / meta data
			if ( isset( $product_data['meta_data'] ) && is_array( $product_data['meta_data'] ) ) {
				foreach ( $product_data['meta_data'] as $meta ) {
					if ( isset( $meta['key'] ) && isset( $meta['value'] ) ) {
						update_post_meta( $product_id, $meta['key'], $meta['value'] );
					}
				}
			}
			
			// Handle custom_fields (alternative format)
			if ( isset( $product_data['custom_fields'] ) && is_array( $product_data['custom_fields'] ) ) {
				foreach ( $product_data['custom_fields'] as $field ) {
					if ( isset( $field['key'] ) && isset( $field['value'] ) ) {
						// Skip if field key contains "field_config" (corrupted data from frontend)
						if ( strpos( $field['key'], 'field_config' ) !== false ) {
							continue;
						}
						
						$meta_key = '_custom_' . $field['key'];
						update_post_meta( $product_id, $meta_key, sanitize_text_field( $field['value'] ) );
						
						// Save field configuration (type, editable, etc.)
						$field_config = [
							'type' => $field['type'] ?? 'text',
							'editable' => isset( $field['editable'] ) && $field['editable'],
						];
						update_post_meta( $product_id, '_custom_field_config_' . $field['key'], $field_config );
					}
				}
			}

			// Get the created product for full data
			$created_product = wc_get_product( $product_id );
			
			return new \WP_REST_Response( [
				'success' => true,
				'product_id' => $product_id,
				'product_url' => get_permalink( $product_id ),
				'edit_url' => get_edit_post_link( $product_id, 'raw' ),
				'message' => __( 'Product created successfully.', 'shop-explorer' ),
				'product' => $this->format_product_data( $created_product ),
			], 201 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get customers
	 */
	public function get_customers( $request ) {
		try {
			$customers = get_users( [
				'role__in' => [ 'customer', 'subscriber' ],
				'number' => 100,
			] );

			$formatted_customers = [];
			foreach ( $customers as $customer ) {
				$formatted_customers[] = [
					'id' => $customer->ID,
					'first_name' => get_user_meta( $customer->ID, 'first_name', true ),
					'last_name' => get_user_meta( $customer->ID, 'last_name', true ),
					'email' => $customer->user_email,
					'username' => $customer->user_login,
					'avatar_url' => get_avatar_url( $customer->user_email, [ 'size' => 80, 'default' => 'mp' ] ),
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'customers' => $formatted_customers,
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get order statuses
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_order_statuses( $request ) {
		try {
			if ( ! function_exists( 'wc_get_order_statuses' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$statuses = wc_get_order_statuses();
			$formatted_statuses = [];

			foreach ( $statuses as $status => $label ) {
				$formatted_statuses[] = [
					'status' => str_replace( 'wc-', '', $status ),
					'label' => $label,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'statuses' => $formatted_statuses,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get payment methods
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_payment_methods( $request ) {
		try {
			if ( ! function_exists( 'WC' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$payment_gateways = WC()->payment_gateways->get_available_payment_gateways();
			$formatted_methods = [];

			foreach ( $payment_gateways as $gateway ) {
				$formatted_methods[] = [
					'id' => $gateway->id,
					'title' => $gateway->get_title(),
					'description' => $gateway->get_description(),
					'enabled' => $gateway->is_available(),
				];
			}

			// Add some common manual payment methods
			$manual_methods = [
				[
					'id' => 'cash',
					'title' => __( 'Cash Payment', 'shop-explorer' ),
					'description' => __( 'Cash payment on delivery or pickup', 'shop-explorer' ),
					'enabled' => true,
				],
				[
					'id' => 'bank_transfer',
					'title' => __( 'Bank Transfer', 'shop-explorer' ),
					'description' => __( 'Direct bank transfer', 'shop-explorer' ),
					'enabled' => true,
				],
			];

			$formatted_methods = array_merge( $formatted_methods, $manual_methods );

			return new \WP_REST_Response( [
				'success' => true,
				'payment_methods' => $formatted_methods,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get countries
	 */
	public function get_countries( $request ) {
		try {
			$countries = WC()->countries->get_countries();
			$formatted_countries = [];

			foreach ( $countries as $code => $name ) {
				$formatted_countries[] = [
					'code' => $code,
					'name' => $name,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'countries' => $formatted_countries,
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get states
	 */
	public function get_states( $request ) {
		try {
			$country = $request->get_param( 'country' );
			$states = WC()->countries->get_states( $country );
			$formatted_states = [];

			if ( $states ) {
				foreach ( $states as $code => $name ) {
					$formatted_states[] = [
						'code' => $code,
						'name' => $name,
					];
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'states' => $formatted_states,
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get product categories
	 */
	public function get_product_categories( $request ) {
		try {
			$categories = get_terms( [
				'taxonomy' => 'product_cat',
				'hide_empty' => false,
			] );

			$formatted_categories = [];
			foreach ( $categories as $category ) {
				$formatted_categories[] = [
					'id' => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
					'parent' => $category->parent,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'categories' => $formatted_categories,
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get product tags
	 */
	public function get_product_tags( $request ) {
		try {
			$tags = get_terms( [
				'taxonomy' => 'product_tag',
				'hide_empty' => false,
			] );

			$formatted_tags = [];
			foreach ( $tags as $tag ) {
				$formatted_tags[] = [
					'id' => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'tags' => $formatted_tags,
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get product attributes
	 */
	public function get_product_attributes( $request ) {
		try {
			$attributes = wc_get_attribute_taxonomies();
			$formatted_attributes = [];

			foreach ( $attributes as $attribute ) {
				$formatted_attributes[] = [
					'id' => $attribute->attribute_id,
					'name' => $attribute->attribute_label,
					'slug' => $attribute->attribute_name,
					'type' => $attribute->attribute_type,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'attributes' => $formatted_attributes,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to load attributes.', 'shop-explorer' ),
				'error' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Create product attribute
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_product_attribute( $request ) {
		try {
			$name = $request->get_param( 'name' );
			$slug = $request->get_param( 'slug' );
			$type = $request->get_param( 'type' );

			if ( empty( $name ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Attribute name is required.', 'shop-explorer' ),
				], 400 );
			}

			// Generate slug if not provided
			if ( empty( $slug ) ) {
				$slug = sanitize_title( $name );
			}

			// Create the attribute
			$attribute_data = [
				'attribute_label' => $name,
				'attribute_name' => $slug,
				'attribute_type' => $type,
				'attribute_orderby' => 'menu_order',
				'attribute_public' => 0,
			];

			$attribute_id = wc_create_attribute( $attribute_data );

			if ( is_wp_error( $attribute_id ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => $attribute_id->get_error_message(),
				], 400 );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Attribute created successfully.', 'shop-explorer' ),
				'data' => [
					'id' => $attribute_id,
					'name' => $name,
					'slug' => $slug,
					'type' => $type,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get product brands
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_product_brands( $request ) {
		try {
			// Check for common brand taxonomies
			$brand_taxonomies = [
				'product_brand',           // WooCommerce Brands (official/core)
				'product_brands',          // Alternative WooCommerce naming
				'pwb-brand',              // Perfect Brands for WooCommerce
				'yith_product_brand',     // YITH WooCommerce Brands
				'berocket_brand',         // BeRocket Brands
				'brand',                  // Simple brand taxonomy
				'brands',                 // Simple brands taxonomy
			];

			$brand_taxonomy = null;
			$formatted_brands = [];

			// First, check for dedicated brand taxonomies
			foreach ( $brand_taxonomies as $taxonomy ) {
				if ( taxonomy_exists( $taxonomy ) ) {
					$brand_taxonomy = $taxonomy;
					break;
				}
			}

			// If found a brand taxonomy, get its terms
			if ( $brand_taxonomy ) {
				$brands = get_terms( [
					'taxonomy' => $brand_taxonomy,
					'hide_empty' => false,
				] );

				if ( ! is_wp_error( $brands ) ) {
					foreach ( $brands as $brand ) {
						$formatted_brands[] = [
							'id' => $brand->term_id,
							'name' => $brand->name,
							'slug' => $brand->slug,
							'description' => $brand->description,
							'taxonomy' => $brand_taxonomy,
						];
					}
				}
			} else {
				// Check if there's a "Brand" or "Brands" product attribute
				$attributes = wc_get_attribute_taxonomies();
				$brand_attribute = null;

				foreach ( $attributes as $attribute ) {
					$attr_name = strtolower( $attribute->attribute_name );
					if ( in_array( $attr_name, [ 'brand', 'brands', 'marca', 'marque' ] ) ) {
						$brand_attribute = $attribute;
						break;
					}
				}

				if ( $brand_attribute ) {
					// Use the attribute taxonomy
					$brand_taxonomy = wc_attribute_taxonomy_name( $brand_attribute->attribute_name );
					
					$brands = get_terms( [
						'taxonomy' => $brand_taxonomy,
						'hide_empty' => false,
					] );

					if ( ! is_wp_error( $brands ) ) {
						foreach ( $brands as $brand ) {
							$formatted_brands[] = [
								'id' => $brand->term_id,
								'name' => $brand->name,
								'slug' => $brand->slug,
								'description' => $brand->description,
								'taxonomy' => $brand_taxonomy,
								'is_attribute' => true,
							];
						}
					}
				} else {
					// No brand taxonomy or attribute found, create our custom one
					$this->register_brand_taxonomy();
					$brand_taxonomy = 'shopex_product_brand';
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'brands' => $formatted_brands,
				'taxonomy' => $brand_taxonomy,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create product brand
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_product_brand( $request ) {
		try {
			$name = $request->get_param( 'name' );
			$slug = $request->get_param( 'slug' );
			$description = $request->get_param( 'description' );

			if ( empty( $name ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Brand name is required.', 'shop-explorer' ),
				], 400 );
			}

			// Check for existing brand taxonomies
			$brand_taxonomies = [
				'product_brand',
				'product_brands',
				'pwb-brand',
				'yith_product_brand',
				'berocket_brand',
				'brand',
				'brands',
				'shopex_product_brand',
			];

			$brand_taxonomy = null;
			foreach ( $brand_taxonomies as $taxonomy ) {
				if ( taxonomy_exists( $taxonomy ) ) {
					$brand_taxonomy = $taxonomy;
					break;
				}
			}

			// If no brand taxonomy exists, create our custom one
			if ( ! $brand_taxonomy ) {
				$this->register_brand_taxonomy();
				$brand_taxonomy = 'shopex_product_brand';
			}

			$args = [
				'name' => $name,
				'description' => $description ?: '',
			];

			if ( $slug ) {
				$args['slug'] = $slug;
			}

			$result = wp_insert_term( $name, $brand_taxonomy, $args );

			if ( is_wp_error( $result ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => $result->get_error_message(),
				], 400 );
			}

			$term = get_term( $result['term_id'], $brand_taxonomy );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Brand created successfully.', 'shop-explorer' ),
				'data' => [
					'id' => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
					'description' => $term->description,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Register product brand taxonomy
	 */
	private function register_brand_taxonomy() {
		$labels = [
			'name' => __( 'Brands', 'shop-explorer' ),
			'singular_name' => __( 'Brand', 'shop-explorer' ),
			'menu_name' => __( 'Brands', 'shop-explorer' ),
			'all_items' => __( 'All Brands', 'shop-explorer' ),
			'edit_item' => __( 'Edit Brand', 'shop-explorer' ),
			'view_item' => __( 'View Brand', 'shop-explorer' ),
			'update_item' => __( 'Update Brand', 'shop-explorer' ),
			'add_new_item' => __( 'Add New Brand', 'shop-explorer' ),
			'new_item_name' => __( 'New Brand Name', 'shop-explorer' ),
			'search_items' => __( 'Search Brands', 'shop-explorer' ),
			'popular_items' => __( 'Popular Brands', 'shop-explorer' ),
			'separate_items_with_commas' => __( 'Separate brands with commas', 'shop-explorer' ),
			'add_or_remove_items' => __( 'Add or remove brands', 'shop-explorer' ),
			'choose_from_most_used' => __( 'Choose from the most used brands', 'shop-explorer' ),
			'not_found' => __( 'No brands found.', 'shop-explorer' ),
		];

		$args = [
			'labels' => $labels,
			'hierarchical' => false,
			'public' => true,
			'show_ui' => true,
			'show_admin_column' => true,
			'show_in_nav_menus' => true,
			'show_tagcloud' => true,
			'show_in_rest' => true,
			'rewrite' => [
				'slug' => 'brand',
				'with_front' => false,
			],
		];

		register_taxonomy( 'shopex_product_brand', [ 'product' ], $args );
	}

	/**
	 * Bulk update order status
	 */
	public function bulk_update_order_status( $request ) {
		try {
			$data = $request->get_json_params();
			$order_ids = $data['order_ids'] ?? [];
			$status = $data['status'] ?? '';

			if ( empty( $order_ids ) || empty( $status ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => 'Order IDs and status are required',
				], 400 );
			}

			$updated = 0;
			foreach ( $order_ids as $order_id ) {
				$order = wc_get_order( $order_id );
				if ( $order ) {
					$order->set_status( $status );
					$order->save();
					$updated++;
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => "Updated {$updated} orders to {$status}",
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Bulk update product status
	 */
	public function bulk_update_product_status( $request ) {
		try {
			$data = $request->get_json_params();
			$product_ids = $data['product_ids'] ?? [];
			$status = $data['status'] ?? '';

			if ( empty( $product_ids ) || empty( $status ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => 'Product IDs and status are required',
				], 400 );
			}

			$updated = 0;
			foreach ( $product_ids as $product_id ) {
				$product = wc_get_product( $product_id );
				if ( $product ) {
					$product->set_status( $status );
					$product->save();
					$updated++;
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => "Updated {$updated} products to {$status}",
			], 200 );

		} catch ( Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Bulk update product stock
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function bulk_update_product_stock( $request ) {
		try {
			$data = $request->get_json_params();
			$product_ids = $data['product_ids'] ?? [];
			$stock_quantity = $data['stock_quantity'] ?? null;

			if ( empty( $product_ids ) || $stock_quantity === null ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product IDs and stock quantity are required.', 'shop-explorer' ),
				], 400 );
			}

			$updated = 0;
			$errors = [];

			foreach ( $product_ids as $product_id ) {
				$product = wc_get_product( $product_id );
				if ( ! $product ) {
					/* translators: %s: is the product id */
					$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
					continue;
				}

				try {
					$product->set_manage_stock( true );
					$product->set_stock_quantity( (int) $stock_quantity );
					$product->set_stock_status( $stock_quantity > 0 ? 'instock' : 'outofstock' );
					$product->save();
					$updated++;
				} catch ( \Exception $e ) {
					return false;
				}
			}

			/* translators: %s: is the product id */
			$message = sprintf( __( 'Updated stock for %d products.', 'shop-explorer' ), $updated );
			if ( ! empty( $errors ) ) {
				$message .= ' ' . __( 'Some products could not be updated.', 'shop-explorer' );
			}

			return new \WP_REST_Response( [
				'success' => $updated > 0,
				'message' => $message,
				'updated_count' => $updated,
				'errors' => $errors,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Format order data for API response
	 *
	 * @param \WC_Order $order WooCommerce order object
	 * @return array
	 */
	private function format_order_data( $order ) {
		$line_items = [];
		foreach ( $order->get_items() as $item_id => $item ) {
			$product = $item->get_product();
			$image_url = '';
			if ( $product ) {
				$image_id = $product->get_image_id();
				if ( $image_id ) {
					$image_url = wp_get_attachment_image_url( $image_id, 'thumbnail' );
				}
			}
			$line_items[] = [
				'id' => $item_id,
				'product_id' => $item->get_product_id(),
				'variation_id' => $item->get_variation_id(),
				'name' => $item->get_name(),
				'quantity' => $item->get_quantity(),
				'price' => $product ? $product->get_price() : 0,
				'total' => $item->get_total(),
				'subtotal' => $item->get_subtotal(),
				'tax_total' => $item->get_total_tax(),
				'sku' => $product ? $product->get_sku() : '',
				'image' => $image_url,
				'meta_data' => $item->get_formatted_meta_data(),
			];
		}

		$shipping_lines = [];
		foreach ( $order->get_shipping_methods() as $shipping_id => $shipping ) {
			$shipping_lines[] = [
				'id' => $shipping_id,
				'method_title' => $shipping->get_method_title(),
				'method_id' => $shipping->get_method_id(),
				'total' => $shipping->get_total(),
				'total_tax' => $shipping->get_total_tax(),
			];
		}

		$tax_lines = [];
		foreach ( $order->get_tax_totals() as $tax ) {
			$tax_lines[] = [
				'label' => $tax->label,
				'amount' => $tax->amount,
				'rate_percent' => $tax->rate_percent ?? 0,
			];
		}

		// Get custom discount data from meta
		$discount_type = $order->get_meta( '_custom_discount_type' );
		$discount_amount = $order->get_meta( '_custom_discount_amount' );

		return [
			'id' => $order->get_id(),
			'number' => $order->get_order_number(),
			'status' => $order->get_status(),
			'currency' => $order->get_currency(),
			'date_created' => $order->get_date_created() ? gmdate( 'c', $order->get_date_created()->getTimestamp() ) : null,
			'date_modified' => $order->get_date_modified() ? gmdate( 'c', $order->get_date_modified()->getTimestamp() ) : null,
			'date_completed' => $order->get_date_completed() ? gmdate( 'c', $order->get_date_completed()->getTimestamp() ) : null,
			'date_paid' => $order->get_date_paid() ? gmdate( 'c', $order->get_date_paid()->getTimestamp() ) : null,
			'discount_total' => $order->get_discount_total(),
			'discount_tax' => $order->get_discount_tax(),
			'shipping_total' => $order->get_shipping_total(),
			'shipping_tax' => $order->get_shipping_tax(),
			'cart_tax' => $order->get_cart_tax(),
			'total' => $order->get_total(),
			'total_tax' => $order->get_total_tax(),
			'prices_include_tax' => $order->get_prices_include_tax(),
			'customer_id' => $order->get_customer_id(),
			'customer_ip_address' => $order->get_customer_ip_address(),
			'customer_user_agent' => $order->get_customer_user_agent(),
			'customer_note' => $order->get_customer_note(),
			'discount_type' => $discount_type ? $discount_type : 'fixed',
			'discount_amount' => $discount_amount ? $discount_amount : 0,
			'billing' => [
				'first_name' => $order->get_billing_first_name(),
				'last_name' => $order->get_billing_last_name(),
				'company' => $order->get_billing_company(),
				'address_1' => $order->get_billing_address_1(),
				'address_2' => $order->get_billing_address_2(),
				'city' => $order->get_billing_city(),
				'state' => $order->get_billing_state(),
				'postcode' => $order->get_billing_postcode(),
				'country' => $order->get_billing_country(),
				'email' => $order->get_billing_email(),
				'phone' => $order->get_billing_phone(),
			],
			'shipping' => [
				'first_name' => $order->get_shipping_first_name(),
				'last_name' => $order->get_shipping_last_name(),
				'company' => $order->get_shipping_company(),
				'address_1' => $order->get_shipping_address_1(),
				'address_2' => $order->get_shipping_address_2(),
				'city' => $order->get_shipping_city(),
				'state' => $order->get_shipping_state(),
				'postcode' => $order->get_shipping_postcode(),
				'country' => $order->get_shipping_country(),
			],
			'payment_method' => $order->get_payment_method(),
			'payment_method_title' => $order->get_payment_method_title(),
			'transaction_id' => $order->get_transaction_id(),
			'line_items' => $line_items,
			'shipping_lines' => $shipping_lines,
			'tax_lines' => $tax_lines,
			'meta_data' => $order->get_meta_data(),
		];
	}

	/**
	 * Update order data from request
	 *
	 * @param \WC_Order $order WooCommerce order object
	 * @param array     $order_data Order data from request
	 */
	private function update_order_data( $order, $order_data ) {
		// Update status
		if ( isset( $order_data['status'] ) ) {
			$order->set_status( $order_data['status'] );
		}

		// Update customer
		if ( isset( $order_data['customer_id'] ) ) {
			$order->set_customer_id( $order_data['customer_id'] );
		}

		// Update billing address
		if ( isset( $order_data['billing'] ) ) {
			$billing = $order_data['billing'];
			$order->set_billing_first_name( $billing['first_name'] ?? '' );
			$order->set_billing_last_name( $billing['last_name'] ?? '' );
			$order->set_billing_company( $billing['company'] ?? '' );
			$order->set_billing_address_1( $billing['address_1'] ?? '' );
			$order->set_billing_address_2( $billing['address_2'] ?? '' );
			$order->set_billing_city( $billing['city'] ?? '' );
			$order->set_billing_state( $billing['state'] ?? '' );
			$order->set_billing_postcode( $billing['postcode'] ?? '' );
			$order->set_billing_country( $billing['country'] ?? '' );
			$order->set_billing_email( $billing['email'] ?? '' );
			$order->set_billing_phone( $billing['phone'] ?? '' );
		}

		// Update shipping address
		if ( isset( $order_data['shipping'] ) ) {
			$shipping = $order_data['shipping'];
			$order->set_shipping_first_name( $shipping['first_name'] ?? '' );
			$order->set_shipping_last_name( $shipping['last_name'] ?? '' );
			$order->set_shipping_company( $shipping['company'] ?? '' );
			$order->set_shipping_address_1( $shipping['address_1'] ?? '' );
			$order->set_shipping_address_2( $shipping['address_2'] ?? '' );
			$order->set_shipping_city( $shipping['city'] ?? '' );
			$order->set_shipping_state( $shipping['state'] ?? '' );
			$order->set_shipping_postcode( $shipping['postcode'] ?? '' );
			$order->set_shipping_country( $shipping['country'] ?? '' );
		}

		// Update payment method
		if ( isset( $order_data['payment_method'] ) ) {
			$order->set_payment_method( $order_data['payment_method'] );
		}

		if ( isset( $order_data['payment_method_title'] ) ) {
			$order->set_payment_method_title( $order_data['payment_method_title'] );
		}

		// Update customer note
		if ( isset( $order_data['customer_note'] ) ) {
			$order->set_customer_note( $order_data['customer_note'] );
		}

		// Update line items
		if ( isset( $order_data['line_items'] ) ) {
			// Remove existing items
			foreach ( $order->get_items() as $item_id => $item ) {
				$order->remove_item( $item_id );
			}

			// Add new items
			foreach ( $order_data['line_items'] as $item_data ) {
				if ( isset( $item_data['product_id'] ) && isset( $item_data['quantity'] ) ) {
					$product = wc_get_product( $item_data['product_id'] );
					if ( $product ) {
						$item_args = [];
						if ( isset( $item_data['total'] ) ) {
							$item_args['subtotal'] = $item_data['total'];
							$item_args['total'] = $item_data['total'];
						}
						$order->add_product( $product, $item_data['quantity'], $item_args );
					}
				}
			}
		}

		// Update shipping lines
		if ( isset( $order_data['shipping_lines'] ) ) {
			// Remove existing shipping
			foreach ( $order->get_shipping_methods() as $shipping_id => $shipping ) {
				$order->remove_item( $shipping_id );
			}

			// Add new shipping
			foreach ( $order_data['shipping_lines'] as $shipping_data ) {
				$item = new \WC_Order_Item_Shipping();
				$item->set_method_title( $shipping_data['method_title'] ?? '' );
				$item->set_method_id( $shipping_data['method_id'] ?? '' );
				$item->set_total( $shipping_data['total'] ?? 0 );
				$order->add_item( $item );
			}
		}

		// Handle discount
		// First, remove any existing discount fees
		foreach ( $order->get_fees() as $fee_id => $fee ) {
			if ( strpos( $fee->get_name(), 'Discount' ) !== false ) {
				$order->remove_item( $fee_id );
			}
		}
		
		// Remove existing coupons
		$order->remove_order_items( 'coupon' );
		
		// Remove discount meta
		$order->delete_meta_data( '_custom_discount_type' );
		$order->delete_meta_data( '_custom_discount_amount' );
		
		if ( isset( $order_data['discount_type'] ) && isset( $order_data['discount_amount'] ) ) {
			$discount_amount = floatval( $order_data['discount_amount'] );
			$discount_type = $order_data['discount_type'];
			
			if ( $discount_amount > 0 ) {
				// Calculate discount based on type
				$subtotal = 0;
				foreach ( $order->get_items() as $item ) {
					$subtotal += $item->get_total();
				}
				
				if ( $discount_type === 'percentage' ) {
					$discount_total = ( $subtotal * $discount_amount ) / 100;
				} else {
					$discount_total = $discount_amount;
				}
				
				// Create a fee item for discount (negative amount)
				$fee = new \WC_Order_Item_Fee();
				$fee->set_name( $discount_type === 'percentage' ? "Discount ({$discount_amount}%)" : 'Discount' );
				$fee->set_amount( -$discount_total );
				$fee->set_total( -$discount_total );
				$order->add_item( $fee );
				
				// Store discount info as meta
				$order->update_meta_data( '_custom_discount_type', $discount_type );
				$order->update_meta_data( '_custom_discount_amount', $discount_amount );
			}
		}

		// Recalculate totals
		$order->calculate_totals();
	}

	/**
	 * Get WooCommerce products
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_products( $request ) {
		try {
			$page = $request->get_param( 'page' ) ?: 1;
			$per_page = $request->get_param( 'per_page' ) ?: 20;
			$search = $request->get_param( 'search' );
			$status = $request->get_param( 'status' );
			$stock_status = $request->get_param( 'stock_status' );

			$args = [
				'limit' => $per_page,
				'offset' => ( $page - 1 ) * $per_page,
				'return' => 'objects',
			];

			if ( $search ) {
				$args['search'] = $search;
			}

			if ( $status ) {
				$args['status'] = $status;
			}

			if ( $stock_status ) {
				$args['stock_status'] = $stock_status;
			}

			$products = wc_get_products( $args );

			// Get total count
			$count_args = $args;
			$count_args['limit'] = -1;
			$count_args['return'] = 'ids';
			$total_products = wc_get_products( $count_args );
			$total = is_array( $total_products ) ? count( $total_products ) : 0;

			$formatted_products = [];
			foreach ( $products as $product ) {
				$formatted_products[] = $this->format_product_data( $product );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'products' => $formatted_products,
				'total' => $total,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get single WooCommerce product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_product( $request ) {
		try {
			$product_id = $request->get_param( 'id' );
			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found.', 'shop-explorer' ),
				], 404 );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'product' => $this->format_product_data( $product ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create WooCommerce product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_woocommerce_product( $request ) {
		try {
			$product_data = $request->get_json_params();

			if ( empty( $product_data ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No product data provided.', 'shop-explorer' ),
				], 400 );
			}

			$product = new \WC_Product_Simple();
			$this->update_product_data( $product, $product_data );
			$product_id = $product->save();

			if ( ! $product_id ) {
				return false;
			}

			$created_product = wc_get_product( $product_id );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Product created successfully.', 'shop-explorer' ),
				'product' => $this->format_product_data( $created_product ),
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Update WooCommerce product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_woocommerce_product( $request ) {
		try {
			$product_id = $request->get_param( 'id' );
			$product_data = $request->get_json_params();

			if ( empty( $product_data ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No product data provided.', 'shop-explorer' ),
				], 400 );
			}

			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found.', 'shop-explorer' ),
				], 404 );
			}

			$this->update_product_data( $product, $product_data );
			$product->save();

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Product updated successfully.', 'shop-explorer' ),
				'product' => $this->format_product_data( $product ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Delete WooCommerce product
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_woocommerce_product( $request ) {
		try {
			$product_id = $request->get_param( 'id' );
			$force = $request->get_param( 'force' ) ?: false;

			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found.', 'shop-explorer' ),
				], 404 );
			}

			$result = $product->delete( $force );

			if ( ! $result ) {
				return false;
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Product deleted successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce categories
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_categories( $request ) {
		try {
			$per_page = $request->get_param( 'per_page' ) ?: 100;

			$categories = get_terms( [
				'taxonomy' => 'product_cat',
				'hide_empty' => false,
				'number' => $per_page,
			] );

			$formatted_categories = [];
			foreach ( $categories as $category ) {
				$formatted_categories[] = [
					'id' => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
					'parent' => $category->parent,
					'description' => $category->description,
					'count' => $category->count,
				];
			}

			return new \WP_REST_Response( $formatted_categories, 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce tags
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_tags( $request ) {
		try {
			$per_page = $request->get_param( 'per_page' ) ?: 100;

			$tags = get_terms( [
				'taxonomy' => 'product_tag',
				'hide_empty' => false,
				'number' => $per_page,
			] );

			$formatted_tags = [];
			foreach ( $tags as $tag ) {
				$formatted_tags[] = [
					'id' => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
					'description' => $tag->description,
					'count' => $tag->count,
				];
			}

			return new \WP_REST_Response( $formatted_tags, 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce attributes
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_attributes( $request ) {
		try {
			$attributes = wc_get_attribute_taxonomies();

			$formatted_attributes = [];
			foreach ( $attributes as $attribute ) {
				$formatted_attributes[] = [
					'id' => $attribute->attribute_id,
					'name' => $attribute->attribute_name,
					'label' => $attribute->attribute_label,
					'type' => $attribute->attribute_type,
					'order_by' => $attribute->attribute_orderby,
					'has_archives' => $attribute->attribute_public,
				];
			}

			return new \WP_REST_Response( $formatted_attributes, 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce shipping classes
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_shipping_classes( $request ) {
		try {
			$per_page = $request->get_param( 'per_page' ) ?: 100;

			$shipping_classes = get_terms( [
				'taxonomy' => 'product_shipping_class',
				'hide_empty' => false,
				'number' => $per_page,
			] );

			$formatted_classes = [];
			foreach ( $shipping_classes as $class ) {
				$formatted_classes[] = [
					'id' => $class->term_id,
					'name' => $class->name,
					'slug' => $class->slug,
					'description' => $class->description,
					'count' => $class->count,
				];
			}

			return new \WP_REST_Response( $formatted_classes, 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce tax classes
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_tax_classes( $request ) {
		try {
			$tax_classes = \WC_Tax::get_tax_classes();

			$formatted_classes = [];
			$formatted_classes[] = [
				'id' => '',
				'name' => __( 'Standard', 'shop-explorer' ),
			];

			foreach ( $tax_classes as $class ) {
				$formatted_classes[] = [
					'id' => sanitize_title( $class ),
					'name' => $class,
				];
			}

			return new \WP_REST_Response( $formatted_classes, 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Upload WordPress media
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function upload_wordpress_media( $request ) {
		try {
			if ( ! function_exists( 'wp_handle_upload' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}

			$files = $request->get_file_params();

			if ( empty( $files['file'] ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'No file provided.', 'shop-explorer' ),
				], 400 );
			}

			$file = $files['file'];
			$upload_overrides = [ 'test_form' => false ];
			$movefile = wp_handle_upload( $file, $upload_overrides );

			if ( $movefile && ! isset( $movefile['error'] ) ) {
				$attachment = [
					'post_mime_type' => $movefile['type'],
					'post_title' => sanitize_file_name( $file['name'] ),
					'post_content' => '',
					'post_status' => 'inherit',
				];

				$attachment_id = wp_insert_attachment( $attachment, $movefile['file'] );

				if ( ! is_wp_error( $attachment_id ) ) {
					require_once ABSPATH . 'wp-admin/includes/image.php';
					$attachment_data = wp_generate_attachment_metadata( $attachment_id, $movefile['file'] );
					wp_update_attachment_metadata( $attachment_id, $attachment_data );

					return new \WP_REST_Response( [
						'success' => true,
						'attachment' => [
							'id' => $attachment_id,
							'url' => wp_get_attachment_url( $attachment_id ),
							'filename' => basename( $movefile['file'] ),
							'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
							'caption' => wp_get_attachment_caption( $attachment_id ),
							'title' => get_the_title( $attachment_id ),
							'mime' => get_post_mime_type( $attachment_id ),
						],
					], 200 );
				}
			}

			return new \WP_REST_Response( [
				'success' => false,
				'message' => $movefile['error'] ?? __( 'Upload failed.', 'shop-explorer' ),
			], 500 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Enqueue media scripts
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function enqueue_media_scripts( $request ) {
		try {
			wp_enqueue_media();

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Media scripts enqueued successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get product brand terms
	 *
	 * @param int $product_id Product ID
	 * @return array
	 */
	private function get_product_brands_terms( $product_id ) {
		$brand_taxonomies = [
			'product_brand',
			'product_brands',
			'pwb-brand',
			'yith_product_brand',
			'berocket_brand',
			'brand',
			'brands',
			'shopex_product_brand',
		];

		foreach ( $brand_taxonomies as $taxonomy ) {
			if ( taxonomy_exists( $taxonomy ) ) {
				$terms = wp_get_post_terms( $product_id, $taxonomy );
				if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
					return $terms;
				}
			}
		}

		return [];
	}

	/**
	 * Format product attributes for API response
	 *
	 * @param \WC_Product $product WooCommerce product object
	 * @return array
	 */
	private function format_product_attributes( $product ) {
		$formatted_attributes = [];
		$attributes = $product->get_attributes();
		
		foreach ( $attributes as $attribute ) {
			if ( ! $attribute instanceof \WC_Product_Attribute ) {
				continue;
			}
			
			$attribute_data = [
				'id' => $attribute->get_id(),
				'name' => $attribute->get_name(),
				'visible' => $attribute->get_visible(),
				'variation' => $attribute->get_variation(),
				'options' => [],
			];
			
			// Get attribute options
			$options = $attribute->get_options();
			
			if ( $attribute->is_taxonomy() ) {
				// For taxonomy attributes, get term names
				$terms = [];
				foreach ( $options as $term_id ) {
					$term = get_term( $term_id, $attribute->get_name() );
					if ( $term && ! is_wp_error( $term ) ) {
						$terms[] = $term->name;
					}
				}
				$attribute_data['options'] = $terms;
				$attribute_data['slug'] = str_replace( 'pa_', '', $attribute->get_name() );
			} else {
				// For custom attributes, options are already strings
				$attribute_data['options'] = $options;
				$attribute_data['slug'] = sanitize_title( $attribute->get_name() );
			}
			
			$formatted_attributes[] = $attribute_data;
		}
		
		return $formatted_attributes;
	}
	
	/**
	 * Format product data for API response
	 *
	 * @param \WC_Product $product WooCommerce product object
	 * @return array
	 */
	private function format_product_data( $product ) {
		$images = [];
		$image_ids = $product->get_gallery_image_ids();

		// Add featured image first
		if ( $product->get_image_id() ) {
			$featured_url = wp_get_attachment_url( $product->get_image_id() );
			if ( $featured_url ) {
				$images[] = [
					'id' => $product->get_image_id(),
					'src' => $featured_url,
					'alt' => get_post_meta( $product->get_image_id(), '_wp_attachment_image_alt', true ) ?: '',
					'name' => get_the_title( $product->get_image_id() ) ?: '',
				];
			}
		}

		// Add gallery images
		foreach ( $image_ids as $image_id ) {
			$gallery_url = wp_get_attachment_url( $image_id );
			if ( $gallery_url ) {
				$images[] = [
					'id' => $image_id,
					'src' => $gallery_url,
					'alt' => get_post_meta( $image_id, '_wp_attachment_image_alt', true ) ?: '',
					'name' => get_the_title( $image_id ) ?: '',
				];
			}
		}

		return [
			'id' => $product->get_id(),
			'name' => $product->get_name(),
			'slug' => $product->get_slug(),
			'permalink' => get_permalink( $product->get_id() ),
			'edit_url' => get_edit_post_link( $product->get_id(), 'raw' ),
			'type' => $product->get_type(),
			'status' => $product->get_status(),
			'featured' => $product->get_featured(),
			'catalog_visibility' => $product->get_catalog_visibility(),
			'description' => $product->get_description(),
			'short_description' => $product->get_short_description(),
			'sku' => $product->get_sku(),
			'price' => $product->get_price(),
			'regular_price' => $product->get_regular_price(),
			'sale_price' => $product->get_sale_price(),
			'date_on_sale_from' => $product->get_date_on_sale_from() ? gmdate( 'c', $product->get_date_on_sale_from()->getTimestamp() ) : null,
			'date_on_sale_to' => $product->get_date_on_sale_to() ? gmdate( 'c', $product->get_date_on_sale_to()->getTimestamp() ) : null,
			'virtual' => $product->get_virtual(),
			'downloadable' => $product->get_downloadable(),
			'downloads' => array_map( function( $download ) {
				return [
					'id' => $download->get_id(),
					'name' => $download->get_name(),
					'file' => $download->get_file(),
				];
			}, array_values( $product->get_downloads() ) ),
			'download_limit' => $product->get_download_limit(),
			'download_expiry' => $product->get_download_expiry(),
			'external_url' => method_exists( $product, 'get_product_url' ) ? $product->get_product_url() : '',
			'button_text' => method_exists( $product, 'get_button_text' ) ? $product->get_button_text() : '',
			'tax_status' => $product->get_tax_status(),
			'tax_class' => $product->get_tax_class(),
			'manage_stock' => $product->get_manage_stock(),
			'stock_quantity' => $product->get_stock_quantity(),
			'stock_status' => $product->get_stock_status(),
			'backorders' => $product->get_backorders(),
			'low_stock_amount' => $product->get_low_stock_amount(),
			'sold_individually' => $product->get_sold_individually(),
			'weight' => $product->get_weight(),
			'dimensions' => [
				'length' => $product->get_length(),
				'width' => $product->get_width(),
				'height' => $product->get_height(),
			],
			'shipping_class' => $product->get_shipping_class(),
			'reviews_allowed' => $product->get_reviews_allowed(),
			'upsell_ids' => $product->get_upsell_ids(),
			'cross_sell_ids' => $product->get_cross_sell_ids(),
			'parent_id' => $product->get_parent_id(),
			'purchase_note' => $product->get_purchase_note(),
			'categories' => wp_get_post_terms( $product->get_id(), 'product_cat' ),
			'tags' => wp_get_post_terms( $product->get_id(), 'product_tag' ),
			'brands' => $this->get_product_brands_terms( $product->get_id() ),
			'images' => $images,
			'attributes' => $this->format_product_attributes( $product ),
			'default_attributes' => $product->get_default_attributes(),
			'menu_order' => $product->get_menu_order(),
			'meta_data' => $product->get_meta_data(),
			'custom_fields' => $this->get_product_custom_fields( $product->get_id() ),
		];
	}
	
	/**
	 * Get custom fields for a product
	 *
	 * @param int $product_id Product ID
	 * @return array Custom fields
	 */
	private function get_product_custom_fields( $product_id ) {
		$custom_fields = [];
		$meta_data = get_post_meta( $product_id );
		
		foreach ( $meta_data as $key => $value ) {
			// Only get custom fields that start with _custom_ but NOT _custom_field_config_
			if ( strpos( $key, '_custom_' ) === 0 && strpos( $key, '_custom_field_config_' ) !== 0 ) {
				$field_key = str_replace( '_custom_', '', $key );
				
				// Skip if the field key itself contains "field_config" (corrupted data)
				if ( strpos( $field_key, 'field_config' ) !== false ) {
					continue;
				}
				
				// Get field configuration
				$field_config = get_post_meta( $product_id, '_custom_field_config_' . $field_key, true );
				
				$field_value = is_array( $value ) ? $value[0] : $value;
				
				// Skip if value is an object/array (serialized data we don't want)
				if ( is_array( $field_value ) || is_object( $field_value ) ) {
					continue;
				}
				
				// Skip if value is serialized string
				if ( is_string( $field_value ) && ( strpos( $field_value, 'a:' ) === 0 || strpos( $field_value, 'O:' ) === 0 ) ) {
					continue;
				}
				
				$custom_fields[] = [
					'key' => $field_key,
					'value' => $field_value,
					'type' => is_array( $field_config ) && isset( $field_config['type'] ) ? $field_config['type'] : 'text',
					'editable' => is_array( $field_config ) && isset( $field_config['editable'] ) ? (bool) $field_config['editable'] : false,
					'id' => time() . rand( 1000, 9999 ), // Generate a unique ID
				];
			}
		}
		
		return $custom_fields;
	}

	/**
	 * Update product data from request
	 *
	 * @param \WC_Product $product WooCommerce product object
	 * @param array       $product_data Product data from request
	 */
	private function update_product_data( $product, $product_data ) {
		// Basic product data
		if ( isset( $product_data['name'] ) ) {
			$product->set_name( $product_data['name'] );
		}

		if ( isset( $product_data['slug'] ) ) {
			$product->set_slug( $product_data['slug'] );
		}

		if ( isset( $product_data['status'] ) ) {
			$product->set_status( $product_data['status'] );
		}

		if ( isset( $product_data['featured'] ) ) {
			$product->set_featured( $product_data['featured'] );
		}

		if ( isset( $product_data['catalog_visibility'] ) ) {
			$product->set_catalog_visibility( $product_data['catalog_visibility'] );
		}

		if ( isset( $product_data['description'] ) ) {
			$product->set_description( $product_data['description'] );
		}

		if ( isset( $product_data['short_description'] ) ) {
			$product->set_short_description( $product_data['short_description'] );
		}

		if ( isset( $product_data['sku'] ) ) {
			$product->set_sku( $product_data['sku'] );
		}

		// Pricing
		if ( isset( $product_data['regular_price'] ) ) {
			$product->set_regular_price( $product_data['regular_price'] );
		}

		if ( isset( $product_data['sale_price'] ) ) {
			$product->set_sale_price( $product_data['sale_price'] );
		}

		// Inventory
		if ( isset( $product_data['manage_stock'] ) ) {
			$product->set_manage_stock( $product_data['manage_stock'] );
		}

		if ( isset( $product_data['stock_quantity'] ) ) {
			$product->set_stock_quantity( $product_data['stock_quantity'] );
		}

		if ( isset( $product_data['stock_status'] ) ) {
			$product->set_stock_status( $product_data['stock_status'] );
		}

		// Shipping
		if ( isset( $product_data['weight'] ) ) {
			$product->set_weight( $product_data['weight'] );
		}

		if ( isset( $product_data['dimensions'] ) ) {
			$dimensions = $product_data['dimensions'];
			$product->set_length( $dimensions['length'] ?? '' );
			$product->set_width( $dimensions['width'] ?? '' );
			$product->set_height( $dimensions['height'] ?? '' );
		}

		// Categories
		if ( isset( $product_data['categories'] ) && is_array( $product_data['categories'] ) ) {
			$category_ids = array_map( function ( $cat ) {
				if ( is_array( $cat ) && isset( $cat['id'] ) ) {
					return (int) $cat['id'];
				} elseif ( is_numeric( $cat ) ) {
					return (int) $cat;
				}
				return 0;
			}, $product_data['categories'] );
			$category_ids = array_filter( $category_ids ); // Remove zeros
			$product->set_category_ids( $category_ids );
		}

		// Tags
		if ( isset( $product_data['tags'] ) && is_array( $product_data['tags'] ) ) {
			$tag_ids = array_map( function ( $tag ) {
				if ( is_array( $tag ) && isset( $tag['id'] ) ) {
					return (int) $tag['id'];
				} elseif ( is_numeric( $tag ) ) {
					return (int) $tag;
				}
				return 0;
			}, $product_data['tags'] );
			$tag_ids = array_filter( $tag_ids ); // Remove zeros
			$product->set_tag_ids( $tag_ids );
		}

		// Brands
		if ( isset( $product_data['brands'] ) && is_array( $product_data['brands'] ) ) {
			// Ensure brand taxonomy exists
			if ( ! taxonomy_exists( 'product_brand' ) ) {
				$this->register_brand_taxonomy();
			}

			$brand_ids = array_map( function ( $brand ) {
				if ( is_array( $brand ) && isset( $brand['id'] ) ) {
					return (int) $brand['id'];
				} elseif ( is_numeric( $brand ) ) {
					return (int) $brand;
				}
				return 0;
			}, $product_data['brands'] );
			$brand_ids = array_filter( $brand_ids ); // Remove zeros

			// Set brand terms for the product
			wp_set_object_terms( $product->get_id(), $brand_ids, 'product_brand' );
		}

		// Images - handle both formats
		if ( isset( $product_data['images'] ) ) {
			$image_ids = [];
			foreach ( $product_data['images'] as $index => $image ) {
				if ( isset( $image['id'] ) ) {
					$image_ids[] = $image['id'];
				}
			}

			if ( ! empty( $image_ids ) ) {
				$product->set_image_id( $image_ids[0] );
				$product->set_gallery_image_ids( array_slice( $image_ids, 1 ) );
			}
		} else {
			// Handle featured image and gallery images separately
			if ( isset( $product_data['featured_image'] ) && is_array( $product_data['featured_image'] ) && isset( $product_data['featured_image']['id'] ) ) {
				$product->set_image_id( $product_data['featured_image']['id'] );
			}

			if ( isset( $product_data['gallery_images'] ) && is_array( $product_data['gallery_images'] ) ) {
				$gallery_ids = [];
				foreach ( $product_data['gallery_images'] as $gallery_image ) {
					if ( isset( $gallery_image['id'] ) ) {
						$gallery_ids[] = $gallery_image['id'];
					}
				}
				$product->set_gallery_image_ids( $gallery_ids );
			}
		}
	}

	/**
	 * Check authentication permission
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return bool
	 */
	public function check_media_authentication( $request ) {
		return is_user_logged_in();
	}


	/**
	 * Get product variations
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_product_variations( $request ) {
		try {
			$product_id = (int) $request->get_param( 'product_id' );

			if ( ! function_exists( 'wc_get_product' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not active.', 'shop-explorer' ),
				], 500 );
			}

			$product = wc_get_product( $product_id );
			if ( ! $product || $product->get_type() !== 'variable' ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found or not a variable product.', 'shop-explorer' ),
				], 404 );
			}

			$variations = $product->get_children();
			$variation_data = [];

			foreach ( $variations as $variation_id ) {
				$variation = wc_get_product( $variation_id );
				if ( $variation ) {
					$variation_data[] = [
						'id' => $variation->get_id(),
						'sku' => $variation->get_sku(),
						'regular_price' => $variation->get_regular_price(),
						'sale_price' => $variation->get_sale_price(),
						'date_on_sale_from' => $variation->get_date_on_sale_from() ? $variation->get_date_on_sale_from()->format( 'Y-m-d\TH:i' ) : '',
						'date_on_sale_to' => $variation->get_date_on_sale_to() ? $variation->get_date_on_sale_to()->format( 'Y-m-d\TH:i' ) : '',
						'stock_quantity' => $variation->get_stock_quantity(),
						'stock_status' => $variation->get_stock_status(),
						'manage_stock' => $variation->get_manage_stock(),
						'backorders' => $variation->get_backorders(),
						'low_stock_amount' => $variation->get_low_stock_amount(),
						'enabled' => $variation->get_status() === 'publish',
						'virtual' => $variation->is_virtual(),
						'downloadable' => $variation->is_downloadable(),
						'downloadable_files' => array_map( function( $download ) {
							return [
								'id' => $download->get_id(),
								'name' => $download->get_name(),
								'file' => $download->get_file(),
							];
						}, array_values( $variation->get_downloads() ) ),
						'download_limit' => $variation->get_download_limit(),
						'download_expiry' => $variation->get_download_expiry(),
						'tax_status' => $variation->get_tax_status(),
						'tax_class' => $variation->get_tax_class(),
						'weight' => $variation->get_weight(),
						'dimensions' => [
							'length' => $variation->get_length(),
							'width' => $variation->get_width(),
							'height' => $variation->get_height(),
						],
						'shipping_class' => $variation->get_shipping_class(),
						'description' => $variation->get_description(),
						'attributes' => $variation->get_variation_attributes(),
						'image' => $variation->get_image_id() ? [
							'id' => $variation->get_image_id(),
							'src' => wp_get_attachment_image_url( $variation->get_image_id(), 'thumbnail' ),
							'alt' => get_post_meta( $variation->get_image_id(), '_wp_attachment_image_alt', true ),
						] : null,
						// Global identifiers
						'gtin' => $variation->get_meta( '_gtin', true ),
						'upc' => $variation->get_meta( '_upc', true ),
						'ean' => $variation->get_meta( '_ean', true ),
						'isbn' => $variation->get_meta( '_isbn', true ),
					];
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'variations' => $variation_data,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to retrieve variations.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Generate product variations
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function generate_product_variations( $request ) {
		try {
			$product_id = (int) $request->get_param( 'product_id' );
			$attributes = $request->get_param( 'attributes' );

			if ( ! function_exists( 'wc_get_product' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not active.', 'shop-explorer' ),
				], 500 );
			}

			$product = wc_get_product( $product_id );
			if ( ! $product || $product->get_type() !== 'variable' ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found or not a variable product.', 'shop-explorer' ),
				], 404 );
			}

			// Generate all possible combinations
			$combinations = $this->generate_attribute_combinations( $attributes );

			if ( count( $combinations ) > 50 ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Too many combinations. Maximum 50 variations allowed.', 'shop-explorer' ),
				], 400 );
			}

			$created_variations = [];
			$parent_sku = $product->get_sku();
			$variation_counter = 1;
			
			foreach ( $combinations as $combination ) {
				$variation = new \WC_Product_Variation();
				$variation->set_parent_id( $product_id );
				$variation->set_attributes( $combination );
				$variation->set_status( 'publish' );
				$variation->set_manage_stock( false );
				$variation->set_stock_status( 'instock' );
				
				// Auto-generate unique SKU
				if ( ! empty( $parent_sku ) ) {
					$variation_sku = $parent_sku . '-' . $variation_counter;
					// Ensure SKU is unique
					while ( wc_get_product_id_by_sku( $variation_sku ) ) {
						$variation_counter++;
						$variation_sku = $parent_sku . '-' . $variation_counter;
					}
					$variation->set_sku( $variation_sku );
				}
				
				$variation->save();
				$created_variations[] = $variation->get_id();
				$variation_counter++;
			}

			return new \WP_REST_Response( [
				'success' => true,
				/* translators: %s: is the product id */
				'message' => sprintf( __( '%d variations created successfully.', 'shop-explorer' ), count( $created_variations ) ),
				'variations' => $created_variations,
				'created_count' => count( $created_variations ),
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to generate variations.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Create product variation
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_product_variation( $request ) {
		try {
			$product_id = (int) $request->get_param( 'product_id' );
			$variation_data = $request->get_params();

			if ( ! function_exists( 'wc_get_product' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not active.', 'shop-explorer' ),
				], 500 );
			}

			$product = wc_get_product( $product_id );
			if ( ! $product || $product->get_type() !== 'variable' ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product not found or not a variable product.', 'shop-explorer' ),
				], 404 );
			}

			$variation = new \WC_Product_Variation();
			$variation->set_parent_id( $product_id );

			// Set variation data
			if ( isset( $variation_data['sku'] ) ) {
				$variation->set_sku( sanitize_text_field( $variation_data['sku'] ) );
			}

			if ( isset( $variation_data['regular_price'] ) ) {
				$variation->set_regular_price( sanitize_text_field( $variation_data['regular_price'] ) );
			}

			if ( isset( $variation_data['sale_price'] ) ) {
				$variation->set_sale_price( sanitize_text_field( $variation_data['sale_price'] ) );
			}

			if ( isset( $variation_data['manage_stock'] ) ) {
				$variation->set_manage_stock( (bool) $variation_data['manage_stock'] );
			}

			if ( isset( $variation_data['stock_quantity'] ) ) {
				$variation->set_stock_quantity( (int) $variation_data['stock_quantity'] );
			}

			if ( isset( $variation_data['weight'] ) ) {
				$variation->set_weight( sanitize_text_field( $variation_data['weight'] ) );
			}

			if ( isset( $variation_data['dimensions'] ) ) {
				$dimensions = $variation_data['dimensions'];
				if ( isset( $dimensions['length'] ) ) {
					$variation->set_length( sanitize_text_field( $dimensions['length'] ) );
				}
				if ( isset( $dimensions['width'] ) ) {
					$variation->set_width( sanitize_text_field( $dimensions['width'] ) );
				}
				if ( isset( $dimensions['height'] ) ) {
					$variation->set_height( sanitize_text_field( $dimensions['height'] ) );
				}
			}

			if ( isset( $variation_data['virtual'] ) ) {
				$variation->set_virtual( (bool) $variation_data['virtual'] );
			}

			if ( isset( $variation_data['downloadable'] ) ) {
				$variation->set_downloadable( (bool) $variation_data['downloadable'] );
			}

			if ( isset( $variation_data['attributes'] ) ) {
				$variation->set_attributes( $variation_data['attributes'] );
			}

			$variation->set_status( isset( $variation_data['enabled'] ) && $variation_data['enabled'] ? 'publish' : 'private' );

			$variation->save();

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Variation created successfully.', 'shop-explorer' ),
				'variation' => [
					'id' => $variation->get_id(),
					'sku' => $variation->get_sku(),
					'regular_price' => $variation->get_regular_price(),
					'sale_price' => $variation->get_sale_price(),
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to create variation.', 'shop-explorer' ),
			], 500 );
		}
	}

	
	/**
	 * Update product variation
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_product_variation( $request ) {
		try {
			$product_id = (int) $request->get_param( 'product_id' );
			$variation_id = (int) $request->get_param( 'variation_id' );
			$variation_data = $request->get_params();

			if ( ! function_exists( 'wc_get_product' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not active.', 'shop-explorer' ),
				], 500 );
			}

			$variation = wc_get_product( $variation_id );
			if ( ! $variation || $variation->get_parent_id() !== $product_id ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Variation not found.', 'shop-explorer' ),
				], 404 );
			}

			// Update variation data
			if ( isset( $variation_data['sku'] ) ) {
				$variation->set_sku( sanitize_text_field( $variation_data['sku'] ) );
			}

			if ( isset( $variation_data['regular_price'] ) ) {
				$variation->set_regular_price( sanitize_text_field( $variation_data['regular_price'] ) );
			}

			if ( isset( $variation_data['sale_price'] ) ) {
				$variation->set_sale_price( sanitize_text_field( $variation_data['sale_price'] ) );
			}
			
			// Sale price dates
			if ( isset( $variation_data['date_on_sale_from'] ) ) {
				$variation->set_date_on_sale_from( $variation_data['date_on_sale_from'] );
			}
			if ( isset( $variation_data['date_on_sale_to'] ) ) {
				$variation->set_date_on_sale_to( $variation_data['date_on_sale_to'] );
			}
			
			// Stock management
			if ( isset( $variation_data['manage_stock'] ) ) {
				$variation->set_manage_stock( (bool) $variation_data['manage_stock'] );
			}
			if ( isset( $variation_data['stock_quantity'] ) ) {
				$variation->set_stock_quantity( (int) $variation_data['stock_quantity'] );
			}
			if ( isset( $variation_data['stock_status'] ) ) {
				$variation->set_stock_status( sanitize_text_field( $variation_data['stock_status'] ) );
			}
			if ( isset( $variation_data['backorders'] ) ) {
				$variation->set_backorders( sanitize_text_field( $variation_data['backorders'] ) );
			}
			if ( isset( $variation_data['low_stock_amount'] ) ) {
				$variation->set_low_stock_amount( $variation_data['low_stock_amount'] );
			}
			
			// Physical properties
			if ( isset( $variation_data['weight'] ) ) {
				$variation->set_weight( $variation_data['weight'] );
			}
			if ( isset( $variation_data['dimensions'] ) ) {
				$dimensions = $variation_data['dimensions'];
				if ( isset( $dimensions['length'] ) ) {
					$variation->set_length( $dimensions['length'] );
				}
				if ( isset( $dimensions['width'] ) ) {
					$variation->set_width( $dimensions['width'] );
				}
				if ( isset( $dimensions['height'] ) ) {
					$variation->set_height( $dimensions['height'] );
				}
			}
			
			// Shipping class - variations use shipping_class_id
			if ( isset( $variation_data['shipping_class'] ) ) {
				$shipping_class = sanitize_text_field( $variation_data['shipping_class'] );
				if ( ! empty( $shipping_class ) ) {
					$term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
					if ( $term ) {
						$variation->set_shipping_class_id( $term->term_id );
					}
				} else {
					$variation->set_shipping_class_id( 0 );
				}
			}
			if ( isset( $variation_data['virtual'] ) ) {
				$variation->set_virtual( (bool) $variation_data['virtual'] );
			}
			if ( isset( $variation_data['downloadable'] ) ) {
				$variation->set_downloadable( (bool) $variation_data['downloadable'] );
			}
			
			// Tax options
			if ( isset( $variation_data['tax_status'] ) ) {
				$variation->set_tax_status( sanitize_text_field( $variation_data['tax_status'] ) );
			}
			if ( isset( $variation_data['tax_class'] ) ) {
				$variation->set_tax_class( sanitize_text_field( $variation_data['tax_class'] ) );
			}
			
			// Description
			if ( isset( $variation_data['description'] ) ) {
				$variation->set_description( wp_kses_post( $variation_data['description'] ) );
			}
			
			// Image
			if ( isset( $variation_data['image_id'] ) ) {
				$variation->set_image_id( (int) $variation_data['image_id'] );
			}
			
			// Enabled status
			if ( isset( $variation_data['enabled'] ) ) {
				$variation->set_status( $variation_data['enabled'] ? 'publish' : 'private' );
			}
			
			// Global identifiers (custom meta)
			if ( isset( $variation_data['gtin'] ) ) {
				$variation->update_meta_data( '_gtin', sanitize_text_field( $variation_data['gtin'] ) );
			}
			if ( isset( $variation_data['upc'] ) ) {
				$variation->update_meta_data( '_upc', sanitize_text_field( $variation_data['upc'] ) );
			}
			if ( isset( $variation_data['ean'] ) ) {
				$variation->update_meta_data( '_ean', sanitize_text_field( $variation_data['ean'] ) );
			}
			if ( isset( $variation_data['isbn'] ) ) {
				$variation->update_meta_data( '_isbn', sanitize_text_field( $variation_data['isbn'] ) );
			}
			
			// Handle downloadable files
			if ( isset( $variation_data['downloadable_files'] ) && is_array( $variation_data['downloadable_files'] ) ) {
				$downloads = [];
				foreach ( $variation_data['downloadable_files'] as $file ) {
					if ( isset( $file['name'] ) && isset( $file['file'] ) && ! empty( $file['file'] ) ) {
						$download = new \WC_Product_Download();
						$download->set_id( isset( $file['id'] ) ? $file['id'] : md5( $file['file'] ) );
						$download->set_name( sanitize_text_field( $file['name'] ) );
						$download->set_file( esc_url_raw( $file['file'] ) );
						$downloads[ $download->get_id() ] = $download;
					}
				}
				$variation->set_downloads( $downloads );
			}
			
			// Handle download limit and expiry
			if ( isset( $variation_data['download_limit'] ) ) {
				$variation->set_download_limit( (int) $variation_data['download_limit'] );
			}
			if ( isset( $variation_data['download_expiry'] ) ) {
				$variation->set_download_expiry( (int) $variation_data['download_expiry'] );
			}

			$variation->save();

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Variation updated successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			error_log( 'Variation update error: ' . $e->getMessage() );
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to update variation: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Delete product variation
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_product_variation( $request ) {
		try {
			$product_id = (int) $request->get_param( 'product_id' );
			$variation_id = (int) $request->get_param( 'variation_id' );

			if ( ! function_exists( 'wc_get_product' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not active.', 'shop-explorer' ),
				], 500 );
			}

			$variation = wc_get_product( $variation_id );
			if ( ! $variation || $variation->get_parent_id() !== $product_id ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Variation not found.', 'shop-explorer' ),
				], 404 );
			}

			$variation->delete( true );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => __( 'Variation deleted successfully.', 'shop-explorer' ),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to delete variation.', 'shop-explorer' ),
			], 500 );
		}
	}


	/**
	 * Generate attribute combinations
	 *
	 * @param array $attributes Attributes array
	 * @return array
	 */
	private function generate_attribute_combinations( $attributes ) {
		$combinations = [ [] ];

		foreach ( $attributes as $attribute ) {
			$new_combinations = [];
			foreach ( $combinations as $combination ) {
				if ( isset( $attribute['terms'] ) && is_array( $attribute['terms'] ) ) {
					foreach ( $attribute['terms'] as $term ) {
						$new_combination = $combination;
						// Use proper attribute key format for WooCommerce
						$attr_key = isset( $attribute['id'] ) && $attribute['id'] > 0 
							? 'attribute_pa_' . sanitize_title( $attribute['slug'] ?? $attribute['name'] )
							: 'attribute_' . sanitize_title( $attribute['slug'] ?? $attribute['name'] );
						$new_combination[ $attr_key ] = $term['name'];
						$new_combinations[] = $new_combination;
					}
				}
			}
			$combinations = $new_combinations;
		}

		return $combinations;
	}

	/**
	 * Get frontend dashboard settings
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response
	 */
	public function get_frontend_settings( $request ) {
		try {
			$settings = get_option( 'shop_explorer_frontend_settings', [
				'orders_management' => [
					'enabled' => false,
					'default_statuses' => [],
					'custom_statuses' => [],
					'filter_settings' => [],
					'filter_sections' => [],
				],
				'products_management' => [
					'enabled' => false,
				],
				'customer_management' => [
					'enabled' => false,
				],
			]);

			return new \WP_REST_Response([
				'success' => true,
				'settings' => $settings,
			], 200);
		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Save frontend dashboard settings
	 *
	 * @param \WP_REST_Request $request Request object.
	 * @return \WP_REST_Response
	 */
	public function save_frontend_settings( $request ) {
		try {
			$settings = $request->get_json_params();

			if ( empty( $settings ) ) {
				throw new \Exception( 'No settings provided' );
			}

			update_option( 'shop_explorer_frontend_settings', $settings );

			return new \WP_REST_Response([
				'success' => true,
				'message' => 'Frontend settings saved successfully',
				'settings' => $settings,
			], 200);
		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Get order notes
	 */
	public function get_order_notes( $request ) {
		$order_id = $request->get_param( 'id' );
		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Order not found.', 'shop-explorer' ),
			], 404);
		}

		$notes = wc_get_order_notes([
			'order_id' => $order_id,
		]);

		$formatted_notes = [];
		foreach ( $notes as $note ) {
			$formatted_notes[] = [
				'id' => $note->id,
				'content' => $note->content,
				'type' => $note->customer_note ? 'customer' : 'private',
				'date' => $note->date_created->date( 'c' ),
				'author' => $note->added_by,
			];
		}

		return new \WP_REST_Response([
			'success' => true,
			'notes' => $formatted_notes,
		], 200);
	}

	/**
	 * Add order note
	 */
	public function add_order_note( $request ) {
		$order_id = $request->get_param( 'id' );
		$content = $request->get_param( 'content' );
		$note_type = $request->get_param( 'note_type' );

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Order not found.', 'shop-explorer' ),
			], 404);
		}

		if ( empty( $content ) ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Note content is required.', 'shop-explorer' ),
			], 400);
		}

		$is_customer_note = ( $note_type === 'customer' ) ? 1 : 0;

		$note_id = $order->add_order_note(
			$content,
			$is_customer_note,
			true
		);

		if ( ! $note_id ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Failed to add note.', 'shop-explorer' ),
			], 500);
		}

		return new \WP_REST_Response([
			'success' => true,
			'message' => __( 'Note added successfully.', 'shop-explorer' ),
			'note_id' => $note_id,
		], 200);
	}

	/**
	 * Update order note
	 */
	public function update_order_note( $request ) {
		$order_id = $request->get_param( 'id' );
		$note_id = $request->get_param( 'note_id' );
		$content = $request->get_param( 'content' );

		global $wpdb;

		$updated = $wpdb->update(
			$wpdb->comments,
			[ 'comment_content' => $content ],
			[ 'comment_ID' => $note_id, 'comment_post_ID' => $order_id ],
			[ '%s' ],
			[ '%d', '%d' ]
		);

		if ( $updated === false ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Failed to update note.', 'shop-explorer' ),
			], 500);
		}

		return new \WP_REST_Response([
			'success' => true,
			'message' => __( 'Note updated successfully.', 'shop-explorer' ),
		], 200);
	}

	/**
	 * Delete order note
	 */
	public function delete_order_note( $request ) {
		$note_id = $request->get_param( 'note_id' );

		$deleted = wc_delete_order_note( $note_id );

		if ( ! $deleted ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Failed to delete note.', 'shop-explorer' ),
			], 500);
		}

		return new \WP_REST_Response([
			'success' => true,
			'message' => __( 'Note deleted successfully.', 'shop-explorer' ),
		], 200);
	}

	/**
	 * Refund order
	 */
	public function refund_order( $request ) {
		$order_id = $request->get_param( 'id' );
		$amount = $request->get_param( 'amount' );
		$reason = $request->get_param( 'reason' );

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Order not found.', 'shop-explorer' ),
			], 404);
		}

		// Convert amount to float for validation
		$amount_float = floatval( $amount );
		$order_total = floatval( $order->get_total() );


		if ( $amount_float <= 0 ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Invalid refund amount.', 'shop-explorer' ),
			], 400);
		}

		
		if ( $amount_float > $order_total ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => __( 'Refund amount cannot exceed order total.', 'shop-explorer' ),
			], 400);
		}

		try {
			// For manual refunds without line items, we need to use a different approach
			// Create the refund object directly
			$refund = new \WC_Order_Refund();
			$refund->set_parent_id( $order_id );
			$refund->set_amount( $amount_float );
			$refund->set_reason( $reason ?: __( 'Refund processed', 'shop-explorer' ) );
			$refund->save();
			
			if ( ! $refund->get_id() ) {
				throw new \Exception( __( 'Failed to create refund.', 'shop-explorer' ) );
			}
			
			if ( ! $refund ) {
				throw new \Exception( 'Failed to create refund - null returned' );
			}

			// Update order status to refunded if full refund
			if ( $amount_float >= $order_total ) {
			
				$order->update_status( 'refunded', __( 'Order fully refunded.', 'shop-explorer' ) );
			} else {
				
				$order->add_order_note(
					sprintf(
						/* translators: %s: refund amount */
						__( 'Partial refund of %s processed.', 'shop-explorer' ),
						wc_price( $amount_float )
					)
				);
			}

			return new \WP_REST_Response([
				'success' => true,
				'message' => __( 'Refund processed successfully.', 'shop-explorer' ),
				'refund_id' => $refund->get_id(),
			], 200);

		} catch ( \Exception $e ) {
			
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Get all categories
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_categories( $request ) {
		try {
			$categories = get_terms( [
				'taxonomy' => 'product_cat',
				'hide_empty' => false,
				'orderby' => 'name',
				'order' => 'ASC',
			] );

			if ( is_wp_error( $categories ) ) {
				throw new \Exception( $categories->get_error_message() );
			}

			$formatted_categories = [];
			foreach ( $categories as $category ) {
				$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
				$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;
				$display = get_term_meta( $category->term_id, 'display_type', true );

				$formatted_categories[] = [
					'id' => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
					'description' => $category->description,
					'parent' => $category->parent,
					'count' => $category->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
					'display' => $display ?: 'default',
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'categories' => $formatted_categories,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get single category
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_category( $request ) {
		try {
			$category_id = $request->get_param( 'id' );
			$category = get_term( $category_id, 'product_cat' );

			if ( is_wp_error( $category ) ) {
				throw new \Exception( $category->get_error_message() );
			}

			if ( ! $category ) {
				throw new \Exception( 'Category not found' );
			}

			$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
			$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;
			$display = get_term_meta( $category->term_id, 'display_type', true );

			return new \WP_REST_Response( [
				'success' => true,
				'category' => [
					'id' => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
					'description' => $category->description,
					'parent' => $category->parent,
					'count' => $category->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
					'display' => $display ?: 'default',
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Create new category
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_category( $request ) {
		try {
			$data = $request->get_json_params();

			if ( empty( $data['name'] ) ) {
				throw new \Exception( 'Category name is required' );
			}

			$args = [
				'description' => $data['description'] ?? '',
				'parent' => $data['parent'] ?? 0,
			];

			if ( ! empty( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			$result = wp_insert_term( $data['name'], 'product_cat', $args );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$category_id = $result['term_id'];

			// Save thumbnail if provided
			if ( ! empty( $data['thumbnail_id'] ) ) {
				update_term_meta( $category_id, 'thumbnail_id', $data['thumbnail_id'] );
			}

			// Save display type if provided
			if ( ! empty( $data['display'] ) ) {
				update_term_meta( $category_id, 'display_type', $data['display'] );
			}

			$category = get_term( $category_id, 'product_cat' );
			$thumbnail_id = get_term_meta( $category_id, 'thumbnail_id', true );
			$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;
			$display = get_term_meta( $category_id, 'display_type', true );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Category created successfully',
				'category' => [
					'id' => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
					'description' => $category->description,
					'parent' => $category->parent,
					'count' => $category->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
					'display' => $display ?: 'default',
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Update category
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_category( $request ) {
		try {
			$category_id = $request->get_param( 'id' );
			$data = $request->get_json_params();

			$category = get_term( $category_id, 'product_cat' );
			if ( is_wp_error( $category ) || ! $category ) {
				throw new \Exception( 'Category not found' );
			}

			$args = [];

			if ( isset( $data['name'] ) ) {
				$args['name'] = $data['name'];
			}

			if ( isset( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			if ( isset( $data['description'] ) ) {
				$args['description'] = $data['description'];
			}

			if ( isset( $data['parent'] ) ) {
				$args['parent'] = $data['parent'];
			}

			if ( ! empty( $args ) ) {
				$result = wp_update_term( $category_id, 'product_cat', $args );

				if ( is_wp_error( $result ) ) {
					throw new \Exception( $result->get_error_message() );
				}
			}

			// Update thumbnail if provided
			if ( isset( $data['thumbnail_id'] ) ) {
				if ( $data['thumbnail_id'] ) {
					update_term_meta( $category_id, 'thumbnail_id', $data['thumbnail_id'] );
				} else {
					delete_term_meta( $category_id, 'thumbnail_id' );
				}
			}

			// Update display type if provided
			if ( isset( $data['display'] ) ) {
				update_term_meta( $category_id, 'display_type', $data['display'] );
			}

			$updated_category = get_term( $category_id, 'product_cat' );
			$thumbnail_id = get_term_meta( $category_id, 'thumbnail_id', true );
			$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;
			$display = get_term_meta( $category_id, 'display_type', true );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Category updated successfully',
				'category' => [
					'id' => $updated_category->term_id,
					'name' => $updated_category->name,
					'slug' => $updated_category->slug,
					'description' => $updated_category->description,
					'parent' => $updated_category->parent,
					'count' => $updated_category->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
					'display' => $display ?: 'default',
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Delete category
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_category( $request ) {
		try {
			$category_id = $request->get_param( 'id' );

			$category = get_term( $category_id, 'product_cat' );
			if ( is_wp_error( $category ) || ! $category ) {
				throw new \Exception( 'Category not found' );
			}

			// Delete thumbnail meta
			delete_term_meta( $category_id, 'thumbnail_id' );

			$result = wp_delete_term( $category_id, 'product_cat' );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			if ( ! $result ) {
				throw new \Exception( 'Failed to delete category' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Category deleted successfully',
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get all tags
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_tags( $request ) {
		try {
			$tags = get_terms( [
				'taxonomy' => 'product_tag',
				'hide_empty' => false,
				'orderby' => 'name',
				'order' => 'ASC',
			] );

			if ( is_wp_error( $tags ) ) {
				throw new \Exception( $tags->get_error_message() );
			}

			$formatted_tags = [];
			foreach ( $tags as $tag ) {
				$formatted_tags[] = [
					'id' => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
					'description' => $tag->description,
					'count' => $tag->count,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'tags' => $formatted_tags,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get single tag
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_tag( $request ) {
		try {
			$tag_id = $request->get_param( 'id' );
			$tag = get_term( $tag_id, 'product_tag' );

			if ( is_wp_error( $tag ) ) {
				throw new \Exception( $tag->get_error_message() );
			}

			if ( ! $tag ) {
				throw new \Exception( 'Tag not found' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'tag' => [
					'id' => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
					'description' => $tag->description,
					'count' => $tag->count,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Create new tag
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_tag( $request ) {
		try {
			$data = $request->get_json_params();

			if ( empty( $data['name'] ) ) {
				throw new \Exception( 'Tag name is required' );
			}

			$args = [
				'description' => $data['description'] ?? '',
			];

			if ( ! empty( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			$result = wp_insert_term( $data['name'], 'product_tag', $args );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$tag_id = $result['term_id'];
			$tag = get_term( $tag_id, 'product_tag' );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Tag created successfully',
				'tag' => [
					'id' => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
					'description' => $tag->description,
					'count' => $tag->count,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Update tag
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_tag( $request ) {
		try {
			$tag_id = $request->get_param( 'id' );
			$data = $request->get_json_params();

			$tag = get_term( $tag_id, 'product_tag' );
			if ( is_wp_error( $tag ) || ! $tag ) {
				throw new \Exception( 'Tag not found' );
			}

			$args = [];

			if ( isset( $data['name'] ) ) {
				$args['name'] = $data['name'];
			}

			if ( isset( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			if ( isset( $data['description'] ) ) {
				$args['description'] = $data['description'];
			}

			if ( ! empty( $args ) ) {
				$result = wp_update_term( $tag_id, 'product_tag', $args );

				if ( is_wp_error( $result ) ) {
					throw new \Exception( $result->get_error_message() );
				}
			}

			$updated_tag = get_term( $tag_id, 'product_tag' );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Tag updated successfully',
				'tag' => [
					'id' => $updated_tag->term_id,
					'name' => $updated_tag->name,
					'slug' => $updated_tag->slug,
					'description' => $updated_tag->description,
					'count' => $updated_tag->count,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Delete tag
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_tag( $request ) {
		try {
			$tag_id = $request->get_param( 'id' );

			$tag = get_term( $tag_id, 'product_tag' );
			if ( is_wp_error( $tag ) || ! $tag ) {
				throw new \Exception( 'Tag not found' );
			}

			$result = wp_delete_term( $tag_id, 'product_tag' );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			if ( ! $result ) {
				throw new \Exception( 'Failed to delete tag' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Tag deleted successfully',
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get all brands
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_brands( $request ) {
		try {
			$brands = get_terms( [
				'taxonomy' => 'product_brand',
				'hide_empty' => false,
				'orderby' => 'name',
				'order' => 'ASC',
			] );

			if ( is_wp_error( $brands ) ) {
				throw new \Exception( $brands->get_error_message() );
			}

			$formatted_brands = [];
			foreach ( $brands as $brand ) {
				$thumbnail_id = get_term_meta( $brand->term_id, 'thumbnail_id', true );
				$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;

				$formatted_brands[] = [
					'id' => $brand->term_id,
					'name' => $brand->name,
					'slug' => $brand->slug,
					'description' => $brand->description,
					'count' => $brand->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'brands' => $formatted_brands,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get single brand
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_brand( $request ) {
		try {
			$brand_id = $request->get_param( 'id' );
			$brand = get_term( $brand_id, 'product_brand' );

			if ( is_wp_error( $brand ) ) {
				throw new \Exception( $brand->get_error_message() );
			}

			if ( ! $brand ) {
				throw new \Exception( 'Brand not found' );
			}

			$thumbnail_id = get_term_meta( $brand->term_id, 'thumbnail_id', true );
			$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;

			return new \WP_REST_Response( [
				'success' => true,
				'brand' => [
					'id' => $brand->term_id,
					'name' => $brand->name,
					'slug' => $brand->slug,
					'description' => $brand->description,
					'count' => $brand->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Create new brand
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_brand( $request ) {
		try {
			$data = $request->get_json_params();

			if ( empty( $data['name'] ) ) {
				throw new \Exception( 'Brand name is required' );
			}

			$args = [
				'description' => $data['description'] ?? '',
			];

			if ( ! empty( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			$result = wp_insert_term( $data['name'], 'product_brand', $args );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$brand_id = $result['term_id'];

			// Save thumbnail if provided
			if ( ! empty( $data['thumbnail_id'] ) ) {
				update_term_meta( $brand_id, 'thumbnail_id', $data['thumbnail_id'] );
			}

			$brand = get_term( $brand_id, 'product_brand' );
			$thumbnail_id = get_term_meta( $brand_id, 'thumbnail_id', true );
			$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Brand created successfully',
				'brand' => [
					'id' => $brand->term_id,
					'name' => $brand->name,
					'slug' => $brand->slug,
					'description' => $brand->description,
					'count' => $brand->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Update brand
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_brand( $request ) {
		try {
			$brand_id = $request->get_param( 'id' );
			$data = $request->get_json_params();

			$brand = get_term( $brand_id, 'product_brand' );
			if ( is_wp_error( $brand ) || ! $brand ) {
				throw new \Exception( 'Brand not found' );
			}

			$args = [];

			if ( isset( $data['name'] ) ) {
				$args['name'] = $data['name'];
			}

			if ( isset( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			if ( isset( $data['description'] ) ) {
				$args['description'] = $data['description'];
			}

			if ( ! empty( $args ) ) {
				$result = wp_update_term( $brand_id, 'product_brand', $args );

				if ( is_wp_error( $result ) ) {
					throw new \Exception( $result->get_error_message() );
				}
			}

			// Update thumbnail if provided
			if ( isset( $data['thumbnail_id'] ) ) {
				if ( $data['thumbnail_id'] ) {
					update_term_meta( $brand_id, 'thumbnail_id', $data['thumbnail_id'] );
				} else {
					delete_term_meta( $brand_id, 'thumbnail_id' );
				}
			}

			$updated_brand = get_term( $brand_id, 'product_brand' );
			$thumbnail_id = get_term_meta( $brand_id, 'thumbnail_id', true );
			$thumbnail_url = $thumbnail_id ? wp_get_attachment_url( $thumbnail_id ) : null;

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Brand updated successfully',
				'brand' => [
					'id' => $updated_brand->term_id,
					'name' => $updated_brand->name,
					'slug' => $updated_brand->slug,
					'description' => $updated_brand->description,
					'count' => $updated_brand->count,
					'thumbnail_id' => $thumbnail_id,
					'thumbnail_url' => $thumbnail_url,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Delete brand
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_brand( $request ) {
		try {
			$brand_id = $request->get_param( 'id' );

			$brand = get_term( $brand_id, 'product_brand' );
			if ( is_wp_error( $brand ) || ! $brand ) {
				throw new \Exception( 'Brand not found' );
			}

			// Delete thumbnail meta
			delete_term_meta( $brand_id, 'thumbnail_id' );

			$result = wp_delete_term( $brand_id, 'product_brand' );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			if ( ! $result ) {
				throw new \Exception( 'Failed to delete brand' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Brand deleted successfully',
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get all attributes
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_attributes( $request ) {
		try {
			$attributes = wc_get_attribute_taxonomies();

			if ( is_wp_error( $attributes ) ) {
				throw new \Exception( $attributes->get_error_message() );
			}

			$formatted_attributes = [];
			foreach ( $attributes as $attribute ) {
				$formatted_attributes[] = [
					'id' => $attribute->attribute_id,
					'name' => $attribute->attribute_label,
					'slug' => $attribute->attribute_name,
					'type' => $attribute->attribute_type,
					'order_by' => $attribute->attribute_orderby,
					'has_archives' => (bool) $attribute->attribute_public,
					'enable_archives' => (bool) $attribute->attribute_public,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'attributes' => $formatted_attributes,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get single attribute
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_attribute( $request ) {
		try {
			$attribute_id = $request->get_param( 'id' );
			$attribute = wc_get_attribute( $attribute_id );

			if ( is_wp_error( $attribute ) ) {
				throw new \Exception( $attribute->get_error_message() );
			}

			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'attribute' => [
					'id' => $attribute->id,
					'name' => $attribute->name,
					'slug' => $attribute->slug,
					'type' => $attribute->type,
					'order_by' => $attribute->order_by,
					'has_archives' => $attribute->has_archives,
					'enable_archives' => $attribute->has_archives,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Create new attribute
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_attribute( $request ) {
		try {
			$data = $request->get_json_params();

			if ( empty( $data['name'] ) ) {
				throw new \Exception( 'Attribute name is required' );
			}

			$args = [
				'name' => $data['name'],
				'slug' => $data['slug'] ?? '',
				'type' => $data['type'] ?? 'select',
				'order_by' => $data['order_by'] ?? 'menu_order',
				'has_archives' => $data['enable_archives'] ?? false,
			];

			$attribute_id = wc_create_attribute( $args );

			if ( is_wp_error( $attribute_id ) ) {
				throw new \Exception( $attribute_id->get_error_message() );
			}

			$attribute = wc_get_attribute( $attribute_id );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Attribute created successfully',
				'attribute' => [
					'id' => $attribute->id,
					'name' => $attribute->name,
					'slug' => $attribute->slug,
					'type' => $attribute->type,
					'order_by' => $attribute->order_by,
					'has_archives' => $attribute->has_archives,
					'enable_archives' => $attribute->has_archives,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Update attribute
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_attribute( $request ) {
		try {
			$attribute_id = $request->get_param( 'id' );
			$data = $request->get_json_params();

			$attribute = wc_get_attribute( $attribute_id );
			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			$args = [
				'name' => $data['name'] ?? $attribute->name,
				'slug' => $data['slug'] ?? $attribute->slug,
				'type' => $data['type'] ?? $attribute->type,
				'order_by' => $data['order_by'] ?? $attribute->order_by,
				'has_archives' => $data['enable_archives'] ?? $attribute->has_archives,
			];

			$result = wc_update_attribute( $attribute_id, $args );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$updated_attribute = wc_get_attribute( $attribute_id );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Attribute updated successfully',
				'attribute' => [
					'id' => $updated_attribute->id,
					'name' => $updated_attribute->name,
					'slug' => $updated_attribute->slug,
					'type' => $updated_attribute->type,
					'order_by' => $updated_attribute->order_by,
					'has_archives' => $updated_attribute->has_archives,
					'enable_archives' => $updated_attribute->has_archives,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Delete attribute
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_attribute( $request ) {
		try {
			$attribute_id = $request->get_param( 'id' );

			$attribute = wc_get_attribute( $attribute_id );
			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			$result = wc_delete_attribute( $attribute_id );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Attribute deleted successfully',
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get attribute terms
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_attribute_terms( $request ) {
		try {
			$attribute_id = $request->get_param( 'attribute_id' );
			$attribute = wc_get_attribute( $attribute_id );

			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			// The slug from wc_get_attribute already has 'pa_' prefix, so use it directly
			$taxonomy = $attribute->slug;
			
			$terms = get_terms( [
				'taxonomy' => $taxonomy,
				'hide_empty' => false,
			] );

			if ( is_wp_error( $terms ) ) {
				throw new \Exception( $terms->get_error_message() );
			}

			$formatted_terms = [];
			foreach ( $terms as $term ) {
				$formatted_terms[] = [
					'id' => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
					'description' => $term->description,
					'count' => $term->count,
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'terms' => $formatted_terms,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Create attribute term
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function create_attribute_term( $request ) {
		try {
			$attribute_id = $request->get_param( 'attribute_id' );
			$data = $request->get_json_params();

			$attribute = wc_get_attribute( $attribute_id );
			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			if ( empty( $data['name'] ) ) {
				throw new \Exception( 'Term name is required' );
			}

			// The slug from wc_get_attribute already has 'pa_' prefix
			$taxonomy = $attribute->slug;

			$args = [
				'description' => $data['description'] ?? '',
			];

			if ( ! empty( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			$result = wp_insert_term( $data['name'], $taxonomy, $args );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			$term = get_term( $result['term_id'], $taxonomy );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Term created successfully',
				'term' => [
					'id' => $term->term_id,
					'name' => $term->name,
					'slug' => $term->slug,
					'description' => $term->description,
					'count' => $term->count,
				],
			], 201 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Update attribute term
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function update_attribute_term( $request ) {
		try {
			$attribute_id = $request->get_param( 'attribute_id' );
			$term_id = $request->get_param( 'term_id' );
			$data = $request->get_json_params();

			$attribute = wc_get_attribute( $attribute_id );
			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			// The slug from wc_get_attribute already has 'pa_' prefix
			$taxonomy = $attribute->slug;
			$term = get_term( $term_id, $taxonomy );

			if ( is_wp_error( $term ) || ! $term ) {
				throw new \Exception( 'Term not found' );
			}

			$args = [];

			if ( isset( $data['name'] ) ) {
				$args['name'] = $data['name'];
			}

			if ( isset( $data['slug'] ) ) {
				$args['slug'] = $data['slug'];
			}

			if ( isset( $data['description'] ) ) {
				$args['description'] = $data['description'];
			}

			if ( ! empty( $args ) ) {
				$result = wp_update_term( $term_id, $taxonomy, $args );

				if ( is_wp_error( $result ) ) {
					throw new \Exception( $result->get_error_message() );
				}
			}

			$updated_term = get_term( $term_id, $taxonomy );

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Term updated successfully',
				'term' => [
					'id' => $updated_term->term_id,
					'name' => $updated_term->name,
					'slug' => $updated_term->slug,
					'description' => $updated_term->description,
					'count' => $updated_term->count,
				],
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Delete attribute term
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function delete_attribute_term( $request ) {
		try {
			$attribute_id = $request->get_param( 'attribute_id' );
			$term_id = $request->get_param( 'term_id' );

			$attribute = wc_get_attribute( $attribute_id );
			if ( ! $attribute ) {
				throw new \Exception( 'Attribute not found' );
			}

			// The slug from wc_get_attribute already has 'pa_' prefix
			$taxonomy = $attribute->slug;
			$term = get_term( $term_id, $taxonomy );

			if ( is_wp_error( $term ) || ! $term ) {
				throw new \Exception( 'Term not found' );
			}

			$result = wp_delete_term( $term_id, $taxonomy );

			if ( is_wp_error( $result ) ) {
				throw new \Exception( $result->get_error_message() );
			}

			if ( ! $result ) {
				throw new \Exception( 'Failed to delete term' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Term deleted successfully',
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get reviews
	 */
	public function get_reviews( $request ) {
		try {
			$status = $request->get_param( 'status' ) ?: 'all';
			
			$args = [
				'post_type' => 'product',
				'status' => $status === 'all' ? 'all' : $status,
			];

			$comments = get_comments( $args );
			$formatted_reviews = [];

			foreach ( $comments as $comment ) {
				$product = wc_get_product( $comment->comment_post_ID );
				
				// Normalize status: '1' = 'approved', '0' = 'hold', 'spam' = 'spam', 'trash' = 'trash'
				$status = $comment->comment_approved;
				if ( $status === '1' ) {
					$status = 'approved';
				} elseif ( $status === '0' ) {
					$status = 'hold';
				}
				
				// Get avatar URL
				// For logged-in users (user_id > 0), get their WordPress avatar
				// For guests, get Gravatar based on email
				$avatar_url = '';
				if ( $comment->user_id > 0 ) {
					// Logged-in user - get WordPress user avatar
					$avatar_url = get_avatar_url( $comment->user_id, [ 'size' => 80 ] );
				} elseif ( ! empty( $comment->comment_author_email ) ) {
					// Guest with email - get Gravatar
					$avatar_url = get_avatar_url( $comment->comment_author_email, [ 'size' => 80 ] );
				}
				
				$formatted_reviews[] = [
					'id' => $comment->comment_ID,
					'product_id' => $comment->comment_post_ID,
					'product_name' => $product ? $product->get_name() : 'Unknown',
					'product_url' => $product ? get_permalink( $product->get_id() ) : '',
					'author_name' => $comment->comment_author,
					'author_email' => $comment->comment_author_email,
					'author_avatar' => $avatar_url,
					'user_id' => (int) $comment->user_id,
					'content' => $comment->comment_content,
					'rating' => (int) get_comment_meta( $comment->comment_ID, 'rating', true ),
					'date' => $comment->comment_date,
					'status' => $status,
					'verified' => (bool) wc_customer_bought_product( $comment->comment_author_email, $comment->user_id, $comment->comment_post_ID ),
				];
			}

			return new \WP_REST_Response( [
				'success' => true,
				'reviews' => $formatted_reviews,
			], 200 );
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
		}
	}

	/**
	 * Get single review
	 */
	public function get_review( $request ) {
		try {
			$review_id = $request->get_param( 'id' );
			$comment = get_comment( $review_id );

			if ( ! $comment ) {
				throw new \Exception( 'Review not found' );
			}

			$product = wc_get_product( $comment->comment_post_ID );

			// Normalize status
			$status = $comment->comment_approved;
			if ( $status === '1' ) {
				$status = 'approved';
			} elseif ( $status === '0' ) {
				$status = 'hold';
			}

			// Get avatar URL
			$avatar_url = '';
			if ( $comment->user_id > 0 ) {
				// Logged-in user - get WordPress user avatar
				$avatar_url = get_avatar_url( $comment->user_id, [ 'size' => 80 ] );
			} elseif ( ! empty( $comment->comment_author_email ) ) {
				// Guest with email - get Gravatar
				$avatar_url = get_avatar_url( $comment->comment_author_email, [ 'size' => 80 ] );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'review' => [
					'id' => $comment->comment_ID,
					'product_id' => $comment->comment_post_ID,
					'product_name' => $product ? $product->get_name() : 'Unknown',
					'author_name' => $comment->comment_author,
					'author_email' => $comment->comment_author_email,
					'author_avatar' => $avatar_url,
					'user_id' => (int) $comment->user_id,
					'content' => $comment->comment_content,
					'rating' => (int) get_comment_meta( $comment->comment_ID, 'rating', true ),
					'date' => $comment->comment_date,
					'status' => $status,
				],
			], 200 );
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
		}
	}

	/**
	 * Update review status
	 */
	public function update_review_status( $request ) {
		try {
			$review_id = $request->get_param( 'id' );
			$data = $request->get_json_params();
			$status = $data['status'];

			$result = wp_set_comment_status( $review_id, $status );

			if ( ! $result ) {
				throw new \Exception( 'Failed to update review status' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Review status updated successfully',
			], 200 );
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
		}
	}

	/**
	 * Delete review
	 */
	public function delete_review( $request ) {
		try {
			$review_id = $request->get_param( 'id' );
			$result = wp_delete_comment( $review_id, true );

			if ( ! $result ) {
				throw new \Exception( 'Failed to delete review' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Review deleted successfully',
			], 200 );
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
		}
	}

	/**
	 * Reply to review
	 */
	public function reply_to_review( $request ) {
		try {
			$review_id = $request->get_param( 'id' );
			$data = $request->get_json_params();
			$parent_comment = get_comment( $review_id );

			if ( ! $parent_comment ) {
				throw new \Exception( 'Review not found' );
			}

			$current_user = wp_get_current_user();
			
			if ( ! $current_user->ID ) {
				throw new \Exception( 'User not authenticated' );
			}

			$reply_data = [
				'comment_post_ID' => $parent_comment->comment_post_ID,
				'comment_content' => $data['reply'],
				'comment_parent' => $review_id,
				'user_id' => $current_user->ID,
				'comment_author' => $current_user->display_name,
				'comment_author_email' => $current_user->user_email,
				'comment_approved' => 1,
				'comment_type' => 'comment',
			];

			$reply_id = wp_insert_comment( $reply_data );

			if ( ! $reply_id ) {
				throw new \Exception( 'Failed to post reply' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Reply posted successfully',
			], 201 );
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
		}
	}

	/**
	 * Get review settings
	 */
	public function get_review_settings( $request ) {
		return new \WP_REST_Response( [
			'success' => true,
			'settings' => [
				'reviews_enabled' => get_option( 'woocommerce_enable_reviews', 'yes' ) === 'yes',
				'show_verified_badge' => get_option( 'woocommerce_review_rating_verification_label', 'yes' ) === 'yes',
				'verified_only' => get_option( 'woocommerce_review_rating_verification_required', 'no' ) === 'yes',
				'enable_star_rating' => get_option( 'woocommerce_enable_review_rating', 'yes' ) === 'yes',
				'star_rating_required' => get_option( 'woocommerce_review_rating_required', 'yes' ) === 'yes',
			],
		], 200 );
	}

	/**
	 * Update review settings
	 */
	public function update_review_settings( $request ) {
		try {
			$data = $request->get_json_params();

			if ( isset( $data['reviews_enabled'] ) ) {
				update_option( 'woocommerce_enable_reviews', $data['reviews_enabled'] ? 'yes' : 'no' );
			}
			if ( isset( $data['show_verified_badge'] ) ) {
				update_option( 'woocommerce_review_rating_verification_label', $data['show_verified_badge'] ? 'yes' : 'no' );
			}
			if ( isset( $data['verified_only'] ) ) {
				update_option( 'woocommerce_review_rating_verification_required', $data['verified_only'] ? 'yes' : 'no' );
			}
			if ( isset( $data['enable_star_rating'] ) ) {
				update_option( 'woocommerce_enable_review_rating', $data['enable_star_rating'] ? 'yes' : 'no' );
			}
			if ( isset( $data['star_rating_required'] ) ) {
				update_option( 'woocommerce_review_rating_required', $data['star_rating_required'] ? 'yes' : 'no' );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'message' => 'Settings updated successfully',
			], 200 );
		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [ 'success' => false, 'message' => $e->getMessage() ], 500 );
		}
	}

	/**
	 * Batch update orders with progress tracking
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function batch_update_orders( $request ) {
		try {
			$data = $request->get_json_params();
			$order_ids = $data['order_ids'] ?? [];
			$update_data = $data['data'] ?? [];
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $order_ids ) || empty( $update_data ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order IDs and update data are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $order_ids ) );
			$batch_order_ids = array_slice( $order_ids, $start_index, $batch_size );

			$updated_count = 0;
			$errors = [];

			foreach ( $batch_order_ids as $order_id ) {
				try {
					$order = wc_get_order( $order_id );
					if ( ! $order ) {
						$errors[] = sprintf( __( 'Order %d not found.', 'shop-explorer' ), $order_id );
						continue;
					}

					// Update order fields
					foreach ( $update_data as $field => $value ) {
						switch ( $field ) {
							case 'status':
								$order->set_status( $value );
								break;
							case 'customer_note':
								$order->set_customer_note( $value );
								break;
							// Add more fields as needed
						}
					}

					$order->save();
					$updated_count++;

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Failed to update order %d: %s', 'shop-explorer' ), $order_id, $e->getMessage() );
				}
			}

			$total_orders = count( $order_ids );
			$processed_orders = $end_index;
			$is_complete = $processed_orders >= $total_orders;
			$progress = $total_orders > 0 ? ( $processed_orders / $total_orders ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'updated_count' => $updated_count,
				'batch_index' => $batch_index,
				'processed_orders' => $processed_orders,
				'total_orders' => $total_orders,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: Updated %d orders. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$updated_count,
					$processed_orders,
					$total_orders,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch update failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch update products with progress tracking
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function batch_update_products( $request ) {
		try {
			$data = $request->get_json_params();
			$product_ids = $data['product_ids'] ?? [];
			$update_data = $data['data'] ?? [];
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $product_ids ) || empty( $update_data ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product IDs and update data are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $product_ids ) );
			$batch_product_ids = array_slice( $product_ids, $start_index, $batch_size );

			$updated_count = 0;
			$errors = [];

			foreach ( $batch_product_ids as $product_id ) {
				try {
					$product = wc_get_product( $product_id );
					if ( ! $product ) {
						$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
						continue;
					}

					// Update product fields
					foreach ( $update_data as $field => $value ) {
						switch ( $field ) {
							case 'name':
								$product->set_name( $value );
								break;
							case 'status':
								$product->set_status( $value );
								break;
							case 'price':
								$product->set_regular_price( $value );
								break;
							case 'sale_price':
								$product->set_sale_price( $value );
								break;
							case 'stock_quantity':
								$product->set_stock_quantity( $value );
								break;
							case 'manage_stock':
								$product->set_manage_stock( $value );
								break;
							// Add more fields as needed
						}
					}

					$product->save();
					$updated_count++;

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Failed to update product %d: %s', 'shop-explorer' ), $product_id, $e->getMessage() );
				}
			}

			$total_products = count( $product_ids );
			$processed_products = $end_index;
			$is_complete = $processed_products >= $total_products;
			$progress = $total_products > 0 ? ( $processed_products / $total_products ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'updated_count' => $updated_count,
				'batch_index' => $batch_index,
				'processed_products' => $processed_products,
				'total_products' => $total_products,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: Updated %d products. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$updated_count,
					$processed_products,
					$total_products,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch update failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch update order status with progress tracking
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function batch_update_order_status( $request ) {
		try {
			$data = $request->get_json_params();
			$order_ids = $data['order_ids'] ?? [];
			$status = $data['status'] ?? '';
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $order_ids ) || empty( $status ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order IDs and status are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $order_ids ) );
			$batch_order_ids = array_slice( $order_ids, $start_index, $batch_size );

			$updated_count = 0;
			$errors = [];

			foreach ( $batch_order_ids as $order_id ) {
				try {
					$order = wc_get_order( $order_id );
					if ( ! $order ) {
						$errors[] = sprintf( __( 'Order %d not found.', 'shop-explorer' ), $order_id );
						continue;
					}

					$order->set_status( $status );
					$order->save();
					$updated_count++;

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Failed to update order %d: %s', 'shop-explorer' ), $order_id, $e->getMessage() );
				}
			}

			$total_orders = count( $order_ids );
			$processed_orders = $end_index;
			$is_complete = $processed_orders >= $total_orders;
			$progress = $total_orders > 0 ? ( $processed_orders / $total_orders ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'updated_count' => $updated_count,
				'batch_index' => $batch_index,
				'processed_orders' => $processed_orders,
				'total_orders' => $total_orders,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: Updated %d orders to %s. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$updated_count,
					$status,
					$processed_orders,
					$total_orders,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch status update failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch update product status with progress tracking
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function batch_update_product_status( $request ) {
		try {
			$data = $request->get_json_params();
			$product_ids = $data['product_ids'] ?? [];
			$status = $data['status'] ?? '';
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $product_ids ) || empty( $status ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product IDs and status are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $product_ids ) );
			$batch_product_ids = array_slice( $product_ids, $start_index, $batch_size );

			$updated_count = 0;
			$errors = [];

			foreach ( $batch_product_ids as $product_id ) {
				try {
					$product = wc_get_product( $product_id );
					if ( ! $product ) {
						$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
						continue;
					}

					$product->set_status( $status );
					$product->save();
					$updated_count++;

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Failed to update product %d: %s', 'shop-explorer' ), $product_id, $e->getMessage() );
				}
			}

			$total_products = count( $product_ids );
			$processed_products = $end_index;
			$is_complete = $processed_products >= $total_products;
			$progress = $total_products > 0 ? ( $processed_products / $total_products ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'updated_count' => $updated_count,
				'batch_index' => $batch_index,
				'processed_products' => $processed_products,
				'total_products' => $total_products,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: Updated %d products to %s. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$updated_count,
					$status,
					$processed_products,
					$total_products,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch status update failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch update product stock with progress tracking
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function batch_update_product_stock( $request ) {
		try {
			$data = $request->get_json_params();
			$stock_updates = $data['stock_updates'] ?? [];
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $stock_updates ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Stock updates are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $stock_updates ) );
			$batch_stock_updates = array_slice( $stock_updates, $start_index, $batch_size );

			$updated_count = 0;
			$errors = [];

			foreach ( $batch_stock_updates as $stock_update ) {
				try {
					$product_id = $stock_update['product_id'] ?? 0;
					$quantity = $stock_update['quantity'] ?? 0;

					$product = wc_get_product( $product_id );
					if ( ! $product ) {
						$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
						continue;
					}

					$product->set_manage_stock( true );
					$product->set_stock_quantity( $quantity );
					$product->save();
					$updated_count++;

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Failed to update stock for product %d: %s', 'shop-explorer' ), $product_id, $e->getMessage() );
				}
			}

			$total_updates = count( $stock_updates );
			$processed_updates = $end_index;
			$is_complete = $processed_updates >= $total_updates;
			$progress = $total_updates > 0 ? ( $processed_updates / $total_updates ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'updated_count' => $updated_count,
				'batch_index' => $batch_index,
				'processed_updates' => $processed_updates,
				'total_updates' => $total_updates,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: Updated stock for %d products. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$updated_count,
					$processed_updates,
					$total_updates,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch stock update failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch get orders for bulk editor loading
	 *
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response
	 */
	public function batch_get_orders( $request ) {
		try {
			$data = $request->get_json_params();
			$order_ids = $data['order_ids'] ?? [];
			$batch_size = $data['batch_size'] ?? 100;

			if ( empty( $order_ids ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order IDs are required.', 'shop-explorer' ),
				], 400 );
			}

			$orders = [];
			$errors = [];
			$processed_count = 0;

			// Process orders in chunks to avoid memory issues
			$chunks = array_chunk( $order_ids, $batch_size );
			
			foreach ( $chunks as $chunk ) {
				foreach ( $chunk as $order_id ) {
					try {
						$order = wc_get_order( $order_id );
						if ( ! $order ) {
							$errors[] = sprintf( __( 'Order %d not found.', 'shop-explorer' ), $order_id );
							continue;
						}

						$orders[] = [
							'id' => $order->get_id(),
							'number' => $order->get_order_number(),
							'status' => $order->get_status(),
							'date_created' => $order->get_date_created() ? $order->get_date_created()->date( 'Y-m-d H:i:s' ) : '',
							'total' => $order->get_total(),
							'currency' => $order->get_currency(),
							'customer_note' => $order->get_customer_note(),
							'payment_method' => $order->get_payment_method(),
							'payment_method_title' => $order->get_payment_method_title(),
							'transaction_id' => $order->get_transaction_id(),
							'billing' => [
								'first_name' => $order->get_billing_first_name(),
								'last_name' => $order->get_billing_last_name(),
								'email' => $order->get_billing_email(),
								'phone' => $order->get_billing_phone(),
								'address_1' => $order->get_billing_address_1(),
								'address_2' => $order->get_billing_address_2(),
								'city' => $order->get_billing_city(),
								'state' => $order->get_billing_state(),
								'postcode' => $order->get_billing_postcode(),
								'country' => $order->get_billing_country(),
							],
							'shipping' => [
								'first_name' => $order->get_shipping_first_name(),
								'last_name' => $order->get_shipping_last_name(),
								'address_1' => $order->get_shipping_address_1(),
								'address_2' => $order->get_shipping_address_2(),
								'city' => $order->get_shipping_city(),
								'state' => $order->get_shipping_state(),
								'postcode' => $order->get_shipping_postcode(),
								'country' => $order->get_shipping_country(),
							],
							'customer' => [
								'name' => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ),
								'email' => $order->get_billing_email(),
							],
							'items_count' => $order->get_item_count(),
						];

						$processed_count++;

					} catch ( \Exception $e ) {
						$errors[] = sprintf( __( 'Error loading order %d: %s', 'shop-explorer' ), $order_id, $e->getMessage() );
					}
				}

				// Add a small delay between chunks to prevent server overload
				if ( count( $chunks ) > 1 ) {
					usleep( 10000 ); // 10ms delay
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'orders' => $orders,
				'processed_count' => $processed_count,
				'total_requested' => count( $order_ids ),
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Loaded %d of %d orders successfully.', 'shop-explorer' ),
					$processed_count,
					count( $order_ids )
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch order loading failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch get products for bulk editor loading
	 *
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response
	 */
	public function batch_get_products( $request ) {
		try {
			$data = $request->get_json_params();
			$product_ids = $data['product_ids'] ?? [];
			$batch_size = $data['batch_size'] ?? 100;

			if ( empty( $product_ids ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product IDs are required.', 'shop-explorer' ),
				], 400 );
			}

			$products = [];
			$errors = [];
			$processed_count = 0;

			// Process products in chunks to avoid memory issues
			$chunks = array_chunk( $product_ids, $batch_size );
			
			foreach ( $chunks as $chunk ) {
				foreach ( $chunk as $product_id ) {
					try {
						$product = wc_get_product( $product_id );
						if ( ! $product ) {
							$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
							continue;
						}

						$images = [];
						$image_ids = $product->get_gallery_image_ids();

						// Add featured image first
						if ( $product->get_image_id() ) {
							$featured_url = wp_get_attachment_url( $product->get_image_id() );
							if ( $featured_url ) {
								$images[] = [
									'id' => $product->get_image_id(),
									'src' => $featured_url,
									'alt' => get_post_meta( $product->get_image_id(), '_wp_attachment_image_alt', true ) ?: '',
									'name' => get_the_title( $product->get_image_id() ) ?: '',
								];
							}
						}

						// Add gallery images
						foreach ( $image_ids as $image_id ) {
							$gallery_url = wp_get_attachment_url( $image_id );
							if ( $gallery_url ) {
								$images[] = [
									'id' => $image_id,
									'src' => $gallery_url,
									'alt' => get_post_meta( $image_id, '_wp_attachment_image_alt', true ) ?: '',
									'name' => get_the_title( $image_id ) ?: '',
								];
							}
						}

						$products[] = [
							'id' => $product->get_id(),
							'name' => $product->get_name(),
							'slug' => $product->get_slug(),
							'status' => $product->get_status(),
							'type' => $product->get_type(),
							'sku' => $product->get_sku(),
							'price' => $product->get_price(),
							'regular_price' => $product->get_regular_price(),
							'sale_price' => $product->get_sale_price(),
							'stock_quantity' => $product->get_stock_quantity(),
							'stock_status' => $product->get_stock_status(),
							'manage_stock' => $product->get_manage_stock(),
							'weight' => $product->get_weight(),
							'dimensions' => [
								'length' => $product->get_length(),
								'width' => $product->get_width(),
								'height' => $product->get_height(),
							],
							'short_description' => $product->get_short_description(),
							'description' => $product->get_description(),
							'categories' => wp_get_post_terms( $product->get_id(), 'product_cat' ),
							'tags' => wp_get_post_terms( $product->get_id(), 'product_tag' ),
							'images' => $images,
							'featured' => $product->get_featured(),
							'virtual' => $product->get_virtual(),
							'downloadable' => $product->get_downloadable(),
							'tax_status' => $product->get_tax_status(),
							'tax_class' => $product->get_tax_class(),
							'shipping_class' => $product->get_shipping_class(),
						];

						$processed_count++;

					} catch ( \Exception $e ) {
						$errors[] = sprintf( __( 'Error loading product %d: %s', 'shop-explorer' ), $product_id, $e->getMessage() );
					}
				}

				// Add a small delay between chunks to prevent server overload
				if ( count( $chunks ) > 1 ) {
					usleep( 10000 ); // 10ms delay
				}
			}

			return new \WP_REST_Response( [
				'success' => true,
				'products' => $products,
				'processed_count' => $processed_count,
				'total_requested' => count( $product_ids ),
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Loaded %d of %d products successfully.', 'shop-explorer' ),
					$processed_count,
					count( $product_ids )
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch product loading failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch delete orders for bulk operations
	 *
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response
	 */
	public function batch_delete_orders( $request ) {
		try {
			$data = $request->get_json_params();
			$order_ids = $data['order_ids'] ?? [];
			$force = $data['force'] ?? false;
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $order_ids ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Order IDs are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $order_ids ) );
			$batch_order_ids = array_slice( $order_ids, $start_index, $batch_size );

			$deleted_count = 0;
			$errors = [];

			foreach ( $batch_order_ids as $order_id ) {
				try {
					$order = wc_get_order( $order_id );
					if ( ! $order ) {
						$errors[] = sprintf( __( 'Order %d not found.', 'shop-explorer' ), $order_id );
						continue;
					}

					if ( $force ) {
						$result = $order->delete( true );
					} else {
						$order->set_status( 'trash' );
						$result = $order->save();
					}

					if ( $result ) {
						$deleted_count++;
					} else {
						$errors[] = sprintf( __( 'Failed to delete order %d.', 'shop-explorer' ), $order_id );
					}

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Error deleting order %d: %s', 'shop-explorer' ), $order_id, $e->getMessage() );
				}
			}

			$total_orders = count( $order_ids );
			$processed_orders = $end_index;
			$is_complete = $processed_orders >= $total_orders;
			$progress = $total_orders > 0 ? ( $processed_orders / $total_orders ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'processed_count' => $deleted_count,
				'batch_index' => $batch_index,
				'processed_orders' => $processed_orders,
				'total_orders' => $total_orders,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: %s %d orders. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$force ? 'Deleted' : 'Moved to trash',
					$deleted_count,
					$processed_orders,
					$total_orders,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch order deletion failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Batch delete products for bulk operations
	 *
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response
	 */
	public function batch_delete_products( $request ) {
		try {
			$data = $request->get_json_params();
			$product_ids = $data['product_ids'] ?? [];
			$force = $data['force'] ?? false;
			$batch_size = $data['batch_size'] ?? 5000;
			$batch_index = $data['batch_index'] ?? 0;

			if ( empty( $product_ids ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'Product IDs are required.', 'shop-explorer' ),
				], 400 );
			}

			// Calculate batch boundaries
			$start_index = $batch_index * $batch_size;
			$end_index = min( $start_index + $batch_size, count( $product_ids ) );
			$batch_product_ids = array_slice( $product_ids, $start_index, $batch_size );

			$deleted_count = 0;
			$errors = [];

			foreach ( $batch_product_ids as $product_id ) {
				try {
					$product = wc_get_product( $product_id );
					if ( ! $product ) {
						$errors[] = sprintf( __( 'Product %d not found.', 'shop-explorer' ), $product_id );
						continue;
					}

					if ( $force ) {
						$result = $product->delete( true );
					} else {
						$product->set_status( 'trash' );
						$result = $product->save();
					}

					if ( $result ) {
						$deleted_count++;
					} else {
						$errors[] = sprintf( __( 'Failed to delete product %d.', 'shop-explorer' ), $product_id );
					}

				} catch ( \Exception $e ) {
					$errors[] = sprintf( __( 'Error deleting product %d: %s', 'shop-explorer' ), $product_id, $e->getMessage() );
				}
			}

			$total_products = count( $product_ids );
			$processed_products = $end_index;
			$is_complete = $processed_products >= $total_products;
			$progress = $total_products > 0 ? ( $processed_products / $total_products ) * 100 : 100;

			return new \WP_REST_Response( [
				'success' => true,
				'processed_count' => $deleted_count,
				'batch_index' => $batch_index,
				'processed_products' => $processed_products,
				'total_products' => $total_products,
				'progress' => round( $progress, 2 ),
				'is_complete' => $is_complete,
				'errors' => $errors,
				'message' => sprintf( 
					__( 'Batch %d: %s %d products. Progress: %d/%d (%.1f%%)', 'shop-explorer' ),
					$batch_index + 1,
					$force ? 'Deleted' : 'Moved to trash',
					$deleted_count,
					$processed_products,
					$total_products,
					$progress
				),
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Batch product deletion failed: ', 'shop-explorer' ) . $e->getMessage(),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce revenue data for analytics
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_revenue_data( $request ) {
		try {
			if ( ! function_exists( 'wc_get_orders' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$from = $request->get_param( 'from' );
			$to = $request->get_param( 'to' );

			// Default to last 30 days if no dates provided
			if ( ! $from && ! $to ) {
				$to = gmdate( 'Y-m-d' );
				$from = gmdate( 'Y-m-d', strtotime( '-30 days' ) );
			} elseif ( ! $from ) {
				$from = gmdate( 'Y-m-d', strtotime( '-30 days', strtotime( $to ) ) );
			} elseif ( ! $to ) {
				$to = gmdate( 'Y-m-d' );
			}

			// Get orders within date range
			$args = [
				'status' => [ 'wc-completed', 'wc-processing' ],
				'date_created' => $from . '...' . $to,
				'limit' => -1,
				'return' => 'objects',
			];

			$orders = wc_get_orders( $args );
			$revenue_data = [];

			// Group orders by date
			$daily_data = [];
			foreach ( $orders as $order ) {
				$date = $order->get_date_created()->date( 'Y-m-d' );
				if ( ! isset( $daily_data[ $date ] ) ) {
					$daily_data[ $date ] = [
						'revenue' => 0,
						'orders' => 0,
					];
				}
				$daily_data[ $date ]['revenue'] += (float) $order->get_total();
				$daily_data[ $date ]['orders']++;
			}

			// Fill in missing dates with zero values
			$current_date = strtotime( $from );
			$end_date = strtotime( $to );

			while ( $current_date <= $end_date ) {
				$date_str = gmdate( 'Y-m-d', $current_date );
				$revenue_data[] = [
					'date' => $date_str,
					'revenue' => isset( $daily_data[ $date_str ] ) ? $daily_data[ $date_str ]['revenue'] : 0,
					'orders' => isset( $daily_data[ $date_str ] ) ? $daily_data[ $date_str ]['orders'] : 0,
				];
				$current_date = strtotime( '+1 day', $current_date );
			}

			return new \WP_REST_Response( [
				'success' => true,
				'data' => $revenue_data,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to get revenue data.', 'shop-explorer' ),
			], 500 );
		}
	}

	/**
	 * Get WooCommerce top products for analytics
	 *
	 * @param \WP_REST_Request $request Request object
	 * @return \WP_REST_Response
	 */
	public function get_woocommerce_top_products( $request ) {
		try {
			if ( ! function_exists( 'wc_get_orders' ) ) {
				return new \WP_REST_Response( [
					'success' => false,
					'message' => __( 'WooCommerce is not available.', 'shop-explorer' ),
				], 500 );
			}

			$from = $request->get_param( 'from' );
			$to = $request->get_param( 'to' );
			$limit = $request->get_param( 'limit' );

			// Default to last 30 days if no dates provided
			if ( ! $from && ! $to ) {
				$to = gmdate( 'Y-m-d' );
				$from = gmdate( 'Y-m-d', strtotime( '-30 days' ) );
			} elseif ( ! $from ) {
				$from = gmdate( 'Y-m-d', strtotime( '-30 days', strtotime( $to ) ) );
			} elseif ( ! $to ) {
				$to = gmdate( 'Y-m-d' );
			}

			// Get orders within date range
			$args = [
				'status' => [ 'wc-completed', 'wc-processing' ],
				'date_created' => $from . '...' . $to,
				'limit' => -1,
				'return' => 'objects',
			];

			$orders = wc_get_orders( $args );
			$product_data = [];

			// Collect product sales data
			foreach ( $orders as $order ) {
				foreach ( $order->get_items() as $item ) {
					$product_id = $item->get_product_id();
					$product = $item->get_product();
					
					if ( ! $product ) {
						continue;
					}

					if ( ! isset( $product_data[ $product_id ] ) ) {
						$product_data[ $product_id ] = [
							'id' => $product_id,
							'name' => $product->get_name(),
							'sales' => 0,
							'revenue' => 0,
							'stock' => $product->get_stock_quantity() ?: 0,
						];
					}

					$quantity = $item->get_quantity();
					$total = $item->get_total();

					$product_data[ $product_id ]['sales'] += $quantity;
					$product_data[ $product_id ]['revenue'] += (float) $total;
				}
			}

			// Sort by revenue and limit results
			uasort( $product_data, function( $a, $b ) {
				return $b['revenue'] <=> $a['revenue'];
			});

			$top_products = array_slice( array_values( $product_data ), 0, $limit );

			return new \WP_REST_Response( [
				'success' => true,
				'data' => $top_products,
			], 200 );

		} catch ( \Exception $e ) {
			return new \WP_REST_Response( [
				'success' => false,
				'message' => __( 'Failed to get top products data.', 'shop-explorer' ),
			], 500 );
		}
	}

}

