<?php

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

/**
 * P5-T2 dental deep-dive — recall system. ClinicCore's clc_reminder_settings is
 * a vaccine-specific mechanism (no generic type enum), so — per the task — we do
 * NOT extend it. Instead dental owns its own recall table (cleaning, perio
 * maintenance, …). A daily console command (dental:send-recalls) fires the
 * MedNotify 'dental.recall_due' event for rows whose due_date has arrived.
 */
class CreateDentalRecallsTable extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_patients')) {
            return; // requires ClinicCore
        }

        if (! Schema::hasTable('dental_recalls')) {
            Schema::create('dental_recalls', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id');
                $table->unsignedInteger('patient_id');            // clc_patients.id
                $table->date('due_date');
                $table->unsignedSmallInteger('interval_months')->nullable(); // recurrence hint
                $table->string('reason', 100)->nullable();        // e.g. cleaning, perio maintenance
                $table->enum('status', ['due', 'scheduled', 'done', 'cancelled'])->default('due');
                $table->text('notes')->nullable();
                $table->timestamp('notified_at')->nullable();     // last recall notification sent
                $table->timestamps();

                $table->index(['business_id', 'status', 'due_date'], 'dental_recall_biz_status_due_idx');
                $table->foreign('patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            });
        }
    }

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