class Cart {
  constructor() {
    this.items = JSON.parse(localStorage.getItem('cartitem')) || [];
  }

  addItem(item) {
    this.items.push(item);
    this.updateStorage();
  }

  removeItem(item) {
    this.items = this.items.filter(e => e.id != item)
    this.updateStorage();
    // const index = this.items.indexOf(item);
    // if (index > -1) {
    //   this.items.splice(index, 1);

    // }
  }


  updateStorage() {
    localStorage.setItem('cartitem', JSON.stringify(this.items));
  }

  getTotal() {
    return this.items.reduce((total, item) => total + item.price, 0);
  }
  totalItems() {
    return this.items.length;
  }

  getItems() {
    return this.items;
  }
  emptyCart() {
    this.items = [];
    localStorage.removeItem('cartitem');
  }
  
  updateTotalQuantity(itemId, quantity) {
    const itemIndex = this.items.findIndex(item => item.id === itemId);
    if (itemIndex > -1) {
      this.items[itemIndex].quantity = quantity; 
      this.updateStorage();
    }
  }

  updateTotalPrice(){
    this.items.forEach(item => {
      item.totalPrice = parseFloat(item.price) * item.quantity;
    });
    this.updateStorage();
  }
  checkItems(id) {
    // Check if an item with the given ID exists in the cart
    return this.items.find(item => item.id === id) || null;
  }
}