<?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.28
 * @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 Mirasvit\Core\Ui\QuickDataBar\ScalarDataBlock;
use Mirasvit\Rma\Api\Data\MessageInterface;
use Mirasvit\Rma\Model\Message;

class UnreadDataBlock extends ScalarDataBlock
{
    private $resource;

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

        parent::__construct($context);
    }

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

    public function getLabel(): string
    {
        return (string)__('Unread:');
    }

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

        $value = (int)$this->resource->getConnection()
            ->fetchOne('SELECT COUNT(*) FROM (' . $select . ') as rmc');

        return (string)$value;
    }

    public function getSelect(array $columns = []): Select
    {
        $columns = array_merge($columns, [
            'value' => new \Zend_Db_Expr(Message::KEY_RMA_ID),
        ]);

        return $this->resource->getConnection()
            ->select()
            ->from($this->resource->getTableName(MessageInterface::TABLE_NAME), $columns)
            ->where(Message::KEY_IS_READ . ' = 0 AND ' . Message::KEY_CUSTOMER_ID . ' > 0')
            ->group(Message::KEY_RMA_ID);
    }
}
