<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('mpesa_transactions', function (Blueprint $table) {
            $table->id();
            $table->string('checkout_request_id')->unique()->index();
            $table->unsignedBigInteger('payment_id')->nullable();
            $table->string('phone_number');
            $table->decimal('amount', 10, 2);
            $table->enum('status', ['pending', 'completed', 'failed'])->default('pending');
            $table->string('mpesa_receipt')->nullable();
            $table->string('result_code')->nullable();
            $table->text('result_desc')->nullable();
            $table->string('merchant_request_id')->nullable();
            $table->string('response_code')->nullable();
            $table->string('response_description')->nullable();
            $table->timestamps();
            
            $table->foreign('payment_id')
                  ->references('id')
                  ->on('internet_payments')
                  ->onDelete('set null');
                  
            $table->index(['status', 'created_at']);
            $table->index('phone_number');
        });
    }

    public function down()
    {
        Schema::dropIfExists('mpesa_transactions');
    }
};