<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class MappingCustomerOrderCommand
 * @package FiloBlu\Refilo\Console\Command
 */
class OrderMappingCommand extends Command
{
    /**
     * @var \FiloBlu\Refilo\Helper\OrderMappingHelper
     */
    private $orderMappingHelper;

    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    private $resourceConnection;

    /**
     * @param \FiloBlu\Refilo\Helper\OrderMappingHelper $orderMappingHelper
     * @param \Magento\Framework\App\ResourceConnection $resourceConnection
     * @param string|null $name
     */
    public function __construct(
        \FiloBlu\Refilo\Helper\OrderMappingHelper $orderMappingHelper,
        \Magento\Framework\App\ResourceConnection $resourceConnection,
        string $name = null
    ) {
        parent::__construct($name);
        $this->orderMappingHelper = $orderMappingHelper;
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * @inheritDoc
     */
    protected function configure()
    {
        $this->setName('refilo:order:mapping');
        $this->setDescription('Mapping customer-order');
        parent::configure();
    }

    /**
     * Execute the command
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $enabledStore = $this->orderMappingHelper->getEnabledStore();
        if (count($enabledStore) === 0) {
            return 0;
        }

        $connection = $this->resourceConnection->getConnection();
        $orderTable = $connection->getTableName('sales_order');
        $mappingTable = $connection->getTableName('filoblu_order_mapping');
        $customerTable = $connection->getTableName('customer_entity');

        $connection->update($orderTable, ['is_in_store' => 1], "is_viewide_order = 1");

        $select = $connection->select()
            ->from(['so' => $orderTable], ['entity_id', 'store_id'])
            ->joinInner(['ce' => $customerTable], 'ce.email = so.customer_email', ['ce.entity_id'])
            ->where('so.is_in_store = 1')
            ->where('so.store_id in (?)', array_keys($enabledStore));

        $query = "INSERT INTO $mappingTable (order_id, order_store_id, customer_id) " . $select->__toString() .
            " ON DUPLICATE KEY UPDATE order_store_id = VALUES(order_store_id);";

        $connection->query($query);

        return 0;
    }
}
