<?php
/**
 * Order Service
 *
 * Handles order lookup and status for customer support.
 *
 * @package BoostBot
 * @since 1.0.0
 */

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

/**
 * Class BoostBot_Order_Service
 *
 * Provides order information for chatbot.
 */
class BoostBot_Order_Service {

    /**
     * Get order status by order ID.
     *
     * @param int         $order_id Order ID.
     * @param string|null $email    Email for verification (optional).
     * @return array|null Order data or null.
     */
    public function get_order_status( int $order_id, ?string $email = null ): ?array {
        if ( ! BoostBot_WooCommerce_Service::is_active() ) {
            return null;
        }

        $order = wc_get_order( $order_id );

        if ( ! $order ) {
            return null;
        }

        // Verify email if provided (security)
        if ( $email && strtolower( $order->get_billing_email() ) !== strtolower( $email ) ) {
            BoostBot_Logger::warning( 'Order email mismatch', array(
                'order_id'    => $order_id,
                'email_given' => $email,
            ) );
            return null;
        }

        return $this->format_order( $order );
    }

    /**
     * Get customer orders by email.
     *
     * @param string $email    Customer email.
     * @param int    $limit    Number of orders.
     * @return array Orders array.
     */
    public function get_customer_orders( string $email, int $limit = 5 ): array {
        if ( ! BoostBot_WooCommerce_Service::is_active() ) {
            return array();
        }

        $orders = wc_get_orders(
            array(
                'billing_email' => $email,
                'limit'         => $limit,
                'orderby'       => 'date',
                'order'         => 'DESC',
            )
        );

        return array_map( array( $this, 'format_order_summary' ), $orders );
    }

    /**
     * Format full order data.
     *
     * @param WC_Order $order Order object.
     * @return array Formatted order.
     */
    private function format_order( $order ): array {
        $items = array();
        
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product();
            $items[] = array(
                'name'     => $item->get_name(),
                'quantity' => $item->get_quantity(),
                'total'    => $order->get_formatted_line_subtotal( $item ),
                'image'    => $product ? wp_get_attachment_image_url( $product->get_image_id(), 'thumbnail' ) : null,
            );
        }

