<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('payslips', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payroll_run_id')->constrained('payroll_runs')->cascadeOnDelete();
            $table->foreignId('employee_id')->constrained('employees')->restrictOnDelete();

            // --- Snapshots taken at calculation time (never re-read from master) ---
            $table->string('employee_code');
            $table->string('full_name')->nullable();
            $table->string('salary_structure')->nullable();
            $table->string('grade_level')->nullable();
            $table->unsignedSmallInteger('salary_step')->nullable();
            $table->string('department_name')->nullable();

            $table->string('bank_name')->nullable();
            $table->string('bank_branch')->nullable();
            $table->string('account_type')->nullable();
            $table->string('account_number', 32)->nullable();

            $table->string('pension_house')->nullable();
            $table->string('pen_number', 32)->nullable();

            // --- Totals ---
            $table->decimal('basic', 15, 2)->default(0);
            $table->decimal('gross', 15, 2)->default(0);
            $table->decimal('taxable_income', 15, 2)->default(0);
            $table->decimal('tax', 15, 2)->default(0);
            $table->decimal('statutory_deductions', 15, 2)->default(0);
            $table->decimal('voluntary_deductions', 15, 2)->default(0);
            $table->decimal('total_deductions', 15, 2)->default(0);
            $table->decimal('net_pay', 15, 2)->default(0);

            $table->timestamps();

            $table->unique(['payroll_run_id', 'employee_id']);
            $table->index('employee_code');
        });
    }

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