<?php
namespace App\Core;

class Session {
    public function __construct() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    public function set($key, $value) {
        $_SESSION[$key] = $value;
    }

    public function get($key, $default = null) {
        return isset($_SESSION[$key]) ? $_SESSION[$key] : $default;
    }

    public function remove($key) {
        if (isset($_SESSION[$key])) {
            unset($_SESSION[$key]);
        }
    }

    public function destroy() {
        session_destroy();
    }

    // Cart Helper Methods
    public function getCart() {
        return $this->get('cart', []);
    }

    public function addToCart($productId, $qty = 1) {
        $cart = $this->getCart();
        if (isset($cart[$productId])) {
            $cart[$productId] += $qty;
        } else {
            $cart[$productId] = $qty;
        }
        $this->set('cart', $cart);
    }

    public function updateCart($productId, $qty) {
        $cart = $this->getCart();
        if ($qty <= 0) {
            unset($cart[$productId]);
        } else {
            $cart[$productId] = $qty;
        }
        $this->set('cart', $cart);
    }

    public function clearCart() {
        $this->remove('cart');
    }
}
