<?php

require_once __DIR__ . '/OrderProblemInterface.php';

class OrderProblemInvoice implements OrderProblemInterface
{
    /**
     * @var Order
     */
    protected $order;

    /**
     * @var OrderInvoice[]
     */
    protected $orderInvoices = [];

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->orderInvoices = $order->getInvoicesCollection();
    }

    public function getErrorMessage(): string
    {
        return "La facture n'est pas en accord avec la commande";
    }

    public function isProblematic(): bool
    {
        if (count($this->orderInvoices) > 1) {
            return false;
        }
        $invoice = $this->orderInvoices[0];

        if (
            $invoice->total_products != $this->order->total_products
            || $invoice->total_products_wt != $this->order->total_products_wt
            || $invoice->total_shipping_tax_excl != $this->order->total_shipping_tax_excl
            || $invoice->total_shipping_tax_incl != $this->order->total_shipping_tax_incl
            || $invoice->total_paid_tax_excl != $this->order->total_paid_tax_excl
            || $invoice->total_paid_tax_incl != $this->order->total_paid_tax_incl
        ) {
            return true;
        }

        return false;
    }

    public function isRepairable(): bool
    {
        return $this->isProblematic();
    }

    public function repair(): bool
    {
        if (!$this->isRepairable()) {
            return false;
        }

        $invoice = $this->orderInvoices[0];

        $invoice->total_products = $this->order->total_products;
        $invoice->total_products_wt = $this->order->total_products_wt;
        $invoice->total_shipping_tax_excl = $this->order->total_shipping_tax_excl;
        $invoice->total_shipping_tax_incl = $this->order->total_shipping_tax_incl;
        $invoice->total_paid_tax_excl = $this->order->total_paid_tax_excl;
        $invoice->total_paid_tax_incl = $this->order->total_paid_tax_incl;

        $invoice->save();

        return true;
    }
}
