<?php

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

/**
 * Link LabCore orders/results to the shared ClinicCore patient, mirroring the
 * existing vc_pet_id linkage. Nullable + additive — VetClinic and config-only
 * lab flows are unaffected.
 */
class AddClinicLinkageToLabTables extends Migration
{
    public function up()
    {
        foreach (['lab_worklist', 'lab_test_sessions'] as $tbl) {
            if (! Schema::hasTable($tbl)) continue;
            Schema::table($tbl, function (Blueprint $table) use ($tbl) {
                if (! Schema::hasColumn($tbl, 'clc_patient_id')) {
                    $table->unsignedInteger('clc_patient_id')->nullable()->index();
                }
                if (! Schema::hasColumn($tbl, 'clc_appointment_id')) {
                    $table->unsignedInteger('clc_appointment_id')->nullable()->index();
                }
            });
        }
    }

    public function down()
    {
        foreach (['lab_worklist', 'lab_test_sessions'] as $tbl) {
            if (! Schema::hasTable($tbl)) continue;
            Schema::table($tbl, function (Blueprint $table) use ($tbl) {
                foreach (['clc_patient_id', 'clc_appointment_id'] as $col) {
                    if (Schema::hasColumn($tbl, $col)) $table->dropColumn($col);
                }
            });
        }
    }
}
