<?php

namespace WeDevs\DokanPro\Modules\Germanized;

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

/**
 * Integrates Dokan's split orders with Germanized's order withdrawal (revocation) form.
 *
 * In a marketplace a single purchase is split into one parent order plus one sub-order per
 * vendor. Germanized's withdrawal form (the "eu-owb" package) is vendor-unaware and lists the
 * parent together with every sub-order, so the customer sees the same purchase several times.
 *
 * This class keeps only the parent order (and standalone single-vendor orders) in the form's
 * order dropdown, so the customer selects their purchase once — matching how Dokan shows the
 * order everywhere else. The per-vendor cascade is handled separately.
 *
 * @since 5.0.12
 */
class Withdrawal {

    /**
     * Constructor.
     *
     * @since 5.0.12
     */
    public function __construct() {
        // Reshape the withdrawal form's order list for logged-in customers and guests.
        // These filters live in the Germanized eu-owb package; the callbacks simply never
        // run when the package is inactive, so registering them here is safe.
        add_filter( 'eu_owb_woocommerce_get_orders_for_user', [ $this, 'filter_parent_orders' ] );
        add_filter( 'eu_owb_woocommerce_get_orders_for_guest', [ $this, 'filter_parent_orders' ] );
    }

    /**
     * Drop Dokan sub-orders from the withdrawal form order list.
     *
     * Keeps parent orders and standalone (single-vendor) orders; removes the per-vendor
     * sub-orders so a split purchase appears only once. Works whether the list holds
     * WC_Order objects or ids, since dokan_is_sub_order() accepts either form.
     *
     * @since 5.0.12
     *
     * @param array $orders Orders as WC_Order objects, or as ids when the caller requested ids.
     *
     * @return array
     */
    public function filter_parent_orders( $orders ) {
        if ( empty( $orders ) || ! is_array( $orders ) ) {
            return $orders;
        }

        // dokan_is_sub_order() accepts an order object or an id and returns true only for
        // per-vendor sub-orders (orders that have a parent).
        $parents_only = array_filter(
            $orders,
            function ( $order ) {
                return ! dokan_is_sub_order( $order );
            }
        );

        return array_values( $parents_only );
    }
}
