<?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_compensations', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('trainer_id')->constrained('trainers');
            $table->foreignId('training_session_id')->nullable()->constrained('training_sessions');
            $table->foreignId('attendance_record_id')->nullable()->constrained('attendance_records');
            $table->unsignedBigInteger('payslip_item_id')->nullable(); // filled when included in a payslip item
            $table->date('date')->index();
            $table->string('type', 20);
            $table->string('description', 255)->nullable();
            $table->decimal('quantity', 8, 2)->default(1);
            $table->bigInteger('rate'); // piasters per unit
            $table->bigInteger('amount'); // total piasters (quantity × rate, or manual)
            $table->string('status', 20)->default('pending');
            $table->foreignId('approved_by')->nullable()->constrained('users');
            $table->dateTime('approved_at')->nullable();
            $table->text('notes')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->foreignId('created_by')->constrained('users');
            $table->timestamps();
            $table->softDeletes();

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

        DB::statement("ALTER TABLE trainer_compensations ADD CONSTRAINT trainer_compensations_type_check CHECK (type IN ('session_pay', 'group_pay', 'player_pay', 'revenue_share', 'bonus', 'penalty', 'overtime', 'substitute', 'cancelled_session'))");
        DB::statement("ALTER TABLE trainer_compensations ADD CONSTRAINT trainer_compensations_status_check CHECK (status IN ('pending', 'approved', 'disputed', 'paid', 'cancelled'))");
    }

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