<?php
/**
 * Bubblav REST API Controller
 *
 * Exposes authenticated REST API endpoints for BubblV backend.
 *
 * @package Bubblav_Chat
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Bubblav_REST_API {

	/**
	 * Initialize REST API routes
	 *
	 * @return void
	 */
	public function init() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * Register REST API routes
	 *
	 * @return void
	 */
	public function register_routes() {
		// WordPress content search.
		register_rest_route(
			'bubblav/v1',
			'/search',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'search_content' ),
				'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				'args'                => array(
					'search' => array(
						'required'          => true,
						'validate_callback' => 'sanitize_text_field',
					),
					'type'    => array(
						'required'          => false,
						'default'           => 'any',
						'validate_callback' => 'sanitize_text_field',
					),
					'per_page'    => array(
						'required'          => false,
						'default'           => 10,
						'validate_callback' => 'absint',
					),
				),
			)
		);

		// Get WordPress page/post.
		register_rest_route(
			'bubblav/v1',
			'/page/(?P<id>[a-zA-Z0-9-]+)',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_page' ),
				'permission_callback' => array( $this, 'authenticate_bearer_token' ),
			)
		);

		// WooCommerce products search (only if WooCommerce is active).
		if ( class_exists( 'WooCommerce' ) ) {
			register_rest_route(
				'bubblav/v1',
				'/products',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'search_products' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				)
			);

			register_rest_route(
				'bubblav/v1',
				'/products/(?P<id>\d+)',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_product' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				)
			);

			// Orders list endpoint (for searching by email or customer ID)
			register_rest_route(
				'bubblav/v1',
				'/orders',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'search_orders' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				)
			);

			register_rest_route(
				'bubblav/v1',
				'/orders/(?P<order_id>[a-zA-Z0-9-]+)',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'track_order' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				)
			);

			// Customers endpoint (for looking up customer by email)
			register_rest_route(
				'bubblav/v1',
				'/customers',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'search_customers' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				)
			);

			register_rest_route(
				'bubblav/v1',
				'/customer-orders',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'customer_orders' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
					'args'                => array(
						'email'    => array(
							'required'          => true,
							'validate_callback' => 'sanitize_email',
						),
						'per_page' => array(
							'required'          => false,
							'default'           => 10,
							'validate_callback' => 'absint',
						),
					),
				)
			);

			// Cancel order endpoint
			register_rest_route(
				'bubblav/v1',
				'/orders/(?P<order_id>[a-zA-Z0-9-]+)/cancel',
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'cancel_order' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
					'args'                => array(
						'order_id' => array(
							'required'          => true,
							'validate_callback' => 'sanitize_text_field',
						),
					),
				)
			);

			// Create return endpoint
			register_rest_route(
				'bubblav/v1',
				'/returns',
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'create_return' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
					'args'                => array(
						'order_id' => array(
							'required'          => true,
							'validate_callback' => 'sanitize_text_field',
						),
						'note'     => array(
							'required'          => false,
							'validate_callback' => 'sanitize_textarea_field',
						),
					),
				)
			);

			// Categories endpoint
			register_rest_route(
				'bubblav/v1',
				'/categories',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_categories' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
					'args'                => array(
						'search'   => array(
							'required'          => false,
							'validate_callback' => 'sanitize_text_field',
						),
						'limit'    => array(
							'required'          => false,
							'default'           => 20,
							'validate_callback' => 'absint',
						),
						'parent'   => array(
							'required'          => false,
							'validate_callback' => 'absint',
						),
					),
				)
			);

			// Validate coupon endpoint
			register_rest_route(
				'bubblav/v1',
				'/coupons/(?P<code>[a-zA-Z0-9_-]+)',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'validate_coupon' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
				)
			);

			// Check availability endpoint
			register_rest_route(
				'bubblav/v1',
				'/products/(?P<product_id>\d+)/availability',
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'check_availability' ),
					'permission_callback' => array( $this, 'authenticate_bearer_token' ),
					'args'                => array(
						'product_id' => array(
							'required'          => true,
							'validate_callback' => 'absint',
						),
						'quantity'   => array(
							'required'          => false,
							'default'           => 1,
							'validate_callback' => 'absint',
						),
					),
				)
			);
		}
	}

	/**
	 * Authenticate Bearer token against stored api_token
	 *
	 * @param WP_REST_Request $request The request.
	 * @return true|WP_Error True if authenticated, WP_Error otherwise.
	 */
	public function authenticate_bearer_token( $request ) {
		$token = $this->get_bearer_token( $request );

		if ( ! $token ) {
			return new WP_Error(
				'rest_forbidden',
				'Bearer token is required',
				array( 'status' => 401 )
			);
		}

		// Get the stored API token from WordPress options (not from a separate table).
		$stored_token = get_option( 'bubblav_api_token' );

		if ( empty( $stored_token ) || ! hash_equals( $stored_token, $token ) ) {
			return new WP_Error(
				'rest_forbidden',
				'Invalid bearer token',
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Extract Bearer token from request
	 *
	 * @param WP_REST_Request $request The request.
	 * @return string|false The token or false if not found.
	 */
	private function get_bearer_token( $request ) {
		$header = $request->get_header( 'authorization' );

		if ( ! $header ) {
			return false;
		}

		if ( preg_match( '/Bearer\s+(.*)$/i', $header, $matches ) ) {
			return $matches[1];
		}

		return false;
	}

	/**
	 * Search WordPress content
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response The response.
	 */
	public function search_content( $request ) {
		$search   = $request->get_param( 'search' );
		$type     = $request->get_param( 'type' );
		$per_page = $request->get_param( 'per_page' );

		$args = array(
			's'              => $search,
			'posts_per_page' => $per_page,
			'post_type'      => 'any' === $type ? array( 'post', 'page' ) : $type,
			'post_status'    => 'publish',
		);

		$query = new WP_Query( $args );

		$results = array();
		foreach ( $query->posts as $post ) {
			$results[] = array(
				'id'      => $post->ID,
				'title'   => get_the_title( $post ),
				'url'     => get_permalink( $post ),
				'type'    => $post->post_type,
				'excerpt' => get_the_excerpt( $post ),
			);
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => $results,
				'message' => "Found {$query->post_count} result(s)",
			),
			200
		);
	}

	/**
	 * Get page/post by ID or slug
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function get_page( $request ) {
		$id   = $request->get_param( 'id' );
		$post = get_post( $id );

		if ( ! $post || 'publish' !== $post->post_status ) {
			return new WP_Error(
				'not_found',
				'Page/post not found',
				array( 'status' => 404 )
			);
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => array(
					'id'      => $post->ID,
					'title'   => get_the_title( $post ),
					'content' => wp_strip_all_tags( get_the_content( null, false, $post ) ),
					'url'     => get_permalink( $post ),
					'type'    => $post->post_type,
				),
			),
			200
		);
	}

	/**
	 * Search WooCommerce products
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response The response.
	 */
	public function search_products( $request ) {
		$search   = $request->get_param( 'search' );
		$per_page = $request->get_param( 'per_page', 10 );

		// Try WooCommerce's native product search first (better partial matching)
		$products = $this->search_woocommerce_products( $search, $per_page );

		// If no results, try with singular/plural variations
		if ( empty( $products ) && $search ) {
			$search_variations = $this->get_search_variations( $search );
			foreach ( $search_variations as $variation ) {
				$products = $this->search_woocommerce_products( $variation, $per_page );
				if ( ! empty( $products ) ) {
					break;
				}
			}
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => $products,
				'message' => 'Found ' . count( $products ) . ' product(s)',
			),
			200
		);
	}

	/**
	 * Search WooCommerce products using WP_Query (better search)
	 *
	 * @param string $search Search term.
	 * @param int    $per_page Results per page.
	 * @return array Products array.
	 */
	private function search_woocommerce_products( $search, $per_page = 10 ) {
		// Use WP_Query with 's' parameter for proper search functionality
		// wc_get_products() doesn't support the 'search' parameter
		$args = array(
			's'              => $search,
			'post_type'      => 'product',
			'posts_per_page' => $per_page,
			'post_status'    => 'publish',
		);

		$query = new WP_Query( $args );
		$wc_products = array();

		// Convert WP_Post objects to WC_Product objects
		foreach ( $query->posts as $post ) {
			$product = wc_get_product( $post->ID );
			if ( $product ) {
				$wc_products[] = $product;
			}
		}

		$products = array();
		foreach ( $wc_products as $wc_product ) {
			// Get all product images
			$attachment_ids = $wc_product->get_gallery_image_ids();
			$images = array();

			// Add featured image first
			$featured_image_id = $wc_product->get_image_id();
			if ( $featured_image_id ) {
				$featured_url = wp_get_attachment_url( $featured_image_id );
				if ( $featured_url ) {
					$images[] = array( 'src' => $featured_url );
				}
			}

			// Add gallery images
			foreach ( $attachment_ids as $attachment_id ) {
				$image_url = wp_get_attachment_url( $attachment_id );
				if ( $image_url ) {
					$images[] = array( 'src' => $image_url );
				}
			}

			// Get currency
			$currency = get_woocommerce_currency();

			// Get prices
			$price = $wc_product->get_price();
			$regular_price = $wc_product->get_regular_price();
			$sale_price = $wc_product->get_sale_price();

			// Build price display
			$price_display = '';
			if ( $sale_price && $sale_price < $regular_price ) {
				$price_display = sprintf(
					'%s %s (was %s %s)',
					$currency,
					$sale_price,
					$currency,
					$regular_price
				);
			} elseif ( $price ) {
				$price_display = sprintf( '%s %s', $currency, $price );
			}

			$products[] = array(
				'id'               => $wc_product->get_id(),
				'name'             => $wc_product->get_name(),
				'slug'             => $wc_product->get_slug(),
				'type'             => $wc_product->get_type(),
				'price'            => $price,
				'regular_price'    => $regular_price,
				'sale_price'       => $sale_price ?: null,
				'price_html'       => $price_display,
				'currency'         => $currency,
				'description'      => $wc_product->get_description(),
				'short_description'=> $wc_product->get_short_description(),
				'images'           => $images,
				'permalink'        => $wc_product->get_permalink(),
				'stock_status'     => $wc_product->get_stock_status(),
				'stock_quantity'   => $wc_product->get_stock_quantity(),
				'in_stock'         => $wc_product->is_in_stock(),
			);
		}

		return $products;
	}

	/**
	 * Generate search variations (singular/plural, common forms)
	 *
	 * @param string $search Original search term.
	 * @return array Search variations.
	 */
	private function get_search_variations( $search ) {
		$variations = array();
		$search_lower = strtolower( $search );

		// Common plural/singular suffixes
		if ( substr( $search_lower, -1 ) === 's' ) {
			// Try singular form (jackets -> jacket)
			$variations[] = substr( $search_lower, 0, -1 );
			// Try removing 'es' (boxes -> box)
			if ( substr( $search_lower, -2 ) === 'es' ) {
				$variations[] = substr( $search_lower, 0, -2 );
			}
		} elseif ( substr( $search_lower, -2 ) === 'es' ) {
			// Try without 'es'
			$variations[] = substr( $search_lower, 0, -2 );
		} else {
			// Try adding 's' (jacket -> jackets)
			$variations[] = $search_lower . 's';
			// Try adding 'es' for words ending in s, x, z, ch, sh
			if ( preg_match( '/[sxzchsh]$/', $search_lower ) ) {
				$variations[] = $search_lower . 'es';
			}
		}

		// Also try original with different casing
		$variations[] = ucfirst( $search_lower );

		return array_unique( $variations );
	}

	/**
	 * Get WooCommerce product by ID
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function get_product( $request ) {
		$id      = $request->get_param( 'id' );
		$product = wc_get_product( $id );

		if ( ! $product ) {
			return new WP_Error(
				'not_found',
				'Product not found',
				array( 'status' => 404 )
			);
		}

		// Get all product images
		$attachment_ids = $product->get_gallery_image_ids();
		$images = array();

		// Add featured image first
		$featured_image_id = $product->get_image_id();
		if ( $featured_image_id ) {
			$featured_url = wp_get_attachment_url( $featured_image_id );
			if ( $featured_url ) {
				$images[] = array( 'src' => $featured_url );
			}
		}

		// Add gallery images
		foreach ( $attachment_ids as $attachment_id ) {
			$image_url = wp_get_attachment_url( $attachment_id );
			if ( $image_url ) {
				$images[] = array( 'src' => $image_url );
			}
		}

		// Get currency
		$currency = get_woocommerce_currency();

		// Get prices
		$price = $product->get_price();
		$regular_price = $product->get_regular_price();
		$sale_price = $product->get_sale_price();

		// Build price display
		$price_display = '';
		if ( $sale_price && $sale_price < $regular_price ) {
			$price_display = sprintf(
				'%s %s (was %s %s)',
				$currency,
				$sale_price,
				$currency,
				$regular_price
			);
		} elseif ( $price ) {
			$price_display = sprintf( '%s %s', $currency, $price );
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => array(
					'id'               => $product->get_id(),
					'name'             => $product->get_name(),
					'slug'             => $product->get_slug(),
					'type'             => $product->get_type(),
					'price'            => $price,
					'regular_price'    => $regular_price,
					'sale_price'       => $sale_price ?: null,
					'price_html'       => $price_display,
					'currency'         => $currency,
					'description'      => $product->get_description(),
					'short_description'=> $product->get_short_description(),
					'images'           => $images,
					'permalink'        => $product->get_permalink(),
					'stock_status'     => $product->get_stock_status(),
					'stock_quantity'   => $product->get_stock_quantity(),
					'in_stock'         => $product->is_in_stock(),
				),
			),
			200
		);
	}

	/**
	 * Track WooCommerce order
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function track_order( $request ) {
		$order_id = $request->get_param( 'order_id' );
		$order    = wc_get_order( $order_id );

		if ( ! $order ) {
			return new WP_Error(
				'not_found',
				'Order not found',
				array( 'status' => 404 )
			);
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => $this->format_order_data( $order ),
			),
			200
		);
	}

	/**
	 * Search WooCommerce orders by email, customer ID, or search term
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response The response.
	 */
	public function search_orders( $request ) {
		$email    = $request->get_param( 'email' );
		$customer = $request->get_param( 'customer' );
		$search   = $request->get_param( 'search' );
		$per_page = $request->get_param( 'per_page' ) ?: 50;

		$args = array(
			'limit' => $per_page,
		);

		// Search by billing email
		if ( $email ) {
			$args['billing_email'] = $email;
		}

		// Search by customer ID
		if ( $customer ) {
			$args['customer_id'] = $customer;
		}

		// General search (order number, etc.)
		if ( $search ) {
			$args['s'] = $search;
		}

		$orders = wc_get_orders( $args );
		$data   = array();

		foreach ( $orders as $order ) {
			$data[] = $this->format_order_data( $order );
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => $data,
				'message' => 'Found ' . count( $data ) . ' order(s)',
			),
			200
		);
	}

	/**
	 * Search WooCommerce customers by email
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response The response.
	 */
	public function search_customers( $request ) {
		$email    = $request->get_param( 'email' );
		$per_page = $request->get_param( 'per_page' ) ?: 10;

		$args = array(
			'limit' => $per_page,
		);

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

		$customers = wc_get_customers( $args );
		$data      = array();

		foreach ( $customers as $customer ) {
			$data[] = array(
				'id'            => $customer->get_id(),
				'email'         => $customer->get_email(),
				'first_name'    => $customer->get_first_name(),
				'last_name'     => $customer->get_last_name(),
				'display_name'  => $customer->get_display_name(),
				'date_created'  => $customer->get_date_created() ? $customer->get_date_created()->date( 'Y-m-d H:i:s' ) : null,
			);
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => $data,
				'message' => 'Found ' . count( $data ) . ' customer(s)',
			),
			200
		);
	}

	/**
	 * Format order data for API response
	 *
	 * @param WC_Order $order Order object.
	 * @return array Formatted order data.
	 */
	private function format_order_data( $order ) {
		// Get line items
		$line_items = array();
		foreach ( $order->get_items() as $item ) {
			$line_items[] = array(
				'id'       => $item->get_id(),
				'name'     => $item->get_name(),
				'quantity' => $item->get_quantity(),
				'price'    => $item->get_subtotal() / max( 1, $item->get_quantity() ),
				'total'    => $item->get_total(),
				'sku'      => $item->get_product() ? $item->get_product()->get_sku() : '',
			);
		}

		$formatted = array(
			'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' ) : null,
			'total'          => $order->get_total(),
			'currency'       => $order->get_currency(),
			'payment_method' => $order->get_payment_method(),
			'billing'        => array(
				'email'     => $order->get_billing_email(),
				'first_name'=> $order->get_billing_first_name(),
				'last_name' => $order->get_billing_last_name(),
				'phone'     => $order->get_billing_phone(),
			),
			'line_items'     => $line_items,
			'meta_data'      => $order->get_meta_data(),
		);

		return $formatted;
	}

	/**
	 * Get customer orders by billing email
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function customer_orders( $request ) {
		$email = $request->get_param( 'email' );
		$per_page = $request->get_param( 'per_page' ) ?: 10;

		if ( ! $email ) {
			return new WP_Error(
				'missing_email',
				'Email parameter is required',
				array( 'status' => 400 )
			);
		}

		// Search orders by billing email (not WordPress user)
		$args = array(
			'billing_email' => $email,
			'limit'         => $per_page,
		);

		$orders = wc_get_orders( $args );
		$data   = array();

		foreach ( $orders as $order ) {
			$data[] = $this->format_order_data( $order );
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => $data,
				'message' => 'Found ' . count( $data ) . ' order(s)',
			),
			200
		);
	}

	/**
	 * Get product categories
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response The response.
	 */
	public function get_categories( $request ) {
		$search  = $request->get_param( 'search' );
		$limit   = $request->get_param( 'limit' ) ?: 20;
		$parent  = $request->get_param( 'parent' );

		$args = array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => true,
			'number'     => min( $limit, 100 ),
		);

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

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

		$categories = get_terms( $args );
		$data       = array();

		foreach ( $categories as $cat ) {
			$data[] = array(
				'id'          => (string) $cat->term_id,
				'name'        => $cat->name,
				'slug'        => $cat->slug,
				'description' => $cat->description ?: null,
				'count'       => $cat->count,
				'parent_id'    => $cat->parent ? (string) $cat->parent : null,
				'image'       => null,
			);
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'data'    => array( 'categories' => $data ),
				'message' => $search ? "No categories found matching \"{$search}\"" : 'No categories found',
			),
			200
		);
	}

	/**
	 * Validate discount/coupon code
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function validate_coupon( $request ) {
		$code = $request->get_param( 'code' );

		if ( ! $code ) {
			return new WP_Error(
				'missing_code',
				'Coupon code is required',
				array( 'status' => 400 )
			);
		}

		$coupon = new WC_Coupon( $code );

		if ( ! $coupon || ! $coupon->get_id() ) {
			return new WP_REST_Response(
				array(
						'success' => true,
						'data'    => array( 'valid' => false, 'code' => $code ),
						'message' => "The discount code \"{$code}\" is not valid or has expired.",
				),
				200
			);
		}

		return new WP_REST_Response(
			array(
					'success' => true,
					'data'    => array(
							'valid'          => true,
							'code'           => $coupon->get_code(),
							'amount'         => (float) $coupon->get_amount(),
							'type'           => $coupon->get_discount_type(),
							'description'    => $coupon->get_description() ?: null,
							'minimum_amount' => $coupon->get_minimum_amount() ?: null,
							'maximum_amount' => $coupon->get_maximum_amount() ?: null,
							'free_shipping'  => $coupon->get_free_shipping(),
							'expiry_date'    => $coupon->get_date_expires() ? $coupon->get_date_expires()->date( 'Y-m-d H:i:s' ) : null,
					),
			),
			200
		);
	}

	/**
	 * Check product availability/stock
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function check_availability( $request ) {
		$product_id = $request->get_param( 'product_id' );
		$quantity   = $request->get_param( 'quantity' ) ?: 1;

		if ( ! $product_id ) {
			return new WP_Error(
					'missing_product_id',
					'Product ID is required',
					array( 'status' => 400 )
				);
		}

		$product = wc_get_product( $product_id );

		if ( ! $product ) {
			return new WP_Error(
					'not_found',
					'Product not found',
					array( 'status' => 404 )
				);
		}

		$in_stock     = $product->is_in_stock();
		$stock_status = $product->get_stock_status();
		$stock_qty    = $product->get_stock_quantity();
		$managing_stock = $product->managing_stock();

		$available_quantity = $in_stock ? ( $stock_qty !== null ? $stock_qty : 9999 ) : 0;
		$can_fulfill     = $available_quantity >= $quantity;

		return new WP_REST_Response(
			array(
					'success' => true,
					'data'    => array(
							'product_id'          => (string) $product_id,
							'in_stock'            => $in_stock,
							'stock_status'        => $stock_status,
							'stock_quantity'      => $stock_qty,
							'available_quantity'  => $available_quantity,
							'requested_quantity' => (int) $quantity,
							'can_fulfill'         => $can_fulfill,
							'managing_stock'     => $managing_stock,
							'message'             => $can_fulfill ? 'Product is available' : 'Insufficient stock',
					),
			),
			200
		);
	}

	/**
	 * Cancel order
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function cancel_order( $request ) {
		$order_id = $request->get_param( 'order_id' );

		if ( ! $order_id ) {
			return new WP_Error(
					'missing_order_id',
					'Order ID is required',
					array( 'status' => 400 )
				);
		}

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return new WP_Error(
					'not_found',
					'Order not found',
					array( 'status' => 404 )
				);
		}

		// Check if order can be cancelled
		$current_status = $order->get_status();
		$can_cancel     = in_array( $current_status, array( 'pending', 'on-hold', 'failed' ) );

		if ( ! $can_cancel ) {
			return new WP_Error(
					'cannot_cancel',
					"Order cannot be cancelled. Current status: {$current_status}",
					array( 'status' => 400 )
				);
		}

		// Cancel the order
		$order->update_status( 'cancelled', 'Order cancelled via BubblaV' );
		$order->save();

		// Add order note
		$order->add_order_note( 'Order cancelled via BubblaV integration.' );

		return new WP_REST_Response(
			array(
					'success' => true,
					'data'    => array(
							'order_id'      => (string) $order_id,
							'old_status'    => $current_status,
							'new_status'    => 'cancelled',
							'message'       => 'Order has been cancelled',
					),
			),
			200
		);
	}

	/**
	 * Create return request
	 *
	 * @param WP_REST_Request $request The request.
	 * @return WP_REST_Response|WP_Error The response or error.
	 */
	public function create_return( $request ) {
		$order_id   = $request->get_param( 'order_id' );
		$line_items  = $request->get_json_params();
		$note        = $request->get_param( 'note' );

		if ( ! $order_id ) {
			return new WP_Error(
					'missing_order_id',
					'Order ID is required',
					array( 'status' => 400 )
				);
		}

		if ( empty( $line_items ) ) {
			return new WP_Error(
					'missing_items',
					'Return items are required',
					array( 'status' => 400 )
				);
		}

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return new WP_Error(
					'not_found',
					'Order not found',
					array( 'status' => 404 )
				);
		}

		// Build return details for order note
		$return_details = array();
		foreach ( $line_items as $item ) {
			$item_id = $item['item_id'] ?? 'unknown';
			$qty = $item['quantity'] ?? 1;
			$reason = $item['reason'] ?? 'Not specified';
			$return_details[] = "Item #{$item_id} (Qty: {$qty}) - {$reason}";
		}

		$return_note = "Return Request (via BubblaV Chatbot)\n";
		$return_note .= "Customer Note: " . ( $note ?: 'None' ) . "\n";
		$return_note .= "Items:\n" . implode( "\n", $return_details );

		// Add order note with return request details
		$note_id = $order->add_order_note( $return_note, 1 ); // 1 = customer note (visible to customer)

		// Update order status to indicate return request
		$order->update_status( 'wc-return-requested', 'Return request via BubblaV Chatbot' );

		return new WP_REST_Response(
			array(
					'success' => true,
					'data'    => array(
							'return_id'   => (string) $note_id,
							'order_id'    => (string) $order_id,
							'status'      => 'requested',
							'message'     => 'Return request has been created and added to order notes',
					),
			),
			200
		);
	}
}
