<?php

namespace Opencart\Extension\Alsendo\DTO;

use Opencart\Extension\Alsendo\DTO\MoneyDTO;

class OrderShipmentPackageSubmitDTO
{
    public ?int $packageTemplateId;
    public ?string $templateName;
    public float $packageWidth;
    public float $packageLength;
    public float $packageHeight;
    public float $packageWeight;
    public string $packageShipmentPackaging;
    public bool $nonStandard = false;

    public static function fromArray(array $data): OrderShipmentPackageSubmitDTO
    {
        $dto = new self();

        $dto->packageTemplateId = !empty($data['package_template_id']) ? (int)$data['package_template_id'] : null;
        $dto->templateName = $data['template_name'] ?? null;
        $dto->packageWidth = (float)($data['package_width'] ?? 0);
        $dto->packageLength = (float)($data['package_length'] ?? 0);
        $dto->packageHeight = (float)($data['package_height'] ?? 0);
        $dto->packageWeight = (float)($data['package_weight'] ?? 0);
        $dto->packageShipmentPackaging = $data['package_shipment_packaging'] ?? '';
        $dto->nonStandard = !empty($data['non_standard']);
        return $dto;
    }

    public static function multipleFromArray(array $data, array $templateIdToName = []): array
    {
        $packages = [];
        $count = count($data['package_template_id'] ?? []);
        $nonStandardList = $data['package_non_standard'] ?? [];

        for ($i = 0; $i < $count; $i++) {
            $templateId = isset($data['package_template_id'][$i]) ? (int)$data['package_template_id'][$i] : null;
            $templateName = ($templateId !== null && isset($templateIdToName[$templateId])) ? $templateIdToName[$templateId] : '';
            $packages[] = self::fromArray([
                'template_name' => $templateName,
                'package_template_id' => $data['package_template_id'][$i] ?? null,
                'package_width' => $data['package_width'][$i] ?? 0,
                'package_length' => $data['package_length'][$i] ?? 0,
                'package_height' => $data['package_height'][$i] ?? 0,
                'package_weight' => $data['package_weight'][$i] ?? 0,
                'package_shipment_packaging' => $data['package_shipment_packaging'][$i] ?? '',
                'non_standard' => isset($nonStandardList[$i]) && $nonStandardList[$i] === '1',
            ]);
        }

        return $packages;
    }

    public function toArray(): array
    {
        return [
            'package_template_id' => $this->packageTemplateId,
            'template_name' => $this->templateName,
            'package_width' => $this->packageWidth,
            'package_length' => $this->packageLength,
            'package_height' => $this->packageHeight,
            'package_weight' => $this->packageWeight,
            'package_shipment_packaging' => $this->packageShipmentPackaging,
            'non_standard' => $this->nonStandard,
        ];
    }
} 