<?php

namespace Opencart\Extension\Alsendo\Services;

require_once(DIR_EXTENSION . 'alsendo/src/Repositories/OrderShipmentPackageRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Models/OrderShipmentPackage.php');
require_once(DIR_EXTENSION . 'alsendo/src/DTO/FullOrderDTO.php');

use Opencart\Extension\Alsendo\DTO\FullOrderDTO;
use Opencart\Extension\Alsendo\Repositories\OrderShipmentPackageRepository;
use Opencart\Extension\Alsendo\Models\OrderShipmentPackage;

class OrderShipmentPackageService
{
    private OrderShipmentPackageRepository $orderShipmentPackageRepository;

    public function __construct(OrderShipmentPackageRepository $orderShipmentPackageRepository)
    {
        $this->orderShipmentPackageRepository = $orderShipmentPackageRepository;
    }

    public function createFromOrderShipmentSubmit(FullOrderDTO $dto, int $orderShipmentId): void
    {
        if (!$dto->orderDetails || !$dto->orderDetails->packageDetails) {
            return;
        }

        $packageDetails = $dto->orderDetails->packageDetails;
        $packages = $packageDetails->packages;

        foreach ($packages as $pkg) {
            $orderShipmentPackage = new OrderShipmentPackage(
                null,
                $orderShipmentId,
                $pkg->templateId,
                $pkg->templateName ?? $dto->getAttribute('template_name', 'package'),
                $pkg->packageShipmentPackaging ?? 'standard',
                $dto->getAttribute('pickup_type', 'package'),
                (int)($pkg->packageLength ?? 0),
                (int)($pkg->packageWidth ?? 0),
                (int)($pkg->packageHeight ?? 0),
                (int)($pkg->packageWeight ?? 0),
                $dto->getCodValueOrNull(),
                $dto->getDeclaredValueOrNull(),
                $dto->getAttribute('package_content', 'package'),
            );

            $id = $this->orderShipmentPackageRepository->upsert($orderShipmentPackage);
            $orderShipmentPackage->setId($id);
        }
    }
}
