<?php

namespace domain\Document\DeliveryNote;

use domain\Document\Document\DocumentSolver;
use domain\Document\Invoice\Invoice;
use domain\_\SolverInterface;

class DeliveryNoteSolver extends DocumentSolver implements SolverInterface
{
    public function getInvoiceId(DeliveryNote $deliveryNote): ?int
    {
        if($deliveryNote->orders && count($deliveryNote->orders) > 0) {
            foreach($deliveryNote->orders as $order) {
                if($order->id_invoice) {
                    return $order->id_invoice;
                }
            }
        }

        return null;
    }

    public function isInvoiced(DeliveryNote $deliveryNote): bool
    {
        return (bool) $this->getInvoiceId($deliveryNote);
    }

    public function getInvoice(DeliveryNote $deliveryNote): ?Invoice
    {
        $idInvoice = (int) $this->getInvoiceId($deliveryNote);
        return Invoice::searchOne([
            'id' => $idInvoice
        ]);
    }
}