<?php

/**
 * Created by PhpStorm.
 * User: jderosa
 * Date: 28/02/20
 * Time: 13.04
 */

namespace FiloBlu\Rma\Block\Order;

use Exception;
use FiloBlu\Rma\Helper\ChangeSizeQuote;
use FiloBlu\Rma\Model\OrderLocator;
use FiloBlu\Rma\Model\Payment\ChangeSizePay;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template\Context;
use Magento\Quote\Model\QuoteRepository;
use Magento\Sales\Api\OrderRepositoryInterface;

/**
 *
 */
class Totals extends \Magento\Sales\Block\Order\Totals
{
    /**
     * @var QuoteRepository
     */
    protected $quoteRepository;
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    /**
     * @var OrderLocator
     */
    private $orderLocator;

    /**
     * Totals constructor.
     * @param Context $context
     * @param Registry $registry
     * @param OrderRepositoryInterface $orderRepository
     * @param OrderLocator $orderLocator
     * @param array $data
     */
    public function __construct(
        Context $context,
        Registry $registry,
        OrderRepositoryInterface $orderRepository,
        OrderLocator $orderLocator,
        array $data = []
    ) {
        parent::__construct($context, $registry, $data);
        $this->orderRepository = $orderRepository;
        $this->orderLocator = $orderLocator;
    }

    /**
     * @param null $area
     * @return array
     */
    public function getTotals($area = null)
    {
        try {
            $order = $this->getOrder();

            if ($order->getPayment()->getMethod() == ChangeSizePay::PAYMENT_CODE) {
                $this->orderLocator->reset();
                return $this->_totals;
            }

            $totals = [];
            if ($area === null) {
                $totals = $this->_totals;
            } else {
                $area = (string)$area;
                foreach ($this->_totals as $total) {
                    $totalArea = (string)$total->getArea();
                    if ($totalArea == $area) {
                        $totals[] = $total;
                    }
                }
            }
            return $totals;
        } catch (Exception $exception) {
            $this->_logger->critical($exception->getMessage(), ['exception' => $exception]);
            return $this->_totals;
        }
    }
}
