<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('claims', function (Blueprint $table) {
            $table->id();
            $table->date('claim_date');

            // User FK
            $table->unsignedBigInteger('user_id')->nullable(); // nullable if some claims don't have a user yet
            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');

            // Vehicle type FK
            $table->unsignedBigInteger('jenis_kenderaan_id');
            $table->foreign('jenis_kenderaan_id')->references('id')->on('lkp_jenis_kenderaans')->onDelete('cascade');

            // Project FK
            $table->unsignedBigInteger('project_id');
            $table->foreign('project_id')->references('id')->on('lkp_project');


            // distance_from is always "Pejabat"
            $table->string('distance_from')->default('Pejabat');

            // User input fields
            $table->string('distance_to');
            $table->string('description')->nullable();
            $table->decimal('total_mileage', 8, 2);
            $table->decimal('toll_amount', 8, 2)->nullable();
            $table->decimal('others_amount', 8, 2)->nullable();
            $table->string('others_description')->nullable();

            $table->decimal('calculated_amount', 10, 2)->nullable(); // system auto-calculated RM
            $table->decimal('penalty_amount', 10, 2)->default(0);   // system-applied penalty if late
            $table->string('penalty_reason')->nullable();
            $table->decimal('total_claim_amount', 10, 2)->default(0);

            $table->unsignedBigInteger('rejected_by')->nullable()->after('total_claim_amount');
            $table->foreign('rejected_by')->references('id')->on('users')->onDelete('set null');

            // Claim status (workflow)
            $table->enum('status', [
                'Diproses',     // submitted by staff
                'Disokong',     // verified by PM/HOD
                'Disahkan',     // approved by Project Director/BOD
                'Disemak',      // reviewed by Finance
                'Diluluskan',   // approved by Finance Director
                'Ditolak',      // rejected
                'Dibetulkan',   // corrected by Finance
                'Dibayar'       // final paid
            ])->default('Diproses');
            
            $table->timestamps();
        });
    }

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