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

use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\DB\Ddl\Table;

/**
 * Class AddTbiStatusColumnToOrderGrid
 * This class defines a schema patch to add a 'tbi_status' column to the 'sales_order_grid' table,
 * so the admin order grid can read it directly instead of joining 'sales_order' on every load.
 */
class AddTbiStatusColumnToOrderGrid implements SchemaPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * Constructor for the schema patch.
     *
     * @param ModuleDataSetupInterface $moduleDataSetup Setup module data setup interface.
     */
    public function __construct(ModuleDataSetupInterface $moduleDataSetup)
    {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    /**
     * Returns the array of patches that this patch depends on.
     *
     * @return array An array of dependencies.
     */
    public static function getDependencies()
    {
        return [AddTbiStatusColumn::class];
    }

    /**
     * Returns the array of aliases for this patch.
     *
     * @return array An array of aliases.
     */
    public function getAliases()
    {
        return [];
    }

    /**
     * Applies the schema patch to add 'tbi_status' column to the 'sales_order_grid' table.
     */
    public function apply()
    {
        $this->moduleDataSetup->startSetup();

        $connection = $this->moduleDataSetup->getConnection();
        $tableName = $this->moduleDataSetup->getTable('sales_order_grid');

        if (!$connection->tableColumnExists($tableName, 'tbi_status')) {
            $connection->addColumn(
                $tableName,
                'tbi_status',
                [
                    'type'      =>  Table::TYPE_TEXT,      // Column type is TEXT
                    'length'    =>  255,
                    'nullable'  =>  true,                  // Blank for non-FusionPay orders
                    'comment'   =>  'TBI Status',           // Comment for the column
                ]
            );
        }

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