<?php
declare(strict_types=1);

namespace FiloBlu\Refilo\Console\Command;

use Magento\Framework\Console\Cli;
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 Cli::RETURN_SUCCESS;
        }

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

            // is_viewide_order is provided by Bcame_Viewide; skip if that module is not installed.
            if ($connection->tableColumnExists($orderTable, 'is_viewide_order')) {
                $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);
        } catch (\Throwable $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');
            return Cli::RETURN_FAILURE;
        }

        return Cli::RETURN_SUCCESS;
    }
}
