<?php
namespace TbiBank\FusionPay\Setup\Patch\Data;

use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * Class BackfillTbiStatusInOrderGrid
 * Copies the existing 'tbi_status' value from 'sales_order' into the newly added
 * 'sales_order_grid.tbi_status' column for FusionPay orders placed before this column existed.
 * Going forward, TbiStatusUpdate keeps both columns in sync on every status change.
 */
class BackfillTbiStatusInOrderGrid implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     */
    public function __construct(ModuleDataSetupInterface $moduleDataSetup)
    {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    /**
     * @return array
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * @return array
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * Backfill 'tbi_status' on 'sales_order_grid' for existing FusionPay orders.
     */
    public function apply()
    {
        $this->moduleDataSetup->startSetup();

        $connection = $this->moduleDataSetup->getConnection();
        $gridTable = $this->moduleDataSetup->getTable('sales_order_grid');
        $orderTable = $this->moduleDataSetup->getTable('sales_order');
        $paymentTable = $this->moduleDataSetup->getTable('sales_order_payment');

        $connection->query(
            sprintf(
                'UPDATE %s AS sog
                 INNER JOIN %s AS so ON so.entity_id = sog.entity_id
                 INNER JOIN %s AS sop ON sop.parent_id = so.entity_id AND sop.method = \'fusionpay\'
                 SET sog.tbi_status = so.tbi_status',
                $connection->quoteIdentifier($gridTable),
                $connection->quoteIdentifier($orderTable),
                $connection->quoteIdentifier($paymentTable)
            )
        );

        $this->moduleDataSetup->endSetup();
    }
}
