<?php

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

class CreateAllowancePayoutsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('allowance_payouts', function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->unsignedInteger('election_id');
            $table->unsignedInteger('voter_id');

            // Allow future-proofing: cash for fizikal, bank for maya
            $table->string('method', 20)->default('cash'); // cash | bank
            $table->string('status', 20)->default('paid'); // paid | void | pending

            // Store cents to avoid floating point issues
            $table->unsignedInteger('amount_cents');
            $table->char('currency', 3)->default('MYR');

            // Officer/audit trail (admin user who performed the action)
            $table->unsignedInteger('paid_by_admin_id')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->string('reference', 80)->nullable(); // optional bank ref / receipt no.
            $table->text('note')->nullable();

            // Prevent double-claim for the same election + method
            $table->unique(['election_id', 'voter_id', 'method'], 'allowance_payouts_unique_claim');

            $table->index(['election_id', 'method', 'status']);
            $table->index(['voter_id', 'election_id']);

            $table->foreign('election_id')
                ->references('id')
                ->on('election')
                ->onDelete('cascade');

            $table->foreign('voter_id')
                ->references('id')
                ->on('voter')
                ->onDelete('cascade');

            $table->timestamps();
        });
    }

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