<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Plugin;

/**
 * Fix payment method options plugin
 *
 * Fixes malformed payment method options array in admin grid
 */
class FixPaymentMethodOptions
{
    /**
     * Fix malformed payment method options array
     *
     * @param \Magento\Backend\Block\Widget\Grid\Column\Filter\Select $subject
     * @param array $result
     * @return array
     */
    public function afterGetOptions($subject, $result)
    {
        if (!is_array($result)) {
            return $result;
        }

        $fixed = [];
        foreach ($result as $key => $option) {
            if (isset($option['value']) && is_array($option['value'])) {
                foreach ($option['value'] as $nestedKey => $nestedOption) {
                    if (is_array($nestedOption) && isset($nestedOption['value']) && isset($nestedOption['label'])) {
                        $fixed[$nestedKey] = $nestedOption;
                    }
                }
            } else {
                $fixed[$key] = $option;
            }
        }

        return $fixed;
    }
}
