<?php

/**
 * @psalm-scope-this Mage_Core_Model_Resource_Setup
 */
$installer = $this;

$installer->startSetup();

$conn = $installer->getConnection();
$quoteTable = $installer->getTable("sales/quote");

if( ! $conn->tableColumnExists($quoteTable, "x_forwarded_for")) {
    $conn->addColumn($quoteTable, "x_forwarded_for", [
        "type" => Varien_Db_Ddl_Table::TYPE_TEXT,
        "length" => 255,
        "comment" => "Value of the X-Forwarded-For HTTP header from the customer session",
        "default" => null,
        "nullable" => true,
    ]);
}

$tableIndices = [
    "sales/quote" => [
        ["x_forwarded_for"],
        ["remote_ip"],
    ],
    "sales/order" => [
        ["x_forwarded_for"],
        ["remote_ip"],
    ],
];

foreach($tableIndices as $model => $indices) {
    $table = $installer->getTable($model);
    $existingIndexes = $conn->getIndexList($table);

    foreach($indices as $fields) {
        $name = $conn->getIndexName($model, $fields);

        if( ! array_key_exists(strtoupper($name), $existingIndexes)) {
            $conn->addIndex($table, $name, $fields);
        }
    }
}

$installer->endSetup();
