<?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 UpgradeSchema221 implements SibsUpgradeSchemaInterface
{
    private $upgradeVersion = '2.2.1';

    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_capture_id') === false) {
            $connection->addColumn($setup->getTable($salesOrderTable), 'sibs_capture_id', [
                'type'    => Table::TYPE_TEXT,
                'length'  => 255,
                'comment' => 'Capture ID',
                'after'   => 'sibs_payment_type',
            ]);
        }

        if ($connection->tableColumnExists($salesOrderTable, 'sibs_capture_status') === false) {
            $connection->addColumn($setup->getTable($salesOrderTable), 'sibs_capture_status', [
                'type'    => Table::TYPE_TEXT,
                'length'  => 255,
                'comment' => 'Capture Status',
                'after'   => 'sibs_capture_id',
            ]);
        }

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