<?php
namespace Modules\Project\Services\Order\Transport;

use Modules\Project\Entities\Transport;
use Modules\Project\Services\TransportService;
use SMG\Address\AddressModel;

class TransportCollection
{
    private $collection = [];

    private $address_id;

    public function pushTransport(TransportRow $transport)
    {
        if (isset($this->collection[$transport->transport_id])) {
            $this->collection[$transport->transport_id]->merge($transport);
        } else {
            if ($transport->transport_id) {
                $this->collection[$transport->transport_id] = $transport;
            }
        }
    }

    public function setAddress($address_id)
    {
        $this->address_id = $address_id;
    }

    public function freight()
    {
        $total = 0;

        $transport_service = new TransportService(new Transport());

        foreach ($this->collection as $v) {
            try {
                $amount = $transport_service->prepay($v->weight, $v->transport_id, $this->province_id());
            } catch (\Exception $e) {
                $amount = 0;
            }

            $total = bcadd($total, $amount, 2);
        }

        return $total;
    }

    private function province_id()
    {
        $address = (new AddressModel())->find($this->address_id);

        return $address->area->getAreaIds();
    }
}
