<?php

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

/**
 * Controlled-drug register — Phase 1.
 *  - clc_medicines.controlled_schedule : per-medicine classification (narcotic,
 *    schedule_1, schedule_2, psychotropic, controlled_other). NULL = not controlled.
 *  - clc_controlled_stock_movements    : insert-only log of every IN / OUT for any
 *    controlled medicine, with a running balance per (medicine, batch_no).
 *  - Two new permissions:
 *      clinic.manage_controlled  — set the schedule on medicines, view register
 *      clinic.log_controlled     — record stock movements (dispense / receive / waste)
 */
class ClcCreateControlledDrugRegister extends Migration
{
    public function up()
    {
        if (!Schema::hasColumn('clc_medicines', 'controlled_schedule')) {
            Schema::table('clc_medicines', function (Blueprint $table) {
                $table->string('controlled_schedule', 30)->nullable()->after('status')->index();
            });
        }

        if (!Schema::hasTable('clc_controlled_stock_movements')) {
            Schema::create('clc_controlled_stock_movements', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->index();
                $table->string('serial_no', 30)->unique();              // CR-{biz}-{0000001}
                $table->unsignedInteger('medicine_id')->index();
                $table->enum('direction', ['in', 'out', 'adjust']);     // IN raises stock, OUT lowers
                $table->decimal('qty', 12, 3);                          // always positive; direction conveys sign
                $table->string('unit', 30)->nullable();
                $table->string('batch_no', 60)->nullable()->index();
                $table->date('expiry_date')->nullable();
                $table->decimal('balance_after', 14, 3)->default(0);    // running balance per (medicine, batch)
                $table->string('reason_code', 30)->index();             // dispense | receive | return | wastage | expiry | transfer_in | transfer_out | adjust | correction
                $table->unsignedInteger('patient_id')->nullable()->index();
                $table->unsignedInteger('contact_id')->nullable()->index();
                $table->unsignedInteger('appointment_id')->nullable()->index();
                $table->unsignedInteger('prescription_id')->nullable()->index();
                $table->unsignedInteger('doctor_id')->nullable();       // issuing vet
                $table->unsignedInteger('witness_user_id')->nullable(); // in-clinic witness
                $table->text('notes')->nullable();
                $table->unsignedInteger('created_by')->nullable();
                $table->timestamps();
            });
        }

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

    public function down()
    {
        Schema::dropIfExists('clc_controlled_stock_movements');
        if (Schema::hasColumn('clc_medicines', 'controlled_schedule')) {
            Schema::table('clc_medicines', function (Blueprint $table) {
                $table->dropColumn('controlled_schedule');
            });
        }
        Permission::whereIn('name', ['clinic.manage_controlled', 'clinic.log_controlled'])->delete();
    }
}
