<?php

namespace Devurai\AcceptbluePaymentPro\Traits;

trait WoocommerceFunctions
{
    protected function get_shop_country_code()
    {
        if ( function_exists( 'wc_get_base_location' ) ) {
            $base_location = wc_get_base_location();
            return $base_location['country'] ?? '';
        }else{
            return '';
        }
    }

    protected function get_site_address(): string
    {
        $site_url = get_site_url();
        return preg_replace('#^https?://#', '', $site_url);
    }

    /**
     * Calculates the total tax amount for the current cart or a given order.
     *
     * @param \WC_Order $order The order object to retrieve tax details from if the cart is not available.
     * @return float The total tax amount for the cart or order. Returns 0 in case of an exception or error.
     */
    protected function get_total_tax(\WC_Order $order): float
    {
        $total_tax = 0;
        if(WC()->cart !== null) {
            foreach ( WC()->cart->get_tax_totals() as $code => $tax ) :
                $total_tax += $tax->amount;
            endforeach;

            return $total_tax;
        }else{
            try {
                $taxes = $order->get_items( 'tax' );
                foreach ( $taxes as $tax ) {
                    if($tax instanceof  \WC_Order_Item_Tax) {
                        $total_tax += $tax->get_tax_total();
                    }
                }

                return $total_tax;
            }catch (\Exception $e){
                return 0;
            }
        }
    }
}