<?php
/**
 * WooCommerce Handler class for order tracking and product queries
 *
 * This class handles WooCommerce integration including:
 * - Order status tracking
 * - Order lookup by email, order ID, or transaction ID
 * - Order information formatting
 *
 * @package Askany
 * @since 1.0.0
 */

namespace Askany;

/**
 * WooCommerce Handler class
 *
 * @package Askany
 * @since 1.0.0
 */
class WooCommerceHandler {
	
	/**
	 * Database instance
	 *
	 * @var Database
	 */
	private $database;
	
	/**
	 * Constructor
	 *
	 * @param Database $database Database instance
	 */
	public function __construct( $database ) {
		$this->database = $database;
	}
	
	/**
	 * Check if WooCommerce is active
	 *
	 * @return bool
	 */
	public function is_woocommerce_active() {
		return class_exists( 'WooCommerce' );
	}

	/**
	 * Check if order tracking is enabled
	 *
	 * @return bool
	 */
	public function is_order_tracking_enabled() {
		$woocommerce_enabled = get_option( 'askany_woocommerce_enabled', true );
		$order_tracking_enabled = get_option( 'askany_woocommerce_order_tracking', false );
		
		return $woocommerce_enabled && $order_tracking_enabled && $this->is_woocommerce_active();
	}

	/**
	 * Detect if the query is asking about order status
	 *
	 * @param string $query The user query
	 * @return bool
	 */
	public function is_order_query( $query ) {
		$query_lower = strtolower( $query );
		
		$order_keywords = array(
			'order status',
			'track order',
			'track my order',
			'where is my order',
			'order tracking',
			'check order',
			'my order',
			'order number',
			'order id',
			'transaction id',
			'order details',
			'order information',
			'delivery status',
			'shipping status',
			'when will my order arrive',
			'has my order shipped',
			'order refund',
			'refund status',
		);

		foreach ( $order_keywords as $keyword ) {
			if ( strpos( $query_lower, $keyword ) !== false ) {
				return true;
			}
		}

		return false;
	}
	
