<?php
/**
 * Translates WooCommerce order lines into the plain arrays Core understands.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wc;

use SkyServers\Retragere\Wp\Repository;
use SkyServers\Retragere\Wp\Settings;
use WC_Order;

/**
 * The only place that knows what a WC_Order_Item_Product is. EligibilityRules
 * receives arrays and stays free of WooCommerce.
 */
final class OrderItems
{
    /**
     * @param WC_Order $order
     *
     * @return array<int,array<string,mixed>>
     */
    public static function forOrder($order): array
    {
        $requested = Repository::requestedQuantities((int) $order->get_id());
        $excludes  = (bool) Settings::get('exclude_digital');
        $lines     = [];

        foreach ($order->get_items() as $itemId => $item) {
            $product = method_exists($item, 'get_product') ? $item->get_product() : null;

            // The article 16 carve-out for digital content is conditional, and
            // a virtual product in WooCommerce is often a service rather than
            // digital content. The shop decides whether it applies.
            $isDigital = false;
            if ($excludes && $product) {
                $isDigital = $product->is_virtual() || $product->is_downloadable();
            }

            $lines[] = [
                'item_id'           => (int) $itemId,
                'product_id'        => method_exists($item, 'get_product_id') ? (int) $item->get_product_id() : 0,
                'variation_id'      => method_exists($item, 'get_variation_id') ? (int) $item->get_variation_id() : 0,
                'name'              => (string) $item->get_name(),
                'sku'               => $product ? (string) $product->get_sku() : '',
                'qty'               => method_exists($item, 'get_quantity') ? (int) $item->get_quantity() : 0,
                'is_digital'        => $isDigital,
                'is_non_returnable' => false,
                'requested_qty'     => (int) ($requested[(int) $itemId] ?? 0),
            ];
        }

        return $lines;
    }

    /**
     * @param WC_Order $order
     */
    public static function totalQty($order): int
    {
        $total = 0;

        foreach ($order->get_items() as $item) {
            $total += method_exists($item, 'get_quantity') ? (int) $item->get_quantity() : 0;
        }

        return $total;
    }
}
