<?php

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

class ChangeStatusColumnToVarcharInPengajuanKeuangansTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Cek apakah kolom status masih ada
        if (Schema::hasColumn('pengajuan_keuangans', 'status')) {
            // Backup data terlebih dahulu
            DB::statement('CREATE TABLE IF NOT EXISTS pengajuan_keuangans_status_backup AS SELECT id, status FROM pengajuan_keuangans');
            
            // Hapus kolom status yang lama (ENUM)
            Schema::table('pengajuan_keuangans', function (Blueprint $table) {
                $table->dropColumn('status');
            });
        }
        
        // Tambah kolom status baru dengan tipe VARCHAR
        Schema::table('pengajuan_keuangans', function (Blueprint $table) {
            $table->string('status', 50)->default('pending');
        });
        
        // Restore data dari backup jika ada
        if (Schema::hasTable('pengajuan_keuangans_status_backup')) {
            DB::statement('UPDATE pengajuan_keuangans pk 
                          JOIN pengajuan_keuangans_status_backup pb ON pk.id = pb.id 
                          SET pk.status = pb.status');
            
            // Hapus tabel backup
            Schema::dropIfExists('pengajuan_keuangans_status_backup');
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Backup data terlebih dahulu
        DB::statement('CREATE TABLE IF NOT EXISTS pengajuan_keuangans_status_backup AS SELECT id, status FROM pengajuan_keuangans');
        
        // Hapus kolom status
        Schema::table('pengajuan_keuangans', function (Blueprint $table) {
            $table->dropColumn('status');
        });
        
        // Tambah kolom status dengan ENUM
        Schema::table('pengajuan_keuangans', function (Blueprint $table) {
            $table->enum('status', [
                'pending',
                'ke_manajer',
                'ke_direktur',
                'disetujui',
                'selesai',
                'ditolak'
            ])->default('pending');
        });
        
        // Restore data
        if (Schema::hasTable('pengajuan_keuangans_status_backup')) {
            DB::statement('UPDATE pengajuan_keuangans pk 
                          JOIN pengajuan_keuangans_status_backup pb ON pk.id = pb.id 
                          SET pk.status = pb.status 
                          WHERE pb.status IN ("pending", "ke_manajer", "ke_direktur", "disetujui", "selesai", "ditolak")');
            
            Schema::dropIfExists('pengajuan_keuangans_status_backup');
        }
    }
}