<?php

namespace App\Services;

class CartSummary
{
    public array $items = [];
    public float $subtotal = 0;
    public int $pointsRedeemed = 0;
    public float $discountFromPoints = 0;
    public float $shippingCost = 0;
    public float $paymentFee = 0;
    public float $extraCharges = 0;
    public float $total = 0;
    public float $totalProfit = 0;
    public int $pointsEarned = 0;

    public function itemCount(): int
    {
        return count($this->items);
    }

    public function totalQuantity(): int
    {
        $total = 0;
        foreach ($this->items as $item) {
            $total += $item['quantity'];
        }
        return $total;
    }

    public function isEmpty(): bool
    {
        return empty($this->items);
    }

    /**
     * تجميع العناصر حسب المنتج الأب لعرض الشريحة المطبقة.
     */
    public function groupedByProduct(): array
    {
        $groups = [];
        foreach ($this->items as $item) {
            $pid = $item['product_id'];
            if (! isset($groups[$pid])) {
                $groups[$pid] = [
                    'product_id' => $pid,
                    'product_name' => $item['product_name'],
                    'total_qty' => 0,
                    'unit_price' => $item['unit_price'],
                    'tier' => $item['tier'],
                    'items' => [],
                ];
            }
            $groups[$pid]['total_qty'] += $item['quantity'];
            $groups[$pid]['items'][] = $item;
        }
        return array_values($groups);
    }
}
