<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('trainer_advances', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('trainer_id')->constrained('trainers');
            $table->bigInteger('amount'); // total advance amount (piasters)
            $table->bigInteger('remaining_balance'); // how much is still owed
            $table->bigInteger('installment_amount'); // amount deducted per payroll period
            $table->integer('installments_count'); // total number of installments
            $table->integer('installments_paid')->default(0);
            $table->text('reason')->nullable();
            $table->string('status', 20)->default('active');
            $table->date('issued_date');
            $table->date('expected_completion_date')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users');
            $table->text('notes')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();
            $table->softDeletes();

            $table->index(['academy_id', 'trainer_id', 'status']);
            $table->index(['academy_id', 'status']);
        });

        DB::statement("ALTER TABLE trainer_advances ADD CONSTRAINT trainer_advances_status_check CHECK (status IN ('active', 'fully_deducted', 'cancelled', 'paused'))");
    }

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