<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('patients', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->restrictOnDelete();
            $table->string('full_name', 190);
            $table->string('phone', 32);
            $table->string('phone_normalized', 32);
            $table->string('email', 190)->nullable();
            $table->enum('gender', ['male', 'female'])->nullable();
            $table->date('dob')->nullable();
            $table->string('address')->nullable();
            $table->text('allergies')->nullable();
            $table->text('medical_history')->nullable();
            $table->text('notes')->nullable();
            $table->enum('source', ['walk_in', 'online', 'whatsapp', 'referral'])->default('walk_in');
            $table->unsignedInteger('total_visits')->default(0);
            $table->unsignedBigInteger('total_paid')->default(0);
            $table->unsignedBigInteger('outstanding_balance')->default(0);
            $table->timestamp('last_visit_at')->nullable();
            $table->boolean('whatsapp_opt_in')->default(true);
            $table->timestamps();
            $table->softDeletes();
            $table->index(['tenant_id', 'phone_normalized']);
        });

        if (DB::getDriverName() === 'mysql') {
            DB::statement('ALTER TABLE patients ADD FULLTEXT patients_full_name_fulltext (full_name)');
        }
    }

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