	/**
	 * Check if we're in an order tracking context based on conversation history
	 *
	 * @param string $session_id The session ID
	 * @return bool
	 */
	private function is_in_order_tracking_context( $session_id ) {
		if ( empty( $session_id ) || ! $this->database ) {
			return false;
		}
		
		// Get last 2 messages from the session
		global $wpdb;
		$table_name = $wpdb->prefix . 'askany_chat_messages';
		
		$messages = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT message, sender_type FROM {$table_name} 
				WHERE session_id = %s 
				ORDER BY created_at DESC 
				LIMIT 2",
				$session_id
			)
		);
		
		if ( empty( $messages ) ) {
			return false;
		}
		
		// Check if the last AI message was asking for order information
		foreach ( $messages as $msg ) {
			if ( in_array( $msg->sender_type, array( 'ai', 'assistant' ), true ) ) {
				$message_lower = strtolower( $msg->message );
				
				// Check if AI was asking for order tracking information
				$order_request_indicators = array(
					'track your order',
					'order number',
					'email address',
					'transaction id',
					'provide one of the following',
					'order details',
					'find your order',
				);
				
				foreach ( $order_request_indicators as $indicator ) {
					if ( strpos( $message_lower, $indicator ) !== false ) {
						return true;
					}
				}
			}
		}
		
		return false;
	}

	/**
	 * Extract order identifier from query (email, order ID, or transaction ID)
	 *
	 * @param string $query The user query
	 * @return array Array with 'type' and 'value' keys
	 */
	public function extract_order_identifier( $query ) {
		// Check for email
		if ( preg_match( '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/', $query, $matches ) ) {
			return array(
				'type' => 'email',
				'value' => $matches[0],
			);
		}

		// Check for order ID (format: #12345 or 12345)
		if ( preg_match( '/#?(\d{4,6})\b/', $query, $matches ) ) {
			return array(
				'type' => 'order_id',
				'value' => $matches[1],
			);
		}

		// Check for transaction ID (alphanumeric, typically longer)
		if ( preg_match( '/\b([A-Z0-9]{10,})\b/i', $query, $matches ) ) {
			return array(
				'type' => 'transaction_id',
				'value' => $matches[1],
			);
		}

		return array(
			'type' => null,
			'value' => null,
		);
	}

	/**
	 * Find orders by identifier
	 *
	 * @param string $type Identifier type (email, order_id, transaction_id)
	 * @param string $value Identifier value
	 * @return array Array of WC_Order objects
	 */
	public function find_orders( $type, $value ) {
		if ( ! $this->is_woocommerce_active() ) {
			return array();
		}

		$orders = array();

		switch ( $type ) {
			case 'email':
				$orders = wc_get_orders( array(
					'billing_email' => $value,
					'limit' => 5,
					'orderby' => 'date',
					'order' => 'DESC',
				) );
				break;

			case 'order_id':
				$order = wc_get_order( $value );
				if ( $order ) {
					$orders = array( $order );
				}
				break;

			case 'transaction_id':
				$orders = wc_get_orders( array(
					'transaction_id' => $value,
					'limit' => 1,
				) );
				break;
		}

		return $orders;
	}

	/**
	 * Format order information for AI response
	 *
	 * @param WC_Order $order The WooCommerce order object
	 * @return string Formatted order information
	 */
	public function format_order_info( $order ) {
		if ( ! $order ) {
			return '';
		}

		$order_id = $order->get_id();
		$order_number = $order->get_order_number();
		$status = $order->get_status();
		$status_name = wc_get_order_status_name( $status );
		$date_created = $order->get_date_created()->date_i18n( get_option( 'date_format' ) );
		$total = $order->get_formatted_order_total();
		
		// Build response
		$response = "📦 **Order #{$order_number}**\n\n";
		$response .= "**Status:** {$status_name}\n";
		$response .= "**Order Date:** {$date_created}\n";

		// Add status-specific information
		switch ( $status ) {
			case 'pending':
				$response .= "⏳ Your order is pending payment. Please complete the payment to process your order.\n\n";
				break;

			case 'processing':
				$response .= "⚙️ Your order is being processed. We'll notify you once it's ready for shipment.\n\n";
				break;

			case 'on-hold':
				$response .= "⏸️ Your order is on hold. Please contact us for more information.\n\n";
				break;

			case 'completed':
				$response .= "✅ Your order has been completed and delivered!\n\n";
				break;

			case 'cancelled':
				$response .= "❌ This order has been cancelled.\n\n";
				break;

			case 'refunded':
				$response .= "💰 This order has been refunded.\n";
				$refunds = $order->get_refunds();
				if ( ! empty( $refunds ) ) {
					$response .= "**Refund Details:**\n";
					foreach ( $refunds as $refund ) {
						$refund_amount = $refund->get_formatted_refund_amount();
						$refund_date = $refund->get_date_created()->date_i18n( get_option( 'date_format' ) );
						$response .= "- {$refund_amount} on {$refund_date}\n";
					}
				}
				$response .= "\n";
				break;

			case 'failed':
				$response .= "⚠️ Payment for this order failed. Please try again or contact us for assistance.\n\n";
				break;
		}

		// Add shipping information if available
		if ( $order->has_shipping_address() ) {
			$shipping_method = $order->get_shipping_method();
			if ( $shipping_method ) {
				$response .= "**Shipping Method:** {$shipping_method}\n";
			}

			// Add tracking information if available
			$tracking_number = $order->get_meta( '_tracking_number' );
			if ( $tracking_number ) {
				$response .= "**Tracking Number:** {$tracking_number}\n";
			}
			$response .= "\n";
		}

		// Add order items
		$items = $order->get_items();
		if ( ! empty( $items ) ) {
			$response .= "**Order Items:**\n";
			foreach ( $items as $item ) {
				$product_name = $item->get_name();
				$quantity = $item->get_quantity();
				$response .= "- {$product_name} × {$quantity}\n";
			}
			$response .= "\n";
		}

		// Add payment method
		$payment_method_title = $order->get_payment_method_title();
		if ( $payment_method_title ) {
			$response .= "**Payment Method:** {$payment_method_title}\n";
		}

		// Add transaction ID if available
		$transaction_id = $order->get_transaction_id();
		if ( $transaction_id ) {
			$response .= "**Transaction ID:** {$transaction_id}\n";
		}

		return $response;
	}

	/**
	 * Handle order tracking query
	 *
	 * @param string $query The user query
	 * @return array|false Response data or false if not an order query
	 */
	public function handle_order_query( $query, $session_id = '' ) {
		// Check if order tracking is enabled
		if ( ! $this->is_order_tracking_enabled() ) {
			return false;
		}

		// Check if this is an order query OR if we have an identifier (email/order ID) in the message
		$identifier = $this->extract_order_identifier( $query );
		$has_identifier = ! empty( $identifier['type'] ) && ! empty( $identifier['value'] );
		
		// If we have an identifier, check conversation history to see if we're in an order tracking context
		$is_order_context = false;
		if ( $has_identifier && ! empty( $session_id ) ) {
			$is_order_context = $this->is_in_order_tracking_context( $session_id );
		}
		
		// Only proceed if this is explicitly an order query OR we have an identifier in an order tracking context
		if ( ! $this->is_order_query( $query ) && ! $is_order_context ) {
			return false;
		}

		// If no identifier found, ask for it
		if ( empty( $identifier['type'] ) || empty( $identifier['value'] ) ) {
			return array(
				'message' => "I'd be happy to help you track your order! 📦\n\n" .
							"Please provide one of the following:\n" .
							"- Your email address\n" .
							"- Your order number (e.g., #12345)\n" .
							"- Your transaction ID\n\n" .
							"This will help me find your order details quickly.",
				'is_order_request' => true,
			);
		}

		// Identifier found - look up orders immediately
		$orders = $this->find_orders( $identifier['type'], $identifier['value'] );

		// No orders found
		if ( empty( $orders ) ) {
			$identifier_label = $identifier['type'] === 'email' ? 'email address' : 
								( $identifier['type'] === 'order_id' ? 'order number' : 'transaction ID' );
			
			return array(
				'message' => "I've checked our system but couldn't find any orders associated with the {$identifier_label}: **{$identifier['value']}**\n\n" .
							"This could mean:\n" .
							"- The email address might be slightly different\n" .
							"- The order number might be incorrect\n" .
							"- The order might be very recent and not yet in our system\n\n" .
							"Could you please:\n" .
							"- Double-check the email address you used when placing the order\n" .
							"- Or provide your order number (you can find it in your order confirmation email)\n" .
							"- Or share your transaction ID\n\n" .
							"I'm here to help you track down your order! 😊",
				'is_order_request' => true,
			);
		}

		// Format response
		if ( count( $orders ) === 1 ) {
			// Single order found
			$message = "Great! I found your order. Here are the details:\n\n";
			$message .= $this->format_order_info( $orders[0] );
			$message .= "\nIs there anything else I can help you with regarding this order?";
		} else {
			// Multiple orders found
			$message = "I found **" . count( $orders ) . "** orders for {$identifier['value']}:\n\n";
			
			foreach ( $orders as $index => $order ) {
				$order_number = $order->get_order_number();
				$status = wc_get_order_status_name( $order->get_status() );
				$date = $order->get_date_created()->date_i18n( get_option( 'date_format' ) );
				$total = $order->get_formatted_order_total();
				
				$message .= "**" . ( $index + 1 ) . ". Order #{$order_number}**\n";
				$message .= "Status: {$status} | Date: {$date} | Total: {$total}\n\n";
			}
			
			$message .= "Please provide the specific order number you'd like to know more about.";
		}

		return array(
			'message' => $message,
			'is_order_request' => true,
		);
	}
}
