<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('bill_payments', function (Blueprint $table) {

            $table->id();

            // Ownership
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');

            // Reference
            $table->string('bill_number')->unique()->comment('Unique bill reference e.g. BP-2024-000001');

            // Bill details
            $table->string('category')->comment('electricity|water|mobile|internet|rent|credit_card|insurance|education|mortgage|healthcare');
            $table->string('biller_name');
            $table->string('account_number')->comment('Biller account or reference number');

            // Financials
            $table->decimal('amount', 28, 8);
            $table->decimal('charge', 28, 8)->default(0);
            $table->decimal('final_amount', 28, 8)->comment('amount + charge');
            $table->string('currency')->nullable()->comment('Currency text e.g. USD');
            $table->decimal('post_balance', 28, 8)->default(0)->comment('User balance after transaction');

            // Scheduling
            $table->date('due_date')->nullable();

            // Optional note
            $table->text('note')->nullable();

            /**
             * Payment Status:
             *  0 = Pending
             *  1 = Paid (Completed)
             *  2 = Processing
             *  3 = Rejected / Failed
             *  4 = Cancelled
             */
            $table->tinyInteger('status')->default(0)->comment('0=Pending, 1=Paid, 2=Processing, 3=Rejected, 4=Cancelled');

            // Admin feedback on rejection
            $table->text('admin_feedback')->nullable();

            // Transaction cross-reference
            $table->string('trx')->nullable()->comment('Transaction ID linked to wallet debit');

            $table->timestamps();

            // Indexes for common queries
            $table->index('user_id');
            $table->index('status');
            $table->index('category');
            $table->index('due_date');
            $table->index('created_at');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('bill_payments');
    }
};
