<?php
if (!defined('ABSPATH'))
    exit;

class Dori_Chatbot_WooCommerce_Order_Tracker
{
    const ORDER_STATUS_IN_CART = 'in_cart';
    const ORDER_STATUS_PENDING = 'pending';
    const ORDER_STATUS_PROCESSING = 'processing';
    const ORDER_STATUS_COMPLETED = 'completed';
    const ORDER_STATUS_CANCELLED = 'cancelled';
    const ORDER_STATUS_REFUNDED = 'refunded';
    const ORDER_STATUS_FAILED = 'failed';

    public static function init()
    {
        add_action('woocommerce_order_status_pending', array(__CLASS__, 'handle_order_status_change'));
        add_action('woocommerce_order_status_processing', array(__CLASS__, 'handle_order_status_change'));
        add_action('woocommerce_order_status_on-hold', array(__CLASS__, 'handle_order_status_change'));
        add_action('woocommerce_order_status_completed', array(__CLASS__, 'handle_order_status_change'));
        add_action('woocommerce_order_status_cancelled', array(__CLASS__, 'handle_order_status_change'));
        add_action('woocommerce_order_status_refunded', array(__CLASS__, 'handle_order_status_change'));
        add_action('woocommerce_order_status_failed', array(__CLASS__, 'handle_order_status_change'));

        add_action('woocommerce_order_status_pending', array(__CLASS__, 'capture_early_session'));

        // Save session data to order meta at checkout (best time to capture session)
        // Classic checkout hook
        add_action('woocommerce_checkout_update_order_meta', array(__CLASS__, 'save_session_to_order_meta'));

        // Block-based checkout (Store API) hooks - for WooCommerce Blocks
        add_action('woocommerce_store_api_checkout_order_processed', array(__CLASS__, 'save_session_to_order_meta_blocks'));
        add_action('woocommerce_checkout_order_created', array(__CLASS__, 'save_session_to_order_meta_blocks'));

        // Register Action Scheduler hook for async processing
        add_action('dori_chatbot_send_order_data', array(__CLASS__, 'process_order_data_async'), 10, 8);
    }

