<?php

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

/**
 * Scope exam sheets to a clinical specialty. A null specialty_id means the
 * sheet is general (offered for any specialty); a set specialty_id means the
 * sheet is offered only when the appointment is booked under that specialty.
 * Specialty plugins seed their own sheets tagged with their specialty_id.
 */
class AddSpecialtyIdToClcExamTemplates extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_exam_templates') && ! Schema::hasColumn('clc_exam_templates', 'specialty_id')) {
            Schema::table('clc_exam_templates', function (Blueprint $table) {
                $table->unsignedInteger('specialty_id')->nullable()->after('business_id')->index();
                $table->foreign('specialty_id')->references('id')->on('clc_specialties')->nullOnDelete();
            });
        }
    }

    public function down()
    {
        if (Schema::hasColumn('clc_exam_templates', 'specialty_id')) {
            Schema::table('clc_exam_templates', function (Blueprint $table) {
                $table->dropForeign(['specialty_id']);
                $table->dropColumn('specialty_id');
            });
        }
    }
}
