<?php

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

/**
 * VC-P5.2 — diagnostic imaging requests + studies.
 *
 *  clc_imaging_modalities : catalogue (X-Ray, US, CT, MRI, …). business_id
 *                          NULL = system default.
 *  clc_imaging_requests   : worklist row per ordered study.
 *  clc_imaging_studies    : uploaded result media — JPG/PNG previewed inline,
 *                          PDF/DICOM linked out (DICOM viewer integration is
 *                          a follow-up; for now we treat .dcm as a download).
 */
class CreateClcImagingTables extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_imaging_modalities')) {
            Schema::create('clc_imaging_modalities', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->nullable()->index();
                $table->string('code', 10);
                $table->string('name', 80);
                $table->unsignedSmallInteger('sort_order')->default(0);
                $table->enum('status', ['active', 'inactive'])->default('active');
                $table->timestamps();
            });

            $now = now();
            foreach ([
                ['XR', 'X-Ray',   1],
                ['US', 'Ultrasound', 2],
                ['CT', 'CT scan', 3],
                ['MR', 'MRI',     4],
                ['ENDO', 'Endoscopy', 5],
            ] as $d) {
                DB::table('clc_imaging_modalities')->insert([
                    'business_id' => null,
                    'code'        => $d[0],
                    'name'        => $d[1],
                    'sort_order'  => $d[2],
                    'status'      => 'active',
                    'created_at'  => $now,
                    'updated_at'  => $now,
                ]);
            }
        }

        if (!Schema::hasTable('clc_imaging_requests')) {
            Schema::create('clc_imaging_requests', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->string('ref_no', 30)->unique();
                $table->unsignedInteger('patient_id')->index();
                $table->unsignedInteger('contact_id')->nullable();
                $table->unsignedInteger('appointment_id')->nullable()->index();
                $table->unsignedInteger('modality_id');
                $table->string('body_region', 120)->nullable();
                $table->text('indication')->nullable();
                $table->enum('priority', ['routine', 'urgent', 'stat'])->default('routine');
                $table->enum('status', ['requested', 'in_progress', 'reported', 'cancelled'])->default('requested')->index();
                $table->text('report')->nullable();
                $table->unsignedInteger('requested_by')->nullable();
                $table->unsignedInteger('reported_by')->nullable();
                $table->timestamp('requested_at')->nullable();
                $table->timestamp('completed_at')->nullable();
                $table->timestamp('reported_at')->nullable();
                $table->timestamps();
            });
        }

        if (!Schema::hasTable('clc_imaging_studies')) {
            Schema::create('clc_imaging_studies', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('imaging_request_id')->index();
                $table->string('study_uid', 80)->nullable();   // optional DICOM SOP/study UID
                $table->string('file_path', 255);
                $table->string('original_name', 191)->nullable();
                $table->string('file_mime', 100)->nullable();
                $table->unsignedInteger('file_size')->nullable();
                $table->string('thumb_path', 255)->nullable();
                $table->text('notes')->nullable();
                $table->unsignedInteger('uploaded_by')->nullable();
                $table->timestamp('uploaded_at')->nullable();
                $table->timestamps();
            });
        }

        foreach (['clinic.view_imaging', 'clinic.manage_imaging'] as $perm) {
            Permission::findOrCreate($perm, 'web');
        }
    }

    public function down()
    {
        Schema::dropIfExists('clc_imaging_studies');
        Schema::dropIfExists('clc_imaging_requests');
        Schema::dropIfExists('clc_imaging_modalities');
        Permission::whereIn('name', ['clinic.view_imaging', 'clinic.manage_imaging'])->delete();
    }
}