    public static function handle_order_status_change($order_id)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        $status = $order->get_status();
        self::process_order_correlation($order_id, $status);
    }

    public static function capture_early_session($order_id)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        $session_key = Dori_Chatbot_WooCommerce_Session::get_session_key();

        if ($session_key) {
            // Use WC_Order methods so meta appears in REST API
            $order->update_meta_data('dori_session_key', sanitize_text_field($session_key));
            $order->save();
        }
    }

    /**
     * Save dori session_key to order meta at checkout (classic checkout)
     * This hook fires immediately after order is created during checkout
     *
     * @param int $order_id The order ID
     */
    public static function save_session_to_order_meta($order_id)
    {
        self::do_save_session_to_order($order_id);
    }

    /**
     * Save dori session_key to order meta at checkout (block-based checkout)
     * This hook fires for WooCommerce Blocks / Store API checkout
     *
     * @param \WC_Order $order The order object
     */
    public static function save_session_to_order_meta_blocks($order)
    {
        $order_id = is_object($order) ? $order->get_id() : $order;
        self::do_save_session_to_order($order_id);
    }

    /**
     * Internal method to save session_key to order meta
     *
     * @param int $order_id The order ID
     */
    private static function do_save_session_to_order($order_id)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        $session_key = Dori_Chatbot_WooCommerce_Session::get_session_key();

        if ($session_key) {
            // Check if not already saved (avoid overwriting)
            $existing_session = $order->get_meta('dori_session_key', true);

            if (empty($existing_session)) {
                // Use WC_Order methods so meta appears in REST API
                $order->update_meta_data('dori_session_key', sanitize_text_field($session_key));
                $order->save();
            }
        }
    }

    private static function process_order_correlation($order_id, $status = null)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        $user_id = $order->get_user_id();
        $thread_id = null;

        $thread_id = get_post_meta($order_id, '_dori_thread_id', true);

        if (!$thread_id && $user_id > 0) {
            $thread_id = get_user_meta($user_id, 'dori_current_thread_id', true);
        }

        if (!$thread_id) {
            $thread_id = Dori_Chatbot_WooCommerce_Session::get_thread_from_session();
        }

        if ($thread_id) {
            $products = self::get_order_products($order_id);

            // Try to get session_key from order meta first (most reliable),
            // then fall back to WC session
            $session_key = $order->get_meta('dori_session_key', true);
            if (!$session_key) {
                $session_key = Dori_Chatbot_WooCommerce_Session::get_session_key();
            }

            if (!$status) {
                $status = $order->get_status();
            }

            $customer_email = $order->get_billing_email();
            $customer_id = $order->get_customer_id();
            $total_amount = (float) $order->get_total();

            if (function_exists('as_schedule_single_action')) {
                $action_id = as_schedule_single_action(
                    time(),
                    'dori_chatbot_send_order_data',
                    array($order_id, $status, $products, $session_key, $thread_id, $customer_email, $customer_id, $total_amount),
                    'dori-chatbot'
                );

                if (!$action_id) {
                    try {
                        self::send_thread_order_data(
                            $thread_id,
                            $order_id,
                            $products,
                            $session_key,
                            $status,
                            $customer_email,
                            $customer_id,
                            $total_amount
                        );
                    } catch (Exception $e) {
                    }
                }
            } else {
                try {
                    self::send_thread_order_data(
                        $thread_id,
                        $order_id,
                        $products,
                        $session_key,
                        $status,
                        $customer_email,
                        $customer_id,
                        $total_amount
                    );
                } catch (Exception $e) {
                }
            }
        }
    }

    public static function get_order_products($order_id)
    {
        $order = wc_get_order($order_id);
        $products = array();

        if ($order) {
            foreach ($order->get_items() as $item) {
                $product = $item->get_product();
                if (!$product) {
                    continue;
                }

                $product_data = array(
                    'product_id' => $item->get_product_id(),
                    'variation_id' => $item->get_variation_id(),
                    'name' => $item->get_name(),
                    'product_title' => $item->get_name(),
                    'quantity' => $item->get_quantity(),
                    'price' => (float) $product->get_price(),
                    'subtotal' => (float) $item->get_subtotal(),
                    'total' => (float) $item->get_total(),
                    'sku' => $product->get_sku() ?: '',
                );

                $thumbnail_id = $product->get_image_id();
                if ($thumbnail_id) {
                    $product_data['thumbnail'] = wp_get_attachment_url($thumbnail_id);
                }

                $product_data['url'] = get_permalink($product->get_id());

                $products[] = $product_data;
            }
        }

        return $products;
    }

    public static function send_thread_order_data(
        $thread_id,
        $order_id,
        $items = null,
        $session_key = null,
        $order_status = null,
        $customer_email = null,
        $customer_id = null,
        $total_amount = 0.0
    ) {
        $api_url = Dori_Chatbot_API_Constants::get_server_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_ROI_WEBHOOK;

        $data = array(
            'thread_id' => $thread_id,
            'order_id' => $order_id,
            'customer_email' => $customer_email,
            'customer_id' => $customer_id,
            'items' => $items ?: array(),
            'total_amount' => $total_amount,
            'currency' => "تومان",
            'platform' => "wordpress_woocommerce",
            'order_status' => $order_status,
            'sharing_id' => Dori_Chatbot_Cache_Manager::get_sharing_id()
        );

        if ($session_key) {
            $data['session_key'] = $session_key;
        }

        return Dori_Chatbot_API_Client::call_api($api_url, $data, 10);
    }

    public static function process_order_data_async($order_id, $status, $items_data, $session_key, $thread_id, $customer_email, $customer_id, $total_amount)
    {
        try {
            self::send_thread_order_data(
                $thread_id,
                $order_id,
                $items_data,
                $session_key,
                $status,
                $customer_email,
                $customer_id,
                $total_amount
            );
        } catch (Exception $e) {
        }
    }
}
