<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Doctrine\DBAL;

class AddIndexToTransactionTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::connection('mysql7')->table('transaction', static function (Blueprint $table) {
            $schemaManager = Schema::getConnection()->getDoctrineSchemaManager();
            $indexesFound  = $schemaManager->listTableIndexes('transaction');

            if (! array_key_exists('idx_search_norujukan', $indexesFound)) {
                $table->index(['norujukan', 'created_at', 'trans_type', 'kodcaw'], 'idx_search_norujukan');
            }
        });

        Schema::connection('mysql7')->table('transaksi_keuntungan', static function (Blueprint $table) {
            $schemaManager = Schema::getConnection()->getDoctrineSchemaManager();
            $indexesFound  = $schemaManager->listTableIndexes('transaksi_keuntungan');

            if (! array_key_exists('idx_tarikh_bayaran', $indexesFound)) {
                $table->index('tarikh_bayaran', 'idx_tarikh_bayaran');
            }
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::connection('mysql7')->table('transaction', static function (Blueprint $table) {
            $schemaManager = Schema::getConnection()->getDoctrineSchemaManager();
            $indexesFound  = $schemaManager->listTableIndexes('transaction');

            if (array_key_exists('idx_seach_norujukan', $indexesFound)) {
                $table->dropIndex('idx_search_norujukan');
            }
        });


        Schema::connection('mysql7')->table('transaksi_keuntungan', static function (Blueprint $table) {
            $schemaManager = Schema::getConnection()->getDoctrineSchemaManager();
            $indexesFound  = $schemaManager->listTableIndexes('transaksi_keuntungan');

            if (array_key_exists('idx_tarikh_bayaran', $indexesFound)) {
                $table->dropIndex('idx_tarikh_bayaran');
            }
        });
    }
}
