<?php

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

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

        Schema::create('vc_prescriptions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->string('ref_no', 30)->unique();
            $table->unsignedInteger('appointment_id')->nullable();
            $table->unsignedInteger('contact_id');
            $table->unsignedInteger('pet_id');
            $table->unsignedInteger('doctor_id')->nullable();
            $table->date('prescribed_date');
            $table->date('valid_until')->nullable();
            $table->text('diagnosis')->nullable();
            $table->enum('status', ['active', 'completed', 'cancelled'])->default('active');
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $table->foreign('appointment_id')->references('id')->on('vc_appointments')->onDelete('set null');
            $table->foreign('contact_id')->references('id')->on('contacts')->onDelete('cascade');
            $table->foreign('pet_id')->references('id')->on('vc_pets')->onDelete('cascade');
            $table->foreign('doctor_id')->references('id')->on('vc_doctors')->onDelete('set null');
            $table->index(['business_id', 'pet_id']);
        });
    }

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