<?php

namespace Sibs\Sibs\Setup\Migrations;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Sibs\Sibs\Model\SibsConstants;
use Sibs\Sibs\Setup\SibsUpgradeSchemaInterface;
use Sibs\Sibs\Utils\SibsLog;

class UpgradeSchema245 implements SibsUpgradeSchemaInterface
{
    private $upgradeVersion = '2.4.5';

    private $context;

    public function __construct(ModuleContextInterface $context)
    {
        $this->context = $context;

        SibsLog::setNameFile(SibsConstants::SIBS_LOG_INSTALL);
    }

    public function getUpgradeVersion()
    {
        return $this->upgradeVersion;
    }

    public function validateVersion()
    {
        return version_compare($this->context->getVersion(), $this->getUpgradeVersion(), '<');
    }

    public function upgrade(SchemaSetupInterface $setup)
    {
        if (! $this->validateVersion()) {
            SibsLog::warn('Will not update schema on ' . $this->context->getVersion() . ' to version ' . $this->getUpgradeVersion());

            return;
        }

        SibsLog::warn('Try to Update Schema to version ' . $this->getUpgradeVersion());

        $connection      = $setup->getConnection();
        $salesOrderTable = $setup->getTable('sales_order');

        // For all sibs orders
        if ($connection->tableColumnExists($salesOrderTable, 'sibs_form_context') === false) {
            $connection->addColumn($setup->getTable($salesOrderTable), 'sibs_form_context', [
                'type'    => Table::TYPE_TEXT,
                '2M',
                'comment' => 'Form Context',
                'after'   => 'sibs_refunded_status',
            ]);
        }

        if ($connection->tableColumnExists($salesOrderTable, 'sibs_transaction_signature') === false) {
            $connection->addColumn($setup->getTable($salesOrderTable), 'sibs_transaction_signature', [
                'type'    => Table::TYPE_TEXT,
                '2M',
                'comment' => 'Transaction Signature',
                'after'   => 'sibs_form_context',
            ]);
        }

        SibsLog::warn('Updated Schema version ' . $this->getUpgradeVersion());
    }
}
