<?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_configs', function (Blueprint $table) {
            $table->id();
            $table->string('consumer_key')->nullable();
            $table->string('consumer_secret')->nullable();
            $table->string('shortcode')->nullable();
            $table->string('passkey')->nullable();
            $table->string('callback_url')->nullable();
            $table->string('confirmation_url')->nullable();
            $table->string('validation_url')->nullable();
            $table->boolean('is_active')->default(false);
            $table->boolean('is_production')->default(false);
            $table->text('notes')->nullable();
            $table->timestamps();
        });

        Schema::create('mpesa_transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('order_id')->nullable()->constrained()->onDelete('set null');
            $table->string('transaction_type')->nullable(); // CustomerPayBillOnline, CustomerBuyGoodsOnline
            $table->string('transaction_id')->unique()->nullable(); // M-Pesa transaction ID
            $table->string('transaction_time')->nullable();
            $table->decimal('amount', 12, 2)->default(0);
            $table->string('msisdn')->nullable(); // Phone number
            $table->string('sender')->nullable();
            $table->string('receiver')->nullable();
            $table->string('account_reference')->nullable(); // BillRefNumber
            $table->string('invoice_number')->nullable();
            $table->string('external_reference')->nullable();
            $table->string('status')->default('pending'); // pending, completed, failed, cancelled
            $table->text('raw_request')->nullable();
            $table->text('raw_response')->nullable();
            $table->timestamps();
        });
    }

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