<?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('payslips', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('trainer_id')->constrained('trainers');
            $table->foreignId('payroll_period_id')->constrained('payroll_periods');
            $table->string('payslip_number', 30);
            $table->bigInteger('base_amount')->default(0);
            $table->bigInteger('session_earnings')->default(0);
            $table->bigInteger('bonuses')->default(0);
            $table->bigInteger('penalties')->default(0);
            $table->bigInteger('advances_deducted')->default(0);
            $table->bigInteger('tax_amount')->default(0);
            $table->bigInteger('insurance_amount')->default(0);
            $table->bigInteger('other_deductions')->default(0);
            $table->bigInteger('gross_amount')->default(0);
            $table->bigInteger('total_deductions')->default(0);
            $table->bigInteger('net_amount')->default(0);
            $table->string('status', 20)->default('draft');
            $table->foreignId('approved_by')->nullable()->constrained('users');
            $table->dateTime('approved_at')->nullable();
            $table->dateTime('paid_at')->nullable();
            $table->string('payment_method', 20)->nullable();
            $table->string('payment_reference', 100)->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']);
            $table->index(['academy_id', 'payroll_period_id']);
            $table->index(['academy_id', 'status']);
            $table->unique(['academy_id', 'payslip_number']);
        });

        DB::statement("ALTER TABLE payslips ADD CONSTRAINT payslips_status_check CHECK (status IN ('draft', 'pending_approval', 'approved', 'paid', 'cancelled'))");
        DB::statement("ALTER TABLE payslips ADD CONSTRAINT payslips_payment_method_check CHECK (payment_method IS NULL OR payment_method IN ('cash', 'bank_transfer', 'instapay', 'cheque'))");
    }

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