<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Plugins;

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

/**
 * Class Cart
 * @package FiloBlu\Refilo\Plugins
 */
class Cart
{
    /**
     * @var string
     */
    const XML_REFILO_SALES_CART_SHOW_SHIPPING_ESTIMATION_IN_CART = 'refilo_sales/cart/show_shipping_estimation_in_cart';

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     */
    public function __construct(ScopeConfigInterface $scopeConfig)
    {
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @param Quote $subject
     * @param $result
     * @return mixed
     */
    public function afterGetExtensionAttributes(Quote $subject, $result)
    {
        try {
            $result->setFilobluSubtotal($subject->getSubtotal());
            $result->setFilobluGrandtotal($subject->getGrandTotal());
            if ($this->canDisplayEstimation($subject)) {
                $result->setFilobluShippingEstimated($this->evaluateShippingEstimation($subject));
            }
        } catch (Throwable $throwable) {
            return $result;
        }

        return $result;
    }

    /**
     * @param Quote $quote
     * @return bool
     */
    public function evaluateShippingEstimation(Quote $quote)
    {
        return $quote->getShippingAddress()->validate() !== true;
    }

    /**
     * @param \Magento\Quote\Model\Quote $quote
     * @return bool
     */
    public function canDisplayEstimation(Quote $quote) : bool
    {
        return $this->scopeConfig->isSetFlag(
            self::XML_REFILO_SALES_CART_SHOW_SHIPPING_ESTIMATION_IN_CART,
            ScopeInterface::SCOPE_STORE,
            $quote->getStoreId()
        );
    }
}
