<?php
/**
 * Mirasvit
 *
 * This source file is subject to the Mirasvit Software License, which is available at https://mirasvit.com/license/.
 * Do not edit or add to this file if you wish to upgrade the to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please refer to http://www.magentocommerce.com for more information.
 *
 * @category  Mirasvit
 * @package   mirasvit/module-rma
 * @version   2.2.22
 * @copyright Copyright (C) 2023 Mirasvit (https://mirasvit.com/)
 */



namespace Mirasvit\Rma\Ui\QuickDataBar\OverviewDataBlocks;

use Magento\Backend\Block\Template;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Select;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Mirasvit\Core\Ui\QuickDataBar\ScalarDataBlock;
use Mirasvit\Rma\Api\Data\ItemInterface;

class RefundDataBlock extends ScalarDataBlock
{
    private $currency;

    private $resource;

    public function __construct(
        PriceCurrencyInterface $currency,
        ResourceConnection $resource,
        Template\Context $context
    ) {
        $this->currency = $currency;
        $this->resource = $resource;

        parent::__construct($context);
    }

    public function getCode(): string
    {
        return 'rma_overview_refund';
    }

    public function getLabel(): string
    {
        return (string)__('Amount to refund:');
    }

    public function getScalarValue(): string
    {
        $select = $this->getSelect();

        $value = (int)$this->resource->getConnection()
            ->fetchOne($select);

        $baseCurrency = $this->_storeManager->getStore()->getBaseCurrency();

        return (string)$this->currency->format(number_format($value, 2, '.', ' '), false, 2, null, $baseCurrency);
    }

    public function getSelect(array $columns = []): Select
    {
        $columns = array_merge($columns, [
            'value' => new \Zend_Db_Expr('SUM(soi.base_price_incl_tax - soi.base_discount_amount)'),
        ]);

        return $this->resource->getConnection()
            ->select()
            ->from(['rmai' => $this->resource->getTableName(ItemInterface::TABLE_NAME)], $columns)
            ->joinLeft(['soi' => $this->resource->getTableName('sales_order_item')], 'rmai.order_item_id = soi.item_id', new \Zend_Db_Expr('base_price_incl_tax, base_discount_amount'))
            ->where(ItemInterface::KEY_QTY_REQUESTED . ' >= 1');
    }
}
