<?php

use Hilco\Models\Customer;
use Hilco\Models\CustomerSegment;
use Hilco\Models\OPRICL;
use Hilco\Models\Part;
use Hilco\Pricing\PriceHelper;

abstract class CartLine {
    private int $lineId;
    private int $itemId;
    private string $itemNumber;
    private int $webItemId;
    private int $lineQuantity = 0;
    private bool $isContractPriced = false;
    private float $unitPrice = 0.0;
    private float $extendedPrice = 0.0;
    private float $listPrice = 0.0;
    private float $discountedUnitPrice = 0.0;
    private float $discountedExtendedPrice = 0.0;
    /**
     * @var array<CartLineDiscount>
     */
    private array $cartLineDiscounts = [];

    public function __construct (Part $item, int $quantity) {
        $this->itemId = $item->id;
        $this->itemNumber = $item->getPartNo();
        $this->webItemId = isset($item->webPart) ? $item->webPart->id : 0;
        $this->lineQuantity = $quantity;
    }

    public function updatePrices ($priceListConnection, Customer $customer, Part $item, CustomerSegment $customerSegment, array $m3DiscountCodes = []) {
        $opricl = PriceHelper::getPriceRecord($priceListConnection, $customer, $item, $this->lineQuantity, $customerSegment);
        if (isset($opricl)) {
            $this->setPrice($opricl);
            $this->isContractPriced = $opricl->isContractPrice();
            $discountsData = PriceHelper::calculateDiscountDataForItem(
                $priceListConnection,
                $customer,
                $item,
                $this->lineQuantity,
                $this->unitPrice,
                $m3DiscountCodes,
                $customerSegment
            );
            $this->updateDiscounts($discountsData);
        }
    }

    public function setPrice (OPRICL $priceRecord) {
        $this->unitPrice = round($priceRecord->getSalePrice(), 2);
        $this->extendedPrice = $this->unitPrice * $this->lineQuantity;
    }

    public function updateDiscounts (array $discountsData) {
        $cartLineDiscounts = [];
        foreach ($discountsData as $discountType => $discountsDatum) {
            $bucket = $discountsDatum['bucketNo'];
            $cartLineDiscounts[] = new CartLineDiscount(
                $bucket,
                $discountType,
                $discountsDatum["DIA$bucket"],
                $discountsDatum["DIP$bucket"]
            );
        }
        $this->cartLineDiscounts = $cartLineDiscounts;
    }
}