<?php

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

class UpdateVcAppointmentsForNewFeatures extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('vc_appointments')) return;

        Schema::table('vc_appointments', function (Blueprint $table) {
            // Clinic location
            if (!Schema::hasColumn('vc_appointments', 'location_id')) {
                $table->unsignedInteger('location_id')->nullable()->after('business_id');
                $table->foreign('location_id')->references('id')->on('vc_clinic_locations')->onDelete('set null');
            }
            // Multi-type JSON (new field; old enum `type` kept for backward compat)
            if (!Schema::hasColumn('vc_appointments', 'type_ids')) {
                $table->json('type_ids')->nullable()->after('type');
            }
            // Multi-reason JSON (new field; old `reason` string kept for backward compat)
            if (!Schema::hasColumn('vc_appointments', 'reason_ids')) {
                $table->json('reason_ids')->nullable()->after('reason');
            }
            // Slot reference
            if (!Schema::hasColumn('vc_appointments', 'schedule_id')) {
                $table->unsignedInteger('schedule_id')->nullable()->after('department_id');
                $table->foreign('schedule_id')->references('id')->on('vc_doctor_schedules')->onDelete('set null');
            }
            // Overlap flag (set by system when overlap is detected)
            if (!Schema::hasColumn('vc_appointments', 'has_overlap')) {
                $table->boolean('has_overlap')->default(false)->after('status');
            }
        });
    }

    public function down()
    {
        if (!Schema::hasTable('vc_appointments')) return;

        Schema::table('vc_appointments', function (Blueprint $table) {
            foreach (['location_id', 'type_ids', 'reason_ids', 'schedule_id', 'has_overlap'] as $col) {
                if (Schema::hasColumn('vc_appointments', $col)) {
                    if (in_array($col, ['location_id', 'schedule_id'])) {
                        $table->dropForeign([$col]);
                    }
                    $table->dropColumn($col);
                }
            }
        });
    }
}
