<?php

namespace App\Repositories\Core\User;

use Cart;

class ShopCart
{
    public static function add($item, $update = false)
    {
        if (self::has($item['id'])) {
            if ($update) {
                self::remove($item['id']);
                self::get()->add($item);
            } else {
                self::get()->update($item['id'], ['quantity' => $item['quantity']]);
            }
        } else {
            self::get()->add($item);
        }

        return [
            'count' => self::count(),
            'quantity' => self::getTotalQuantity(),
            'total' => self::getTotal(),
            'added' => $item,
        ];
    }

    public static function getSummary()
    {
        return [
            'count' => self::count(),
            'quantity' => self::getTotalQuantity(),
            'total' => self::getTotal(),
        ];
    }

    public static function remove($id)
    {
        return self::get()->remove($id);
    }

    public static function clear()
    {
        Cart::clear();

        return self::get()->clear();
    }

    public static function has($id)
    {
        return array_key_exists($id, self::getContent()->toArray());
    }

    public static function keys()
    {
        return array_keys(self::getContent()->toArray());
    }

    public static function count()
    {
        return self::getContent()->count();
    }

    public static function getTotalQuantity()
    {
        return self::get()->getTotalQuantity();
    }

    public static function getTotal()
    {
        return self::fixDecimal(self::get()->getTotal());
    }

    public static function fixDecimal($number)
    {
        return number_format(round($number, 2), 2);
    }

    public static function getItemQuantity($id)
    {
        return self::getItem($id) ? (int) self::getItem($id)->quantity : 0;
    }

    public static function getItem($id)
    {
        return Cart::get($id);
    }

    public static function getContent()
    {
        return self::get()->getContent();
    }

    public static function get()
    {
        return Cart::session('_token');
    }
}
