<?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
    {
        // Add paid_at to loan_repayments if missing
        Schema::table('loan_repayments', function (Blueprint $table) {
            if (!Schema::hasColumn('loan_repayments', 'paid_at')) {
                $table->timestamp('paid_at')->nullable()->after('confirmed_at');
            }
        });

        Schema::create('staff_loans', function (Blueprint $table) {
            $table->id();
            $table->string('loan_number')->unique();
            $table->foreignId('employee_id')->constrained('employees')->onDelete('cascade');
            $table->foreignId('company_id')->constrained('companies')->onDelete('cascade');
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->decimal('principal_amount', 15, 2);
            $table->decimal('outstanding_balance', 15, 2);
            $table->decimal('interest_rate', 5, 2)->default(0);
            $table->integer('term_months');
            $table->text('purpose')->nullable();
            $table->enum('deduction_type', ['percentage', 'fixed'])->default('fixed');
            $table->decimal('deduction_value', 10, 2);
            $table->enum('status', ['pending', 'approved', 'active', 'paid_off', 'rejected'])->default('pending');
            $table->text('notes')->nullable();
            $table->date('start_date')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['employee_id', 'status']);
            $table->index(['company_id', 'status']);
        });

        Schema::create('staff_loan_deductions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('staff_loan_id')->constrained('staff_loans')->onDelete('cascade');
            $table->foreignId('employee_id')->constrained('employees')->onDelete('cascade');
            $table->integer('month_number');
            $table->date('due_date');
            $table->decimal('deduction_amount', 12, 2);
            $table->decimal('principal_portion', 12, 2);
            $table->decimal('interest_portion', 12, 2)->default(0);
            $table->enum('status', ['scheduled', 'deducted', 'missed'])->default('scheduled');
            $table->date('deducted_on')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index(['staff_loan_id', 'status']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('staff_loan_deductions');
        Schema::dropIfExists('staff_loans');
        Schema::table('loan_repayments', function (Blueprint $table) {
            if (Schema::hasColumn('loan_repayments', 'paid_at')) {
                $table->dropColumn('paid_at');
            }
        });
    }
};
