<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

/**
 * Polymorphic notes attached to an owner or a pet. Each note carries a
 * visibility flag — "normal" is visible to anyone who can view the subject,
 * "confidential" is hidden from anyone without vet_clinic.view_confidential_notes.
 */
class CreateVcConfidentialNotesTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('vc_confidential_notes')) {
            Schema::create('vc_confidential_notes', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->string('subject_type', 20);            // 'owner' | 'pet'
                $table->unsignedBigInteger('subject_id');
                $table->enum('visibility', ['normal', 'confidential'])->default('normal')->index();
                $table->string('title', 191)->nullable();
                $table->text('body');
                $table->unsignedInteger('created_by')->nullable();
                $table->unsignedInteger('updated_by')->nullable();
                $table->timestamps();
                $table->index(['subject_type', 'subject_id']);
            });
        }

        foreach ([
            'vet_clinic.view_confidential_notes',   // see notes marked confidential
            'vet_clinic.manage_subject_notes',      // write / edit / delete any note (normal or confidential)
        ] as $perm) {
            Permission::findOrCreate($perm, 'web');
        }
    }

    public function down()
    {
        Schema::dropIfExists('vc_confidential_notes');
        Permission::whereIn('name', [
            'vet_clinic.view_confidential_notes',
            'vet_clinic.manage_subject_notes',
        ])->delete();
    }
}
