<?php

namespace Opencart\Extension\Alsendo\Providers;

require_once(DIR_EXTENSION . 'alsendo/src/Models/OrderShipment.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/OrderShipmentRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/OrderShipmentPackageRepository.php');
require_once(DIR_EXTENSION . 'alsendo/src/Providers/OrderShipmentPackageProvider.php');

use Opencart\Extension\Alsendo\Models\OrderShipment;
use Opencart\Extension\Alsendo\Repositories\OrderShipmentPackageRepository;
use Opencart\Extension\Alsendo\Repositories\OrderShipmentRepository;

class OrderShipmentProvider
{
    private OrderShipmentRepository $orderShipmentRepository;
    private OrderShipmentPackageProvider $orderShipmentPackageProvider;

    public function __construct(
        OrderShipmentRepository $orderShipmentRepository,
        OrderShipmentPackageRepository $orderShipmentPackageRepository
    ) {
        $this->orderShipmentRepository = $orderShipmentRepository;
        $this->orderShipmentPackageProvider = new OrderShipmentPackageProvider($orderShipmentPackageRepository);
    }

    public function getLatestNotCancelledByOrderId(int $orderId): ?OrderShipment
    {
        $orderShipment = $this->orderShipmentRepository->getLatestNotCancelledByOrderId($orderId);
        $orderShipment?->setPackage($this->orderShipmentPackageProvider->getByOrderShipmentId($orderShipment->getId()));
        $orderShipment?->setPackages($this->orderShipmentPackageProvider->getMultipleByOrderShipmentId($orderShipment->getId()));

        return $orderShipment;
    }

    public function getTotalCount(): int
    {
        return $this->orderShipmentRepository->getTotalCount();
    }

    public function getMultipleShipmentsWithPackages(array $data = []): array
    {
        $shipmentsData = $this->orderShipmentRepository->findMultipleShipmentsByFilters($data);

        foreach ($shipmentsData as &$shipmentData) {
            $shipmentData['package'] = $this->orderShipmentPackageProvider->getByOrderShipmentId($shipmentData['id'])?->toArray();
        }

        return $shipmentsData;
    }

    public function getAllByOrderIdWithPackages(int $orderId): array
    {
        $orderShipments = $this->orderShipmentRepository->getAllByOrderId($orderId);

        foreach ($orderShipments as $orderShipment) {
            $package = $this->orderShipmentPackageProvider->getByOrderShipmentId($orderShipment->getId());
            $packages = $this->orderShipmentPackageProvider->getMultipleByOrderShipmentId($orderShipment->getId());

            $orderShipment->setPackage($package);
            $orderShipment->setPackages($packages);
        }

        return $orderShipments;
    }
}
