<?php

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

class CreateClcVaccinationsTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_vaccinations')) return;

        Schema::create('clc_vaccinations', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('patient_id');
            $table->unsignedInteger('contact_id');
            $table->unsignedInteger('vaccine_type_id');
            $table->unsignedInteger('appointment_id')->nullable();
            $table->unsignedInteger('medicine_id')->nullable();
            $table->string('batch_no', 50)->nullable();
            $table->date('administered_date');
            $table->date('next_due_date')->nullable();
            $table->unsignedInteger('administered_by')->nullable();
            $table->decimal('weight_at_time', 8, 2)->nullable();
            $table->decimal('temperature_at_time', 5, 2)->nullable();
            $table->enum('status', ['scheduled', 'administered', 'overdue', 'cancelled'])->default('administered');
            $table->boolean('reminder_sent')->default(false);
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $table->foreign('patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade');
            $table->foreign('vaccine_type_id')->references('id')->on('clc_vaccine_types')->onDelete('restrict');
            $table->foreign('appointment_id')->references('id')->on('clc_appointments')->onDelete('set null');
            $table->index(['business_id', 'patient_id']);
            $table->index(['business_id', 'next_due_date']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('clc_vaccinations');
    }
}