        return array(
            'id'              => $order->get_id(),
            'order_number'    => $order->get_order_number(),
            'status'          => $order->get_status(),
            'status_name'     => wc_get_order_status_name( $order->get_status() ),
            'status_color'    => $this->get_status_color( $order->get_status() ),
            'date'            => $order->get_date_created()->format( 'd/m/Y' ),
            'date_formatted'  => $order->get_date_created()->format( 'd/m/Y H:i' ),
            'total'           => $order->get_formatted_order_total(),
            'payment_method'  => $order->get_payment_method_title(),
            'items'           => $items,
            'items_count'     => $order->get_item_count(),
            'shipping'        => array(
                'method'  => $order->get_shipping_method(),
                'address' => $order->get_formatted_shipping_address(),
            ),
            'billing'         => array(
                'name'    => $order->get_formatted_billing_full_name(),
                'email'   => $order->get_billing_email(),
                'phone'   => $order->get_billing_phone(),
                'address' => $order->get_formatted_billing_address(),
            ),
            'tracking'        => $this->get_tracking_info( $order ),
            'notes'           => $this->get_customer_notes( $order ),
            'can_cancel'      => $this->can_cancel_order( $order ),
            'order_url'       => $order->get_view_order_url(),
        );
    }

    /**
     * Format order summary (for list view).
     *
     * @param WC_Order $order Order object.
     * @return array Summary data.
     */
    private function format_order_summary( $order ): array {
        return array(
            'id'           => $order->get_id(),
            'order_number' => $order->get_order_number(),
            'status'       => $order->get_status(),
            'status_name'  => wc_get_order_status_name( $order->get_status() ),
            'status_color' => $this->get_status_color( $order->get_status() ),
            'date'         => $order->get_date_created()->format( 'd/m/Y' ),
            'total'        => $order->get_formatted_order_total(),
            'items_count'  => $order->get_item_count(),
        );
    }

    /**
     * Get status color for UI.
     *
     * @param string $status Order status.
     * @return string Hex color.
     */
    private function get_status_color( string $status ): string {
        $colors = array(
            'pending'    => '#f59e0b', // Yellow
            'processing' => '#3b82f6', // Blue
            'on-hold'    => '#f97316', // Orange
            'completed'  => '#22c55e', // Green
            'cancelled'  => '#ef4444', // Red
            'refunded'   => '#8b5cf6', // Purple
            'failed'     => '#dc2626', // Dark red
        );

        return $colors[ $status ] ?? '#6b7280'; // Gray default
    }

    /**
     * Get tracking information.
     *
     * @param WC_Order $order Order object.
     * @return array|null Tracking data.
     */
    private function get_tracking_info( $order ): ?array {
        // Check for common tracking plugins
        
        // WooCommerce Shipment Tracking
        $tracking_items = $order->get_meta( '_wc_shipment_tracking_items' );
        
        if ( ! empty( $tracking_items ) && is_array( $tracking_items ) ) {
            $item = reset( $tracking_items );
            return array(
                'provider'        => $item['tracking_provider'] ?? '',
                'tracking_number' => $item['tracking_number'] ?? '',
                'tracking_link'   => $item['tracking_link'] ?? '',
                'date_shipped'    => $item['date_shipped'] ?? '',
            );
        }

        // Custom tracking meta
        $tracking_number = $order->get_meta( '_tracking_number' );
        $tracking_url    = $order->get_meta( '_tracking_url' );
        
        if ( $tracking_number ) {
            return array(
                'provider'        => $order->get_meta( '_tracking_provider' ) ?: __( 'חברת משלוחים', 'boostbot' ),
                'tracking_number' => $tracking_number,
                'tracking_link'   => $tracking_url,
                'date_shipped'    => $order->get_meta( '_date_shipped' ),
            );
        }

        return null;
    }

    /**
     * Get customer-visible notes.
     *
     * @param WC_Order $order Order object.
     * @return array Notes.
     */
    private function get_customer_notes( $order ): array {
        $notes = wc_get_order_notes(
            array(
                'order_id'        => $order->get_id(),
                'type'            => 'customer',
                'order'           => 'DESC',
            )
        );

        return array_map(
            fn( $note ) => array(
                'content' => $note->content,
                'date'    => $note->date_created->format( 'd/m/Y H:i' ),
            ),
            array_slice( $notes, 0, 5 )
        );
    }

    /**
     * Check if order can be cancelled.
     *
     * @param WC_Order $order Order object.
     * @return bool
     */
    private function can_cancel_order( $order ): bool {
        $cancelable_statuses = array( 'pending', 'on-hold' );
        return in_array( $order->get_status(), $cancelable_statuses, true );
    }

    /**
     * Get order status text for AI response.
     *
     * @param int         $order_id Order ID.
     * @param string|null $email    Customer email.
     * @return string Status text.
     */
    public function get_order_status_text( int $order_id, ?string $email = null ): string {
        $order = $this->get_order_status( $order_id, $email );

        if ( ! $order ) {
            return __( 'לא הצלחתי למצוא את ההזמנה. אנא ודא שמספר ההזמנה נכון.', 'boostbot' );
        }

        $text = sprintf(
            /* translators: 1: order number, 2: status name, 3: date */
            __( "הזמנה מספר %1\$s:\n📦 סטטוס: %2\$s\n📅 תאריך: %3\$s\n💰 סכום: %4\$s", 'boostbot' ),
            $order['order_number'],
            $order['status_name'],
            $order['date'],
            $order['total']
        );

        // Add tracking if available
        if ( ! empty( $order['tracking'] ) ) {
            $text .= sprintf(
                "\n\n🚚 פרטי משלוח:\nחברה: %s\nמספר מעקב: %s",
                $order['tracking']['provider'],
                $order['tracking']['tracking_number']
            );

            if ( ! empty( $order['tracking']['tracking_link'] ) ) {
                $text .= sprintf( "\nקישור מעקב: %s", $order['tracking']['tracking_link'] );
            }
        }

        // Add status-specific message
        switch ( $order['status'] ) {
            case 'pending':
                $text .= "\n\n⏳ " . __( 'ההזמנה ממתינה לתשלום.', 'boostbot' );
                break;
            case 'processing':
                $text .= "\n\n⚙️ " . __( 'ההזמנה בטיפול ותישלח בקרוב!', 'boostbot' );
                break;
            case 'completed':
                $text .= "\n\n✅ " . __( 'ההזמנה הושלמה בהצלחה!', 'boostbot' );
                break;
            case 'on-hold':
                $text .= "\n\n⏸️ " . __( 'ההזמנה בהמתנה. ייתכן שנדרש אימות תשלום.', 'boostbot' );
                break;
        }

        return $text;
    }

    /**
     * Detect order intent from message.
     *
     * @param string $message User message.
     * @return array|null Order intent or null.
     */
    public function detect_order_intent( string $message ): ?array {
        $message_lower = mb_strtolower( $message );

        // Order status patterns
        $status_patterns = array(
            'סטטוס הזמנה',
            'איפה ההזמנה',
            'מתי יגיע',
            'מעקב הזמנה',
            'מעקב משלוח',
            'הזמנה שלי',
            'הזמנתי',
        );

        foreach ( $status_patterns as $pattern ) {
            if ( mb_strpos( $message_lower, $pattern ) !== false ) {
                // Try to extract order number
                if ( preg_match( '/(\d{4,})/', $message, $matches ) ) {
                    return array(
                        'type'     => 'order_status',
                        'order_id' => intval( $matches[1] ),
                    );
                }

                return array(
                    'type'          => 'order_status',
                    'order_id'      => null,
                    'needs_details' => true,
                );
            }
        }

        return null;
    }
}








