<?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('payslip_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payslip_id')->constrained('payslips');
            $table->string('type', 30);
            $table->string('description', 255);
            $table->decimal('quantity', 8, 2)->default(1);
            $table->bigInteger('rate')->default(0);
            $table->bigInteger('amount'); // can be negative for deductions
            $table->boolean('is_deduction')->default(false);
            $table->string('source_type', 100)->nullable(); // polymorphic: TrainerCompensation, TrainerAdvance, etc.
            $table->unsignedBigInteger('source_id')->nullable();
            $table->jsonb('metadata')->default('{}');
            $table->integer('sort_order')->default(0);
            $table->timestamps();

            $table->index(['payslip_id', 'type']);
        });

        DB::statement("ALTER TABLE payslip_items ADD CONSTRAINT payslip_items_type_check CHECK (type IN ('base_salary', 'session_pay', 'group_pay', 'player_pay', 'revenue_share', 'overtime', 'substitute', 'bonus', 'penalty', 'advance_deduction', 'tax', 'insurance', 'other_deduction', 'cancelled_session_pay'))");
    }

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