<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('treatment_plans', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('tenant_id')->constrained()->restrictOnDelete();
            $table->foreignId('patient_id')->constrained()->restrictOnDelete();
            $table->foreignId('dentist_id')->constrained()->restrictOnDelete();
            $table->string('title', 190);
            $table->string('status', 20)->default('draft'); // draft|proposed|accepted|in_progress|completed|cancelled
            $table->unsignedBigInteger('discount_amount')->default(0); // whole IQD
            $table->text('notes')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('completed_at')->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->index(['tenant_id', 'patient_id', 'status']);
        });

        Schema::create('treatment_plan_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->restrictOnDelete();
            $table->foreignId('treatment_plan_id')->constrained()->cascadeOnDelete();
            $table->foreignId('procedure_id')->constrained()->restrictOnDelete();
            $table->unsignedTinyInteger('tooth')->nullable(); // FDI 11–48
            $table->json('surfaces')->nullable();             // ["M","O"]
            $table->unsignedBigInteger('price');              // whole IQD
            $table->string('status', 20)->default('pending'); // pending|scheduled|completed|cancelled
            $table->foreignId('appointment_id')->nullable()->constrained()->nullOnDelete();
            $table->timestamp('completed_at')->nullable();
            $table->string('note', 190)->nullable();
            $table->timestamps();
            $table->index(['tenant_id', 'treatment_plan_id', 'status']);
        });
    }

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