<?php

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

class ClcMakeScheduleDepartmentNullable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_doctor_schedules') && !$this->isNullable()) {
            // Drop FK constraint first (name may vary, try both conventions)
            foreach (['clc_doctor_schedules_department_id_foreign', 'doctor_schedules_department_id_foreign'] as $fk) {
                try { \DB::statement("ALTER TABLE clc_doctor_schedules DROP FOREIGN KEY `{$fk}`"); } catch (\Exception $e) {}
            }
            // Alter column to nullable via raw SQL (no doctrine/dbal needed)
            \DB::statement("ALTER TABLE clc_doctor_schedules MODIFY `department_id` INT UNSIGNED NULL DEFAULT NULL");
            // Re-add FK with set null on delete
            \DB::statement("ALTER TABLE clc_doctor_schedules ADD CONSTRAINT `clc_doctor_schedules_department_id_foreign`
                FOREIGN KEY (`department_id`) REFERENCES `clc_departments`(`id`) ON DELETE SET NULL");
        }
    }

    public function down()
    {
        // intentionally not reverting — reverting would break existing null rows
    }

    private function isNullable(): bool
    {
        $col = \DB::select("SHOW COLUMNS FROM clc_doctor_schedules WHERE Field = 'department_id'");
        return isset($col[0]) && strtoupper($col[0]->Null) === 'YES';
    }
}
