<?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('transaction_id')->unique()->nullable(); // M-Pesa Transaction ID
            $table->string('merchant_request_id')->nullable();
            $table->string('checkout_request_id')->nullable();
            $table->string('phone_number');
            $table->decimal('amount', 10, 2);
            $table->string('account_reference')->nullable();
            $table->string('transaction_desc')->nullable();
            $table->string('transaction_type')->default('CustomerPayBillOnline');
            $table->string('status')->default('pending'); // pending, success, failed, cancelled
            $table->text('response_code')->nullable();
            $table->text('response_description')->nullable();
            $table->text('customer_message')->nullable();
            $table->text('request_data')->nullable(); // Store original request data
            $table->text('response_data')->nullable(); // Store full response data
            $table->timestamp('transaction_time')->nullable();
            $table->foreignId('order_id')->nullable()->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('set null');
            $table->timestamps();
            
            // Indexes for faster queries
            $table->index('transaction_id');
            $table->index('checkout_request_id');
            $table->index('phone_number');
            $table->index('status');
            $table->index('created_at');
        });
    }

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