<?php
namespace PrimeLink\Modules\Orders;

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

class OrderImportService {
    /**
     * Find an existing order by a given field (order_id, customer_email, etc.)
     * 
     * @param array $order_data Order data
     * @param string $match_by Match by field
     * @param array $batch_lookups Optional batch lookup results (for optimization)
     * @return int Order ID or 0 if not found
     */
    public static function find_existing_order_id( $order_data, $match_by, $batch_lookups = null ) {
        if ( $match_by === 'order_id' && !empty($order_data['order_id']) ) {
            $order = wc_get_order( absint($order_data['order_id']) );
            return $order ? $order->get_id() : 0;
        }
        if ( $match_by === 'customer_email' && !empty($order_data['customer_email']) ) {
            // Note: WC_Order_Query doesn't support batch queries, but we can optimize with direct SQL if needed
            $query = new \WC_Order_Query([
                'limit' => 1,
                'customer_email' => $order_data['customer_email'],
            ]);
            $orders = $query->get_orders();
            return !empty($orders) ? $orders[0]->get_id() : 0;
        }
        return 0;
    }

    /**
     * Create a new WooCommerce order from mapped data
     */
    public static function create_order( $order_data, $import_id = 0 ) {
        $order = wc_create_order();
        
        // Customer data
        if ( !empty($order_data['customer_id']) ) {
            $order->set_customer_id( absint($order_data['customer_id']) );
        }
        if ( !empty($order_data['customer_email']) ) {
            $order->set_billing_email( sanitize_email($order_data['customer_email']) );
            $order->set_shipping_email( sanitize_email($order_data['customer_email']) );
        }
        if ( !empty($order_data['customer_name']) ) {
            $name_parts = explode( ' ', trim($order_data['customer_name']), 2 );
            $first_name = $name_parts[0] ?? '';
            $last_name = $name_parts[1] ?? '';
            $order->set_billing_first_name( $first_name );
            $order->set_billing_last_name( $last_name );
            $order->set_shipping_first_name( $first_name );
            $order->set_shipping_last_name( $last_name );
        }
        if ( !empty($order_data['customer_phone']) ) {
            $order->set_billing_phone( sanitize_text_field($order_data['customer_phone']) );
        }
        
        // Order status - set before adding items
        $status = !empty($order_data['status']) ? sanitize_text_field($order_data['status']) : 'processing';
        $order->set_status( $status );
        
        // Add line items first (before setting total)
        if ( !empty($order_data['line_items']) && is_array($order_data['line_items']) ) {
            foreach ( $order_data['line_items'] as $item ) {
                $product_id = absint($item['product_id'] ?? 0);
                $quantity = absint($item['quantity'] ?? 1);
                if ( $product_id > 0 && $quantity > 0 ) {
                    $product = wc_get_product( $product_id );
                    if ( $product ) {
                        $order->add_product( $product, $quantity );
                    }
                }
            }
        }
        
        // Set total after items are added
        if ( !empty($order_data['order_total']) ) {
            $order->set_total( floatval($order_data['order_total']) );
        } elseif ( !empty($order_data['total']) ) {
            $order->set_total( floatval($order_data['total']) );
        }
        
        // Currency
        if ( !empty($order_data['currency']) ) {
            $order->set_currency( sanitize_text_field($order_data['currency']) );
        }
        
        // Billing address
        if ( !empty($order_data['billing_first_name']) ) {
            $order->set_billing_first_name( sanitize_text_field($order_data['billing_first_name']) );
        }
        if ( !empty($order_data['billing_last_name']) ) {
            $order->set_billing_last_name( sanitize_text_field($order_data['billing_last_name']) );
        }
        if ( !empty($order_data['billing_company']) ) {
            $order->set_billing_company( sanitize_text_field($order_data['billing_company']) );
        }
        if ( !empty($order_data['billing_address_1']) ) {
            $order->set_billing_address_1( sanitize_text_field($order_data['billing_address_1']) );
        }
        if ( !empty($order_data['billing_address_2']) ) {
            $order->set_billing_address_2( sanitize_text_field($order_data['billing_address_2']) );
        }
        if ( !empty($order_data['billing_city']) ) {
            $order->set_billing_city( sanitize_text_field($order_data['billing_city']) );
        }
        if ( !empty($order_data['billing_state']) ) {
            $order->set_billing_state( sanitize_text_field($order_data['billing_state']) );
        }
        if ( !empty($order_data['billing_postcode']) ) {
            $order->set_billing_postcode( sanitize_text_field($order_data['billing_postcode']) );
        }
        if ( !empty($order_data['billing_country']) ) {
            $order->set_billing_country( sanitize_text_field($order_data['billing_country']) );
        }
        if ( !empty($order_data['billing_email']) ) {
            $order->set_billing_email( sanitize_email($order_data['billing_email']) );
        }
        if ( !empty($order_data['billing_phone']) ) {
            $order->set_billing_phone( sanitize_text_field($order_data['billing_phone']) );
        }
        
        // Shipping address
        if ( !empty($order_data['shipping_first_name']) ) {
            $order->set_shipping_first_name( sanitize_text_field($order_data['shipping_first_name']) );
        }
        if ( !empty($order_data['shipping_last_name']) ) {
            $order->set_shipping_last_name( sanitize_text_field($order_data['shipping_last_name']) );
        }
        if ( !empty($order_data['shipping_company']) ) {
            $order->set_shipping_company( sanitize_text_field($order_data['shipping_company']) );
        }
        if ( !empty($order_data['shipping_address_1']) ) {
            $order->set_shipping_address_1( sanitize_text_field($order_data['shipping_address_1']) );
        }
        if ( !empty($order_data['shipping_address_2']) ) {
            $order->set_shipping_address_2( sanitize_text_field($order_data['shipping_address_2']) );
        }
        if ( !empty($order_data['shipping_city']) ) {
            $order->set_shipping_city( sanitize_text_field($order_data['shipping_city']) );
        }
        if ( !empty($order_data['shipping_state']) ) {
            $order->set_shipping_state( sanitize_text_field($order_data['shipping_state']) );
        }
        if ( !empty($order_data['shipping_postcode']) ) {
            $order->set_shipping_postcode( sanitize_text_field($order_data['shipping_postcode']) );
        }
        if ( !empty($order_data['shipping_country']) ) {
            $order->set_shipping_country( sanitize_text_field($order_data['shipping_country']) );
        }
        
        // Payment method
        if ( !empty($order_data['payment_method']) ) {
            $order->set_payment_method( sanitize_text_field($order_data['payment_method']) );
        }
        if ( !empty($order_data['payment_method_title']) ) {
            $order->set_payment_method_title( sanitize_text_field($order_data['payment_method_title']) );
        }
        if ( !empty($order_data['transaction_id']) ) {
            $order->set_transaction_id( sanitize_text_field($order_data['transaction_id']) );
        }
        
        // Dates - support multiple formats and field names
        $order_date = $order_data['order_date'] ?? $order_data['created_date'] ?? $order_data['creation_date'] ?? $order_data['date_created'] ?? $order_data['created_at'] ?? '';
        if ( !empty($order_date) ) {
            $timestamp = self::parse_date( $order_date );
            if ( $timestamp ) {
                $order->set_date_created( $timestamp );
            }
        }
        
        $paid_date = $order_data['date_paid'] ?? $order_data['paid_date'] ?? $order_data['payment_date'] ?? $order_data['paid_at'] ?? '';
        if ( !empty($paid_date) ) {
            $timestamp = self::parse_date( $paid_date );
            if ( $timestamp ) {
                $order->set_date_paid( $timestamp );
            }
        }
        
        $completed_date = $order_data['date_completed'] ?? $order_data['completion_date'] ?? $order_data['completed_date'] ?? $order_data['completed_at'] ?? '';
        if ( !empty($completed_date) ) {
            $timestamp = self::parse_date( $completed_date );
            if ( $timestamp ) {
                $order->set_date_completed( $timestamp );
            }
        }
        
        // Notes
        if ( !empty($order_data['customer_note']) ) {
            $order->set_customer_note( sanitize_textarea_field($order_data['customer_note']) );
        }
        
        $order->save();
        
        // Add order notes if provided
        if ( !empty($order_data['order_notes']) ) {
            $notes = is_array($order_data['order_notes']) ? $order_data['order_notes'] : array($order_data['order_notes']);
            foreach ( $notes as $note ) {
                $order->add_order_note( sanitize_textarea_field($note) );
            }
        }
        if ( !empty($order_data['admin_note']) ) {
            $order->add_order_note( sanitize_textarea_field($order_data['admin_note']), false, true );
        }
        
        if ( $import_id > 0 ) {
            update_post_meta( $order->get_id(), '_mt_primelink_import_id', absint($import_id) );
        }
        
        return $order->get_id();
    }

