<?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('payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->constrained()->cascadeOnDelete();
            $table->string('payment_reference')->unique();
            
            $table->enum('method', ['cash', 'mpesa', 'card', 'bank_transfer'])->default('cash');
            $table->enum('status', ['pending', 'completed', 'failed', 'refunded'])->default('pending');
            
            $table->decimal('amount', 10, 2);
            $table->decimal('received_amount', 10, 2)->nullable(); // For cash payments
            $table->decimal('change_amount', 10, 2)->nullable();
            
            // M-Pesa specific fields
            $table->string('mpesa_receipt_number')->nullable();
            $table->string('mpesa_transaction_id')->nullable();
            $table->string('mpesa_phone_number')->nullable();
            
            // Card payment fields
            $table->string('card_last_four')->nullable();
            $table->string('card_type')->nullable();
            $table->string('authorization_code')->nullable();
            
            $table->text('notes')->nullable();
            $table->timestamp('processed_at')->nullable();
            
            $table->timestamps();
            
            $table->index(['order_id', 'status']);
            $table->index(['method', 'created_at']);
        });
    }

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