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

class Dori_Chatbot_WooCommerce_Cart_Tracker
{
    public static function init()
    {
        add_action('woocommerce_checkout_update_order_review', array(__CLASS__, 'handle_cart_event'), 10, 1);
        add_action('woocommerce_after_add_to_cart_form', array(__CLASS__, 'render_pdp_embedded_widget'), 25);
        add_action('dori_chatbot_send_cart_data', array(__CLASS__, 'process_cart_data_async'), 10, 5);
    }

    public static function handle_cart_event($posted_data = null)
    {
        if (is_admin() && !wp_doing_ajax())
            return;
        if (!is_checkout() || is_order_received_page())
            return;

        $thread_id = Dori_Chatbot_WooCommerce_Session::get_thread_from_session();
        $session_key = Dori_Chatbot_WooCommerce_Session::get_session_key();

        if (!$thread_id || !$session_key || !function_exists('WC') || !WC()->cart) {
            return;
        }

        $cart = WC()->cart;
        $cart_signature = $cart->get_cart_hash();

        if ($cart_signature) {
            $last_signature = WC()->session ? WC()->session->get('dori_last_cart_signature') : null;

            if ($last_signature === $cart_signature) {
                return;
            }

            if (WC()->session) {
                WC()->session->set('dori_last_cart_signature', $cart_signature);
            }
        }

        $products = self::get_cart_products();
        $total_amount = 0;
        foreach ($products as $product) {
            $total_amount += $product['total'];
        }

        if (function_exists('as_schedule_single_action')) {
            as_schedule_single_action(
                time(),
                'dori_chatbot_send_cart_data',
                array($products, $session_key, null, $total_amount, $cart_signature),
                'dori-chatbot'
            );
        } else {
            try {
                Dori_Chatbot_WooCommerce_Order_Tracker::send_thread_order_data(
                    $thread_id,
                    null,
                    $products,
                    $session_key,
                    Dori_Chatbot_WooCommerce_Order_Tracker::ORDER_STATUS_IN_CART,
                    null,
                    null,
                    $total_amount
                );
            } catch (Exception $e) {
            }
        }
    }

    public static function get_cart_products()
    {
        $products = array();

        if (function_exists('WC') && WC()->cart) {
            foreach (WC()->cart->get_cart() as $cart_item) {
                $product = $cart_item['data'];
                if (!$product) {
                    continue;
                }

                $product_data = array(
                    'product_id' => $cart_item['product_id'],
                    'variation_id' => $cart_item['variation_id'],
                    'name' => $product->get_name(),
                    'product_title' => $product->get_name(),
                    'quantity' => $cart_item['quantity'],
                    'price' => (float) $product->get_price(),
                    'subtotal' => (float) $cart_item['line_subtotal'],
                    'total' => (float) $cart_item['line_total'],
                    'sku' => $product->get_sku() ?: '',
                );

                $products[] = $product_data;
            }
        }

        return $products;
    }

    public static function render_pdp_embedded_widget()
    {
        echo '<div id="mori-pdp-embedded-widget-container" style="margin-top: 20px;"></div>';
    }

    public static function process_cart_data_async($cart_items, $session_id, $user_id, $total_amount, $cart_signature)
    {
        try {
            $thread_id = Dori_Chatbot_WooCommerce_Session::get_thread_from_session();

            if (!$thread_id) {
                return;
            }

            Dori_Chatbot_WooCommerce_Order_Tracker::send_thread_order_data(
                $thread_id,
                null,
                $cart_items,
                $session_id,
                Dori_Chatbot_WooCommerce_Order_Tracker::ORDER_STATUS_IN_CART,
                null,
                $user_id,
                $total_amount
            );
        } catch (Exception $e) {
        }
    }
}
