<?php

namespace Opencart\Extension\Alsendo\DTO\Entity;

use Opencart\Extension\Alsendo\DTO\MoneyDTO;
use Opencart\Extension\Alsendo\Providers\PickupLabelProvider;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/MoneyDTO.php');
require_once(DIR_EXTENSION . 'alsendo/src/DTO/Entity/AbstractOrderDetailsPackageEntity.php');
require_once(DIR_EXTENSION . 'alsendo/src/Providers/PickupLabelProvider.php');

abstract class AbstractOrderDetailsPackageDetailsEntity
{
    public int $id;
    public int $orderDetailsId;
    public ?int $templateId;
    public ?string $templateName;
    public ?MoneyDTO $codValue;
    public ?MoneyDTO $declaredValue;
    public ?string $packageContent;
    public ?string $pickupRequest;
    public ?string $pickupRequestDate;
    public ?string $pickupType;
    public ?string $shipViaPickupPoint;
    /** @var AbstractOrderDetailsPackageEntity[] */
    public array $packages = [];

    private PickupLabelProvider $pickupLabelProvider;

    public static function fromArray(array $data, string $currencyCode = 'PLN'): static
    {
        $self = new static();
        $self->id = (int)$data['id'];
        $self->orderDetailsId = (int)$data['order_details_id'];
        $self->templateId = isset($data['template_id']) ? (int)$data['template_id'] : null;
        $self->templateName = $data['template_name'] ?? null;
        $self->packageContent = $data['package_content'] ?? null;
        $self->pickupRequest = $data['pickup_request'] ?? null;
        $self->pickupRequestDate = $data['pickup_request_date'] ?? null;
        $self->pickupType = $data['pickup_type'] ?? null;
        $self->shipViaPickupPoint = $data['ship_via_pickup_point'] ?? null;

        $codMoney = $data['cod_value'] ?? 0;
        $declaredMoney = $data['declared_value'] ?? 0;

        $codFloat = is_numeric($codMoney) ? (float)$codMoney : 0.0;
        $declaredFloat = is_numeric($declaredMoney) ? (float)$declaredMoney : 0.0;

        $self->codValue = MoneyDTO::fromFloat($codFloat, $currencyCode);
        $self->declaredValue = MoneyDTO::fromFloat($declaredFloat, $currencyCode);

        return $self;
    }

    public function getPickupTypeLabel(): string
    {
        if (!isset($this->pickupLabelProvider)) {
            return $this->pickupType ?? '-';
        }

        return $this->pickupLabelProvider->getLabel($this->pickupType) ?? '-';
    }


    public function setPickupLabelProvider(PickupLabelProvider $provider): void
    {
        $this->pickupLabelProvider = $provider;
    }
}
