<?php

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

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

        Schema::create('vc_appointments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('contact_id');
            $table->unsignedInteger('pet_id');
            $table->unsignedInteger('doctor_id')->nullable();
            $table->unsignedInteger('department_id')->nullable();
            $table->string('ref_no', 30)->unique();
            $table->date('appointment_date');
            $table->time('appointment_time');
            $table->unsignedSmallInteger('duration_minutes')->default(30);
            $table->string('reason', 255)->nullable();
            $table->enum('type', ['checkup', 'vaccination', 'surgery', 'grooming', 'emergency', 'other'])->default('checkup');
            $table->enum('status', ['pending', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show'])->default('pending');
            $table->text('notes')->nullable();
            $table->text('doctor_notes')->nullable();
            $table->unsignedInteger('erp_sell_id')->nullable();
            $table->timestamps();

            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $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->foreign('department_id')->references('id')->on('vc_departments')->onDelete('set null');
            $table->index(['business_id', 'appointment_date']);
            $table->index(['business_id', 'status']);
        });
    }

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