<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('reseps', function (Blueprint $table) {
            // Data Resep
            $table->string('nama_dokter')->nullable()->after('user_id');
            $table->string('no_sip')->nullable()->after('nama_dokter');
            $table->enum('jenis_penjamin', ['umum', 'BPJS Kes', 'BPJS Naker', 'Jamkesmas/KIS', 'R. Inap'])->default('umum')->after('no_resep');
            $table->enum('jenis_layanan', ['BP', 'KIA', 'Gigi', 'UGD', 'Lainnya'])->default('BP')->after('jenis_penjamin');
            
            // Data Pasien
            $table->string('no_rm')->nullable()->after('nama_pasien');
            $table->enum('jenis_kelamin', ['L', 'P'])->nullable()->after('alamat_pasien');
            $table->decimal('berat_badan', 5, 2)->nullable()->after('umur_pasien');
            
            // Notification
            $table->boolean('is_read')->default(false)->after('status');
        });

        // Update existing status values and change enum
        // First update any 'draft' to 'proses', then modify enum
        DB::statement("UPDATE reseps SET status = 'proses' WHERE status = 'draft'");
        
        // Change enum values
        DB::statement("ALTER TABLE reseps MODIFY COLUMN status ENUM('proses', 'selesai', 'dibatalkan') DEFAULT 'proses'");
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Revert status enum
        DB::statement("ALTER TABLE reseps MODIFY COLUMN status ENUM('draft', 'selesai', 'dibatalkan') DEFAULT 'selesai'");
        DB::statement("UPDATE reseps SET status = 'draft' WHERE status = 'proses'");

        Schema::table('reseps', function (Blueprint $table) {
            $table->dropColumn([
                'nama_dokter',
                'no_sip',
                'jenis_penjamin',
                'jenis_layanan',
                'no_rm',
                'jenis_kelamin',
                'berat_badan',
                'is_read',
            ]);
        });
    }
};