    /**
     * Update an existing WooCommerce order
     */
    public static function update_order( $order_id, $order_data, $update_fields = array(), $import_id = 0 ) {
        $order = wc_get_order( $order_id );
        if ( ! $order ) return;
        if ( in_array('customer_email', $update_fields) && !empty($order_data['customer_email']) ) {
            update_post_meta( $order_id, '_customer_email', sanitize_email($order_data['customer_email']) );
        }
        if ( in_array('status', $update_fields) && !empty($order_data['status']) ) {
            $order->set_status( sanitize_text_field($order_data['status']) );
        }
        if ( in_array('total', $update_fields) && !empty($order_data['total']) ) {
            $order->set_total( floatval($order_data['total']) );
        }
        // Update line items if needed
        $order->save();
        if ( $import_id > 0 ) {
            update_post_meta( $order_id, '_mt_primelink_import_id', absint($import_id) );
        }
    }

    /**
     * Add line items to an order (products, quantities, meta)
     */
    public static function add_line_items( $order, $line_items ) {
        if ( ! $order || empty($line_items) || !is_array($line_items) ) return;
        foreach ( $line_items as $item ) {
            $product_id = absint($item['product_id'] ?? 0);
            $quantity = absint($item['quantity'] ?? 1);
            if ( $product_id > 0 && $quantity > 0 ) {
                $product = wc_get_product( $product_id );
                if ( $product ) {
                    $order_item_id = $order->add_product( $product, $quantity );
                    // Optionally set meta for each item
                    if ( !empty($item['meta']) && is_array($item['meta']) ) {
                        foreach ( $item['meta'] as $meta_key => $meta_value ) {
                            wc_add_order_item_meta( $order_item_id, $meta_key, $meta_value );
                        }
                    }
                }
            }
        }
    }

