<?php

declare (strict_types=1);
namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Builder;

use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
use Automattic\WooCommerce\StoreApi\Utilities\CartController;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Violations\Violation;
use DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Ucp\Checkout\Violations\Violations;
/**
 * Applies coupon codes to WooCommerce cart.
 *
 * @phpstan-import-type Discounts from CheckoutSessionBuilder
 */
final class CouponApplier
{
    private CartController $cart_controller;
    public function __construct(CartController $cart_controller)
    {
        $this->cart_controller = $cart_controller;
    }
    /**
     * @param Discounts $discounts Discount data with codes key.
     */
    public function apply(array $discounts): Violations
    {
        $violations = Violations::empty();
        $cart = $this->cart_controller->get_cart_instance();
        $cart->remove_coupons();
        $codes = $discounts['codes'] ?? [];
        foreach ($codes as $code) {
            $code = \wc_clean(\wp_unslash($code));
            if (empty($code)) {
                continue;
            }
            try {
                $this->cart_controller->apply_coupon($code);
            } catch (RouteException $e) {
                $violations = $violations->add(Violation::invalid(\wp_specialchars_decode($e->getMessage(), \ENT_QUOTES), '$.discounts.codes'));
            }
        }
        return $violations;
    }
}
