<?php

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

/**
 * Reference normal ranges for vitals, keyed by species + life stage.
 * business_id NULL = system default available to every clinic, populated
 * with canine + feline baselines so VetAdmission's alert engine has
 * something to compare against on day one.
 */
class CreateClcVitalRangesTable extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_vital_ranges')) {
            Schema::create('clc_vital_ranges', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->nullable()->index();
                $table->string('species', 40)->index();
                $table->enum('life_stage', ['pediatric', 'adult', 'senior', 'all'])->default('all');

                $table->decimal('temperature_low',  5, 2)->nullable();
                $table->decimal('temperature_high', 5, 2)->nullable();
                $table->unsignedSmallInteger('heart_rate_low')->nullable();
                $table->unsignedSmallInteger('heart_rate_high')->nullable();
                $table->unsignedSmallInteger('respiratory_rate_low')->nullable();
                $table->unsignedSmallInteger('respiratory_rate_high')->nullable();
                $table->decimal('weight_low_kg',  6, 2)->nullable();
                $table->decimal('weight_high_kg', 6, 2)->nullable();

                $table->timestamps();
            });
        }

        $now = now();
        $defaults = [
            // species, life_stage, t_low, t_high, hr_low, hr_high, rr_low, rr_high
            ['canine', 'all',       38.3, 39.2, 60, 140, 10, 30],
            ['canine', 'pediatric', 38.5, 39.5, 80, 220, 15, 35],
            ['feline', 'all',       38.0, 39.2, 140, 220, 16, 40],
            ['feline', 'pediatric', 38.0, 39.5, 200, 260, 20, 45],
        ];
        foreach ($defaults as $d) {
            $exists = DB::table('clc_vital_ranges')
                ->whereNull('business_id')
                ->where('species', $d[0])->where('life_stage', $d[1])
                ->exists();
            if ($exists) continue;
            DB::table('clc_vital_ranges')->insert([
                'business_id'           => null,
                'species'               => $d[0],
                'life_stage'            => $d[1],
                'temperature_low'       => $d[2],
                'temperature_high'      => $d[3],
                'heart_rate_low'        => $d[4],
                'heart_rate_high'       => $d[5],
                'respiratory_rate_low'  => $d[6],
                'respiratory_rate_high' => $d[7],
                'created_at'            => $now,
                'updated_at'            => $now,
            ]);
        }
    }

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