    /**
     * Remove all line items from an order (for update)
     */
    public static function remove_all_line_items( $order ) {
        if ( ! $order ) return;
        foreach ( $order->get_items() as $item_id => $item ) {
            $order->remove_item( $item_id );
        }
        $order->save();
    }

    /**
     * Update line items for an order (replace all)
     */
    public static function update_line_items( $order, $line_items ) {
        self::remove_all_line_items( $order );
        self::add_line_items( $order, $line_items );
        $order->save();
    }

    /**
     * Parse date string to timestamp. Supports multiple formats.
     *
     * @param string $date_string Date string in various formats.
     * @return int|false Timestamp or false on failure.
     */
    private static function parse_date( $date_string ) {
        return \PrimeLink\Helpers\DateHelper::parse_to_timestamp( $date_string );
    }

    /**
     * Validate order data for import (returns error string or empty if valid)
     */
    public static function validate_order_data( $order_data ) {
        $required = array('customer_email', 'status', 'total', 'line_items');
        foreach ($required as $field) {
            if (empty($order_data[$field])) {
                return 'Missing required order field: ' . $field;
            }
        }
        if (!is_array($order_data['line_items']) || count($order_data['line_items']) === 0) {
            return 'Order must have at least one line item.';
        }
        foreach ($order_data['line_items'] as $item) {
            if (empty($item['product_id']) || empty($item['quantity'])) {
                return 'Line item missing product_id or quantity.';
            }
        }
        return '';
    }
}
