<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('business_trips', function (Blueprint $table) {
            // Instansi yang dikunjungi
            $table->foreignId('destination_office_id')
                ->nullable()
                ->after('destination_province')
                ->constrained('offices')
                ->nullOnDelete();

            $table->string('destination_institution')->nullable()->after('destination_office_id');

            // Jenis transportasi
            $table->enum('transportation_type', [
                'pesawat',
                'kereta',
                'bus',
                'mobil_dinas',
                'mobil_pribadi',
                'lainnya'
            ])->nullable()->after('destination_institution');

            // Nomor surat tugas
            $table->string('surat_tugas_number')->nullable()->after('transportation_type');

            // Update status enum - tambahkan pending dan approved
            // Karena MySQL tidak bisa alter enum, kita drop dan create ulang
        });

        // Alter status enum dengan cara yang aman
        \DB::statement("ALTER TABLE business_trips MODIFY COLUMN status ENUM('pending', 'approved', 'rejected', 'ongoing', 'completed') DEFAULT 'pending'");

        Schema::table('business_trips', function (Blueprint $table) {
            // Approval fields
            $table->foreignId('approved_by')
                ->nullable()
                ->after('status')
                ->constrained('users')
                ->nullOnDelete();

            $table->timestamp('approved_at')->nullable()->after('approved_by');
            $table->text('rejection_reason')->nullable()->after('approved_at');

            // Index
            $table->index('transportation_type');
            $table->index('surat_tugas_number');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('business_trips', function (Blueprint $table) {
            $table->dropForeign(['destination_office_id']);
            $table->dropForeign(['approved_by']);
            $table->dropIndex(['transportation_type']);
            $table->dropIndex(['surat_tugas_number']);
            $table->dropColumn([
                'destination_office_id',
                'destination_institution',
                'transportation_type',
                'surat_tugas_number',
                'approved_by',
                'approved_at',
                'rejection_reason',
            ]);
        });

        \DB::statement("ALTER TABLE business_trips MODIFY COLUMN status ENUM('ongoing', 'completed') DEFAULT 'ongoing'");
    }
};
