<?php

namespace AC_SYNC\Includes\Classes\Order {

    if (!defined('ABSPATH'))
        exit; // Exit if accessed directly

    use AC_SYNC\Includes\Classes\Order\Action_Wear_Order_Repository as Repository;

    /**
     * Main class for ActionWear order management
     */
    class Action_Wear_Order
    {
        /**
         * Check if a WooCommerce order contains ActionWear products
         *
         * @param int $order_id WooCommerce order ID
         * @return bool
         */
        public static function hasActionWearProducts($order_id)
        {
            $order = wc_get_order($order_id);
            if (!$order) {
                return false;
            }

            $items = self::getActionWearItems($order);
            return count($items) > 0;
        }

        /**
         * Check if a product is an ActionWear/CAMAC product
         * Works for both simple products and variations
         *
         * @param \WC_Product $product WooCommerce product object
         * @return bool
         */
        private static function isActionWearProduct($product)
        {
            $product_id = $product->get_id();

            // Check if product itself has the camac meta
            if (get_post_meta($product_id, "camac_cdn_urls", true) !== "") {
                return true;
            }

            // For variations, check the parent product
            if ($product->is_type('variation')) {
                $parent_id = $product->get_parent_id();
                if ($parent_id && get_post_meta($parent_id, "camac_cdn_urls", true) !== "") {
                    return true;
                }
            }

            return false;
        }

        /**
         * Extract only ActionWear products from an order
         *
         * @param \WC_Order $order WooCommerce order object
         * @return array Array of ActionWear items with sku and quantity
         */
        public static function getActionWearItems($order)
        {
            $actionwear_items = [];

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

                // Check if this is an ActionWear product using the camac_cdn_urls meta
                if (self::isActionWearProduct($product)) {
                    $actionwear_items[] = [
                        'sku' => $product->get_sku(),
                        'quantity' => $item->get_quantity(),
                        'product_id' => $product->get_id(),
                        'name' => $product->get_name()
                    ];
                }
            }

            return $actionwear_items;
        }

        /**
         * Get paginated list of ActionWear orders
         *
         * @param int $page Page number
         * @param int $per_page Items per page
         * @param string|null $status_filter Sync status filter
         * @return array
         */
        public static function getOrders($page = 1, $per_page = 20, $status_filter = null)
        {
            $filters = [];
            if ($status_filter && in_array($status_filter, ['pending', 'synced', 'failed'])) {
                $filters['sync_status'] = $status_filter;
            }

            return Repository::paginate($page, $per_page, $filters);
        }

        /**
         * Count total ActionWear orders
         *
         * @param string|null $status_filter Sync status filter
         * @return int
         */
        public static function countOrders($status_filter = null)
        {
            $filters = [];
            if ($status_filter && in_array($status_filter, ['pending', 'synced', 'failed'])) {
                $filters['sync_status'] = $status_filter;
            }

            return Repository::count($filters);
        }

        /**
         * Track a new order in the ActionWear orders table
         *
         * @param int $wc_order_id WooCommerce order ID
         * @return bool
         */
        public static function trackOrder($wc_order_id)
        {
            if (!self::hasActionWearProducts($wc_order_id)) {
                return false;
            }

            return Repository::insert($wc_order_id) !== false;
        }

        /**
         * Update sync status for an order
         *
         * @param int $wc_order_id WooCommerce order ID
         * @param string $status Sync status (pending, synced, failed)
         * @param string|null $response API response
         * @param string|null $error Error message
         * @return bool
         */
        public static function updateSyncStatus($wc_order_id, $status, $response = null, $error = null)
        {
            $data = [
                'sync_status' => $status,
                'last_sync_attempt' => current_time('mysql')
            ];

            if ($response !== null) {
                $data['sync_response'] = is_string($response) ? $response : json_encode($response);
            }

            if ($error !== null) {
                $data['error_message'] = $error;
            } else {
                $data['error_message'] = null;
            }

            return Repository::update($wc_order_id, $data);
        }

        /**
         * Get order sync status
         *
         * @param int $wc_order_id WooCommerce order ID
         * @return object|null
         */
        public static function getOrderStatus($wc_order_id)
        {
            return Repository::findByOrderId($wc_order_id);
        }

        /**
         * Check if order is already tracked
         *
         * @param int $wc_order_id WooCommerce order ID
         * @return bool
         */
        public static function isTracked($wc_order_id)
        {
            return Repository::exists($wc_order_id);
        }

        /**
         * Update destination address for an order
         *
         * @param int $wc_order_id WooCommerce order ID
         * @param int|null $address_id Address ID or null for customer address
         * @return bool
         */
        public static function updateDestination($wc_order_id, $address_id)
        {
            // Ensure order is tracked first
            self::trackOrder($wc_order_id);

            return Repository::update($wc_order_id, [
                'destination_address_id' => $address_id ? intval($address_id) : null
            ]);
        }

