<?php
/**
 * Upgrade Schema to rename delivery_message to shipping_message
 */

namespace PortalPeople\ShippingFields\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * Upgrade schema
     *
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $this->addShippingMessageColumns($setup);
        }

        $setup->endSetup();
    }

    /**
     * Add shipping_message columns to tables
     *
     * @param SchemaSetupInterface $setup
     * @return void
     */
    private function addShippingMessageColumns(SchemaSetupInterface $setup)
    {
        $connection = $setup->getConnection();

        // Add to quote table
        $quoteTable = $setup->getTable('quote');
        if (!$connection->tableColumnExists($quoteTable, 'shipping_message')) {
            $connection->addColumn(
                $quoteTable,
                'shipping_message',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'nullable' => true,
                    'comment' => 'Shipping Message'
                ]
            );
        }

        // Add to sales_order table
        $orderTable = $setup->getTable('sales_order');
        if (!$connection->tableColumnExists($orderTable, 'shipping_message')) {
            $connection->addColumn(
                $orderTable,
                'shipping_message',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'nullable' => true,
                    'comment' => 'Shipping Message'
                ]
            );
        }
    }
}
