<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('mpesa_transactions', function (Blueprint $table) {
            $table->id();
            $table->string('transaction_id')->unique(); // M-Pesa transaction ID
            $table->string('reference'); // Internal reference/Invoice number
            $table->string('phone'); // Customer phone
            $table->decimal('amount', 10, 2); // Transaction amount
            $table->decimal('expected_amount', 10, 2); // Expected amount for matching
            $table->timestamp('transaction_date'); // M-Pesa transaction time
            $table->string('status')->default('pending'); // pending, completed, failed, matched
            $table->string('description')->nullable();
            $table->string('first_name')->nullable();
            $table->string('middle_name')->nullable();
            $table->string('last_name')->nullable();
            $table->foreignId('sale_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('customer_id')->nullable()->constrained()->nullOnDelete();
            $table->json('raw_response')->nullable(); // Full M-Pesa response
            $table->timestamps();
            
            $table->index(['phone', 'status']);
            $table->index(['transaction_id']);
            $table->index(['transaction_date']);
        });
    }

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