<?php

namespace EasySales\Integrari\Model;

use EasySales\Integrari\Api\PaymentManagementInterface;
use EasySales\Integrari\Core\Auth\CheckWebsiteToken;
use EasySales\Integrari\Helper\Data;
use Exception;
use Magento\Framework\Webapi\Rest\Request as RequestInterface;
use Magento\Payment\Api\PaymentMethodListInterface;
use Magento\Store\Model\StoreManagerInterface;

class PaymentManagement extends CheckWebsiteToken implements PaymentManagementInterface
{
    /**
     * @var Data
     */
    protected $helperData;

    /**
     * @var PaymentMethodListInterface
     */
    private $paymentMethodList;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @param Data $helperData
     * @param RequestInterface $request
     * @param PaymentMethodListInterface $paymentMethodList
     * @param StoreManagerInterface $storeManager
     * @throws Exception
     */
    public function __construct(
        Data $helperData,
        RequestInterface $request,
        PaymentMethodListInterface $paymentMethodList,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($request, $helperData);
        $this->helperData = $helperData;
        $this->paymentMethodList = $paymentMethodList;
        $this->storeManager = $storeManager;
    }

    /**
     * GET api for the store active payment methods
     *
     * @inheritDoc
     */
    public function getPaymentMethods()
    {
        try {
            $storeId = $this->helperData->getGeneralConfig('store_id');
            $store = $this->storeManager->getStore($storeId);

            $paymentMethods = [];
            foreach ($this->paymentMethodList->getActiveList($store->getId()) as $method) {
                $paymentMethods[] = [
                    'code' => $method->getCode(),
                    'title' => $method->getTitle(),
                ];
            }

            return [[
                'payment_methods' => $paymentMethods,
            ]];
        } catch (Exception $exception) {
            return [[
                'success' => false,
                'message' => $exception->getMessage(),
            ]];
        }
    }
}
