<?php

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

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

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

            $table->string('method', 20)->default('cash'); // cash | bank

            // Store hash only (never store plaintext code)
            $table->string('code_hash', 255);
            $table->string('code_last4', 10)->nullable();

            $table->timestamp('expires_at')->nullable();
            $table->timestamp('used_at')->nullable();
            $table->unsignedInteger('used_by_admin_id')->nullable();

            // Only one row per voter per election per method (regenerate by updating same row)
            $table->unique(['election_id', 'voter_id', 'method'], 'allowance_claim_codes_unique');

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

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

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

            $table->foreign('used_by_admin_id')
                ->references('id')
                ->on('users')
                ->onDelete('set null');

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

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

