<?php

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

/**
 * Adds to vc_appointments:
 *   - exam_results (JSON) — structured per-exam status for lab + physical exam selections:
 *       [{ key, label, kind, status, result_text, document_id, reason_id, reason_note, product_id, price }]
 *   - next_visit_date / next_visit_time / next_visit_doctor_id / next_visit_department_id
 *   - next_visit_reason / next_visit_notes
 *   - next_appointment_id — FK back to vc_appointments once auto-scheduled
 */
class AddExamResultsAndNextVisitToVcAppointments extends Migration
{
    public function up()
    {
        Schema::table('vc_appointments', function (Blueprint $table) {
            if (!Schema::hasColumn('vc_appointments', 'exam_results')) {
                $table->json('exam_results')->nullable()->after('soap_exam_investigations');
            }
            if (!Schema::hasColumn('vc_appointments', 'next_visit_date')) {
                $table->date('next_visit_date')->nullable()->after('exam_results');
            }
            if (!Schema::hasColumn('vc_appointments', 'next_visit_time')) {
                $table->time('next_visit_time')->nullable()->after('next_visit_date');
            }
            if (!Schema::hasColumn('vc_appointments', 'next_visit_doctor_id')) {
                $table->unsignedInteger('next_visit_doctor_id')->nullable()->after('next_visit_time')->index();
            }
            if (!Schema::hasColumn('vc_appointments', 'next_visit_department_id')) {
                $table->unsignedInteger('next_visit_department_id')->nullable()->after('next_visit_doctor_id')->index();
            }
            if (!Schema::hasColumn('vc_appointments', 'next_visit_reason')) {
                $table->string('next_visit_reason', 255)->nullable()->after('next_visit_department_id');
            }
            if (!Schema::hasColumn('vc_appointments', 'next_visit_notes')) {
                $table->text('next_visit_notes')->nullable()->after('next_visit_reason');
            }
            if (!Schema::hasColumn('vc_appointments', 'next_appointment_id')) {
                $table->unsignedInteger('next_appointment_id')->nullable()->after('next_visit_notes')->index();
            }
        });
    }

    public function down()
    {
        Schema::table('vc_appointments', function (Blueprint $table) {
            foreach ([
                'exam_results', 'next_visit_date', 'next_visit_time',
                'next_visit_doctor_id', 'next_visit_department_id',
                'next_visit_reason', 'next_visit_notes', 'next_appointment_id'
            ] as $col) {
                if (Schema::hasColumn('vc_appointments', $col)) $table->dropColumn($col);
            }
        });
    }
}
