<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace FiloBlu\Rma\Block\Adminhtml\Order\View;

use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Api\OrderRepositoryInterface;

/**
 * Order history block
 *
 * @api
 * @since 100.0.2
 */
class AdditionalInformations extends Template
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * @param Template\Context $context
     * @param OrderRepositoryInterface $orderRepository
     * @param array $data
     */
    public function __construct(Template\Context         $context,
                                OrderRepositoryInterface $orderRepository,
                                array                    $data = [])
    {
        parent::__construct($context, $data);
        $this->orderRepository = $orderRepository;
    }


    /**
     * @return string
     */
    public function getPaymentAdditionalInfo()
    {
        $orderId = $this->getRequest()->getParam('order_id');
        $html = '';
        if ($orderId) {
            $order = $this->orderRepository->get($orderId);
            $paymentAdditionalInformation = $order->getPayment()->getAdditionalInformation();
            foreach ($paymentAdditionalInformation as $key => $val) {
                if ($key == 'parent_order') {
                    $html .= "<div>Parent Order: {$this->getOrderLink($val)}</div>";
                } elseif (is_array($val)) {
                    /*
                     * Orders placed by Credit Card using 3D secure V2, returns some additional information in an array.
                     * Fix made for this case.
                     */
                    $html .= "<div>$key : ".$this->recursivePrint($val) . '</div>';
                } else {
                    $html .= "<div>$key : $val</div>";
                }

            }
        }
        return $html;
    }

    /**
     * TODO: Move in helper
     * TODO: Refactor
     * @param $array
     * @return void
     */
    public function recursivePrint($array){
        foreach($array as $value){
            //If $value is an array.
            if(is_array($value)){
                //We need to loop through it.
                $this->recursivePrint($value);
            } else{
                //It is not an array, so print it out.
                echo $value;
            }
        }
    }

    /**
     * @param $orderId
     * @return string
     */
    public function getOrderLink($orderId)
    {
        if (!$orderId) {
            return '';
        }

        $url = $this->_urlBuilder->getUrl('sales/order/view', ['order_id' => $orderId]);

        return "<a href=\"$url\">$orderId</a>";
    }
}
