<?php

declare(strict_types=1);

require_once __DIR__ . '/OrderProblemInterface.php';

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

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

    /**
     * @var string[];
     */
    protected $errors;

    /**
     * @var bool
     */
    protected $repairable;

    /**
     * @param bool $repairable
     *
     * @return string[]
     */
    protected function computeErrors(&$repairable): array
    {
        $ret = [];
        $repairable = true;

        $totalPayments = array_reduce(
            $this->payments,
            fn ($somme, OrderPayment $payment) => $somme + $payment->amount,
            0
        );

        if ($totalPayments > $this->order->total_paid_tax_incl) {
            $ret[] = 'Paiements : Le paiement a été dédoublé';
        }

        // On ne peut corriger automatique que les doubles paiement identiques
        if (2 != count($this->payments)) {
            $repairable = false;
        }

        if (2 == count($this->payments) && $this->payments[0]->amount !== $this->payments[1]->amount) {
            $repairable = false;
        }

        return $ret;
    }

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

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

    /**
     * @return string[]
     */
    public function getErrors(): array
    {
        return $this->errors;
    }

    public function isProblematic(): bool
    {
        return count($this->errors) > 0;
    }

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

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

        if (!$this->payments[1]->transaction_id) {
            $this->payments[1]->delete();
        } elseif (!$this->payments[0]->transaction_id) {
            $this->payments[0]->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;
    }
}
