<?php

require_once __DIR__ . '/OrderProblemInterface.php';

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

    /**
     * @var OrderPayment[]
     */
    protected $payments;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->payments = $order->getOrderPayments();
    }

    public function getErrorMessage(): string
    {
        return 'Le paiement a été dédoublé';
    }

    public function isProblematic(): bool
    {
        $totalPayments = array_reduce($this->payments, function ($somme, OrderPayment $payment) {
            return $somme + $payment->amount;
        }, 0);

        return $totalPayments > $this->order->total_paid_tax_incl;
    }

    public function isRepairable(): bool
    {
        // On ne peut corriger automatique que les doubles paiement identiques
        if (2 != count($this->payments)) {
            return false;
        }

        if ($this->payments[0]->amount !== $this->payments[1]->amount) {
            return false;
        }

        return true;
    }

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

        if (!$this->payments[1]->transaction_id) {
            $this->payments[1]->delete();
        } elseif (!$this->payments[0]->transaction_id) {
            $this->payments[1]->delete();
        } else {
            return false;
        }

        Cache::getInstance()
            ->deleteQuery('SELECT *
			    FROM `' . _DB_PREFIX_ . 'order_payment`
			    WHERE `order_reference` = \'' . pSQL($this->order->reference) . '\''
            );
        $this->payments = $this->order->getOrderPayments();

        return true;
    }
}
