<?php
declare(strict_types=1);

namespace Autogedal\PayPo\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Sales\Model\Order;
use PayPo\Payment\Model\Payment\PayPo;

class ApprovalConfig
{
    public const XML_PATH_STATUSES = 'payment/paypo/approval_statuses';

    public function __construct(private readonly ScopeConfigInterface $scopeConfig)
    {
    }

    public function isAllowed(?string $status, int|string|null $storeId): bool
    {
        $configured = (string)$this->scopeConfig->getValue(
            self::XML_PATH_STATUSES,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
        $statuses = array_filter(array_map('trim', explode(',', $configured)));

        return $status !== null && in_array($status, $statuses, true);
    }

    public function isOrderAllowed(Order $order, bool $useOriginalStatus = false): bool
    {
        return $order->getPayment()?->getMethod() === PayPo::METHOD_CODE
            && !in_array($order->getState(), [
                Order::STATE_CANCELED, Order::STATE_HOLDED, Order::STATE_COMPLETE, Order::STATE_CLOSED,
            ], true)
            && !$order->canUnhold()
            && $this->isAllowed(
                $useOriginalStatus ? $order->getOrigData('status') : $order->getStatus(),
                $order->getStoreId()
            );
    }
}
