<?php


namespace App\Services;

use Gloudemans\Shoppingcart\Facades\Cart;

trait InteractWithCart{

    public function items($cart = null){
        $cart = (blank($cart)) ? Cart::content() : $cart;
        $items = [];
        if ($cart) {
            foreach ($cart as $rowId => $item) {
                $item = (array) $item;
                $items[$item['rowId'] ?? $rowId] = [
                    'product_id' => $item['id'],
                    'quantity' => $item['qty'],
                    'price' => $item['price'],
//                    'amount' => $item['amount'] ?? $item['price'] * $item['qty'],
                ];
            }
        }
        return $items;
    }

    public function total($order = []){

        if (blank($order)){
            return [
                "customer_id" => auth()->id(),
                'user_address_id' => session("saved_user_address_id"),
                'shipping_company_id' =>  session("saved_shipping_company_id"),
                'payment_method_id' => session("saved_payment_method_id"),
                'subtotal' => getNumbersOfCart()->get('subtotal'),
                'discount_code' => session()->has('coupon') ? session()->get('coupon')['code'] : null,
                'discount' => getNumbersOfCart()->get('discount'),
                'shipping' => getNumbersOfCart()->get('shipping'),
                'tax' => getNumbersOfCart()->get('productTaxes'),
                'total' => getNumbersOfCart()->get('total'),
                'currency' => getSettingsOf("currency"),
                'order_status' => 0,
            ];
        }

        return [
            "customer_id" => $order['customer']['id'],
            'user_address_id' => $order['customer']['address'] ?? null,
            'shipping_company_id' =>  $order['config']['shipping_company_id'] ?? null,
            'payment_method_id' => $order['config']['payment_method_id'] ?? null,
            'subtotal' => $order['allTotal']['sub_total']['value'] ?? 0,
            'discount_code' => $order['allTotal']['discount']["code"] ?? 0,
            'discount' => $order['allTotal']['discount']['value'] ?? 0,
            'shipping' => $order['config']['shipping'] ?? 0,
            'tax' => $order['allTotal']['tax']['value'] ?? 0,
            'total' => $order['allTotal']['total']['value'] ?? 0,
            'currency' => getSettingsOf("currency"),
            'order_status' => 0,
        ];
    }
}
