<?php
namespace App\Entity;
use App\Repository\CartItemRepository;
use Doctrine\ORM\Mapping as ORM;
use DateTimeImmutable;
#[ORM\Entity(repositoryClass: CartItemRepository::class)]
#[ORM\Table(name: '`cart_item`')]
class CartItem
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(targetEntity: Cart::class, inversedBy: 'items')]
#[ORM\JoinColumn(nullable: false)]
private ?Cart $cart = null;
#[ORM\ManyToOne(targetEntity: Product::class)]
#[ORM\JoinColumn(nullable: false)]
private ?Product $product = null;
#[ORM\Column]
private ?int $quantity = null;
#[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
private ?string $unitPrice = null;
#[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
private ?string $totalPrice = null;
#[ORM\Column(nullable: true)]
private ?DateTimeImmutable $addedAt = null;
public function __construct()
{
$this->addedAt = new DateTimeImmutable();
}
public function getId(): ?int
{
return $this->id;
}
public function getCart(): ?Cart
{
return $this->cart;
}
public function setCart(?Cart $cart): self
{
$this->cart = $cart;
return $this;
}
public function getProduct(): ?Product
{
return $this->product;
}
public function setProduct(?Product $product): self
{
$this->product = $product;
if ($product) {
$this->unitPrice = $product->getPrice();
$this->updateTotalPrice();
}
return $this;
}
public function getQuantity(): ?int
{
return $this->quantity;
}
public function setQuantity(int $quantity): self
{
$this->quantity = max(1, $quantity);
$this->updateTotalPrice();
return $this;
}
public function getUnitPrice(): ?string
{
return $this->unitPrice;
}
public function setUnitPrice(string $unitPrice): self
{
$this->unitPrice = $unitPrice;
$this->updateTotalPrice();
return $this;
}
public function getTotalPrice(): ?string
{
return $this->totalPrice;
}
public function setTotalPrice(string $totalPrice): self
{
$this->totalPrice = $totalPrice;
return $this;
}
public function getAddedAt(): ?DateTimeImmutable
{
return $this->addedAt;
}
public function setAddedAt(DateTimeImmutable $addedAt): self
{
$this->addedAt = $addedAt;
return $this;
}
private function updateTotalPrice(): void
{
if ($this->unitPrice && $this->quantity) {
$this->totalPrice = number_format($this->unitPrice * $this->quantity, 2, '.', '');
}
}
public function incrementQuantity(int $amount = 1): self
{
$this->quantity += $amount;
$this->updateTotalPrice();
return $this;
}
public function decrementQuantity(int $amount = 1): self
{
$this->quantity = max(1, $this->quantity - $amount);
$this->updateTotalPrice();
return $this;
}
}