<?php
namespace Medienreaktor\Products\Service;

/**
 * CartService
 */
class CartService implements \TYPO3\CMS\Core\SingletonInterface {

	public $cart;

	public function __construct() {
		$this->cart = $GLOBALS['TSFE']->fe_user->getKey('ses', 'cart');
	}

	public function save(): void {
		$GLOBALS['TSFE']->fe_user->setKey('ses', 'cart', $this->cart);
	}

	public function getCart() {
		return $this->cart;
	}

	public function addToCart($id, $product): void {
		if ( ! isset($this->cart[$id])) {
			$this->cart[$id]['product'] = $product;
	        $this->cart[$id]['qty'] = 1;
			$this->save();
		}
	}

	public function removeFromCart($id): void {
		unset($this->cart[$id]);
		$this->save();
	}

    public function updateQuantity($id, $qty): void {
		$qty = min(abs((int)$qty), 1000);
        if ($qty == 0) {
            $this->removeFromCart($id);
        } else {
            $this->cart[$id]['qty'] = $qty;
            $this->save();
        }
    }

	public function deleteCart(): void {
		$GLOBALS['TSFE']->fe_user->setKey('ses', 'cart', NULL);
        $this->cart = NULL;
	}
}
