<?php

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use WC_Order_Item_Product;
use WC_Product;
use WC_Product_Simple;

class ReturoService
{

    public function __construct()
    {
        add_filter( 'woocommerce_cart_calculate_fees', [$this, 'on_cart_calculate_fees'] );
        add_filter( 'woocommerce_checkout_create_order_line_item', [$this, 'on_checkout_create_order_line_item'], 10, 4 );
    }

    public function on_cart_calculate_fees(): void
    {
        $returo_units = 0;

        foreach ( WC()->cart->get_cart_contents() as $item ) {
            /** @var WC_Product_Simple $product */
            $product = $item['data'];
            $units   = $this->get_collecting_count( $product );
            $returo_units += $units * $item['quantity'];
        }

        if ( $returo_units === 0 ) {
            return;
        }

        foreach ( WC()->cart->get_fees() as $fee ) {
            if ( $fee->id === 'garantie-sgr' ) {
                $fee->amount = 0.5 * $returo_units;

                return;
            }
        }

        WC()->cart->add_fee( 'Garanție SGR', 0.5 * $returo_units );
    }

    public function on_checkout_create_order_line_item( WC_Order_Item_Product $item, $cart_item_key, $values, $order )
    {
        $product = $item->get_product();

        if ( !$product ) {
            return;
        }

        $count = $this->get_collecting_count( $product );

        if ( $count > 0 ) {
            $item->add_meta_data( '_returo_units', $count );
        }
    }

    private function get_collecting_count( WC_Product $product ): int
    {
        $has_returo = $product->get_meta( 'returo_units' );

        if ( !$has_returo ) {
            return 0;
        }

        return intval( $has_returo );
    }
}
