<?php
namespace PortalPeople\DisabledPostcodes\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Config
{
    private const XML_PATH_ENABLED = 'portalpeople_disabledpostcodes/general/enabled';
    private const XML_PATH_BLOCKED_MESSAGE = 'portalpeople_disabledpostcodes/general/blocked_message';
    private const CHECKOUT_SUFFIX = ' Please change your postcode to continue checkout.';

    private ScopeConfigInterface $scopeConfig;

    public function __construct(ScopeConfigInterface $scopeConfig)
    {
        $this->scopeConfig = $scopeConfig;
    }

    public function isEnabled(?int $storeId = null): bool
    {
        return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE, $storeId);
    }

    public function getBlockedMessage(?int $storeId = null): string
    {
        $message = (string)$this->scopeConfig->getValue(self::XML_PATH_BLOCKED_MESSAGE, ScopeInterface::SCOPE_STORE, $storeId);
        return $message !== '' ? $message : 'We are sorry, we do not deliver to this area.';
    }

    public function getBlockedCheckoutMessage(?int $storeId = null): string
    {
        $message = trim($this->getBlockedMessage($storeId));

        if (stripos($message, 'please change your postcode to continue checkout') !== false) {
            return $message;
        }

        return rtrim($message, " \t\n\r\0\x0B.") . '.' . self::CHECKOUT_SUFFIX;
    }
}
