<?php

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

/**
 * SIFA P3-T1 — the patient's insurance card info (spec §7 patient >
 * administrative > insurance). This stores only the card details captured at
 * registration. The full payer master + claims + pre-auth workflow are Phase 4
 * (billing module) — NOT this table. Scanned cards attach via MedDocuments when
 * that module is installed.
 */
class CreateClcPatientInsurancesTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_patient_insurances')) {
            return;
        }

        Schema::create('clc_patient_insurances', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('patient_id');
            $table->string('provider_name');
            $table->string('policy_number')->nullable();
            $table->string('group_number')->nullable();
            $table->string('plan_type')->nullable();
            $table->date('effective_date')->nullable();
            $table->date('expiry_date')->nullable();
            $table->decimal('copay_amount', 12, 2)->nullable();
            $table->boolean('pre_auth_required')->default(false);
            $table->enum('status', ['active', 'expired', 'cancelled'])->default('active');
            $table->text('notes')->nullable();
            $table->unsignedInteger('created_by')->nullable();  // users.id
            $table->timestamps();

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

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