        /**
         * Get all WooCommerce orders containing ActionWear products
         * Scans all orders and checks for ActionWear products, then joins with sync status
         *
         * @param int $page Page number
         * @param int $per_page Items per page
         * @param string|null $sync_status_filter Filter by sync status (pending, synced, failed, not_synced)
         * @return array ['orders' => array, 'total' => int]
         */
        public static function getAllActionWearOrders($page = 1, $per_page = 20, $sync_status_filter = null)
        {
            global $wpdb;

            $orders_table = $wpdb->prefix . 'actionwear_orders';
            $wc_orders_table = $wpdb->prefix . 'wc_orders';

            // Detect HPOS: wc_orders table exists and has data
            $hpos_enabled = $wpdb->get_var("SHOW TABLES LIKE '{$wc_orders_table}'") === $wc_orders_table;

            // Find order IDs containing ActionWear products
            // _product_id always points to the parent product (even for variations)
            // camac_cdn_urls is stored on the parent product only
            if ($hpos_enabled) {
                // HPOS: orders in wc_orders table
                $sql = "
                    SELECT DISTINCT oi.order_id
                    FROM {$wpdb->prefix}woocommerce_order_items oi
                    INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim
                        ON oi.order_item_id = oim.order_item_id
                        AND oim.meta_key = '_product_id'
                        AND oim.meta_value > 0
                    INNER JOIN {$wc_orders_table} o
                        ON o.id = oi.order_id
                        AND o.type IN ('shop_order', 'shop_order_placehold')
                        AND o.status IN ('wc-pending','wc-processing','wc-on-hold','wc-completed','wc-cancelled','wc-refunded','wc-failed')
                    INNER JOIN {$wpdb->postmeta} pm
                        ON pm.post_id = oim.meta_value
                        AND pm.meta_key = 'camac_cdn_urls'
                        AND pm.meta_value != ''
                    WHERE oi.order_item_type = 'line_item'
                    ORDER BY oi.order_id DESC
                ";
            } else {
                // Legacy: orders in wp_posts
                $sql = "
                    SELECT DISTINCT oi.order_id
                    FROM {$wpdb->prefix}woocommerce_order_items oi
                    INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim
                        ON oi.order_item_id = oim.order_item_id
                        AND oim.meta_key = '_product_id'
                        AND oim.meta_value > 0
                    INNER JOIN {$wpdb->posts} p
                        ON p.ID = oi.order_id
                        AND p.post_type IN ('shop_order', 'shop_order_placehold')
                        AND p.post_status IN ('wc-pending','wc-processing','wc-on-hold','wc-completed','wc-cancelled','wc-refunded','wc-failed')
                    INNER JOIN {$wpdb->postmeta} pm
                        ON pm.post_id = oim.meta_value
                        AND pm.meta_key = 'camac_cdn_urls'
                        AND pm.meta_value != ''
                    WHERE oi.order_item_type = 'line_item'
                    ORDER BY oi.order_id DESC
                ";
            }

            $all_aw_order_ids = $wpdb->get_col($sql);

            if (empty($all_aw_order_ids)) {
                return [
                    'orders' => [],
                    'total' => 0
                ];
            }

            // Pre-fetch tracking data for all order IDs at once
            $id_placeholders = implode(',', array_fill(0, count($all_aw_order_ids), '%d'));
            $tracking_results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT wc_order_id, sync_status, last_sync_attempt, error_message
                    FROM {$orders_table}
                    WHERE wc_order_id IN ($id_placeholders)",
                    ...$all_aw_order_ids
                )
            );
            $trackingMap = [];
            foreach ($tracking_results as $t) {
                $trackingMap[(int) $t->wc_order_id] = $t;
            }

            // Build filtered list with sync status
            $actionwear_orders = [];
            foreach ($all_aw_order_ids as $order_id) {
                $order_id = (int) $order_id;
                $tracking = $trackingMap[$order_id] ?? null;
                $sync_status = $tracking ? $tracking->sync_status : 'not_synced';
                $last_sync_attempt = $tracking ? $tracking->last_sync_attempt : null;
                $error_message = $tracking ? $tracking->error_message : null;

                // Apply sync status filter
                if ($sync_status_filter) {
                    if ($sync_status_filter === 'not_synced' && $tracking !== null) {
                        continue;
                    }
                    if ($sync_status_filter !== 'not_synced' && $sync_status !== $sync_status_filter) {
                        continue;
                    }
                }

                $actionwear_orders[] = [
                    'wc_order_id' => $order_id,
                    'order_id' => $order_id,
                    'sync_status' => $sync_status,
                    'last_sync_attempt' => $last_sync_attempt,
                    'error_message' => $error_message,
                ];
            }

            $total = count($actionwear_orders);

            // Apply pagination
            $offset = ($page - 1) * $per_page;
            $paginated_orders = array_slice($actionwear_orders, $offset, $per_page);

            // Load full WC order details only for the current page
            foreach ($paginated_orders as &$order_data) {
                $order = wc_get_order($order_data['wc_order_id']);
                if ($order) {
                    $order_data['wc_status'] = $order->get_status();
                    $order_data['order_date'] = $order->get_date_created() ? $order->get_date_created()->format('Y-m-d H:i:s') : null;
                    $order_data['total'] = $order->get_total();
                    $order_data['customer_name'] = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
                    $order_data['items_count'] = count(self::getActionWearItems($order));
                }
            }
            unset($order_data);

            return [
                'orders' => $paginated_orders,
                'total' => $total
            ];
        }
    }
}
