<?php

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

class CreateTransactionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->id();
            $table->enum('type', ['deposit', 'withdrawal']);
            $table->enum('status', ['pending', 'approved', 'declined', 'completed', 'failed'])->default('pending');
            $table->string('transaction_id')->unique();
            $table->string('external_transaction_id')->nullable()->unique();
            $table->string('merchant_trx_id')->nullable();
            $table->unsignedBigInteger('finance_group_id')->nullable();
            $table->unsignedBigInteger('bank_account_id')->nullable();
            $table->decimal('amount', 15, 2);
            $table->string('currency', 10)->default('TRY');
            $table->string('customer_name');
            $table->string('customer_middle_name')->nullable();
            $table->string('customer_surname')->nullable();
            $table->string('customer_tc')->nullable();
            $table->string('customer_iban')->nullable();
            $table->string('customer_bank_name')->nullable();
            $table->string('customer_player_id')->nullable();
            $table->string('sid')->nullable();
            $table->string('api_key')->nullable();
            $table->text('hash')->nullable();
            $table->string('notify_url')->nullable();
            $table->json('callback_response')->nullable();
            $table->string('ip_address', 45)->nullable();
            $table->unsignedBigInteger('approved_by')->nullable();
            $table->timestamp('approved_at')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->foreign('finance_group_id')->references('id')->on('finance_groups')->onDelete('set null');
            $table->foreign('bank_account_id')->references('id')->on('bank_accounts')->onDelete('set null');

            $table->index('transaction_id');
            $table->index('external_transaction_id');
            $table->index('merchant_trx_id');
            $table->index('status');
            $table->index('type');
            $table->index('finance_group_id');
            $table->index('created_at');
            $table->index(['type', 'status', 'created_at']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('transactions');
    }
}
