<?php

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

/**
 * Class CreateEntitiesTable
 */
class CreateEntitiesTable extends Migration
{
    protected $tableName = 'entities';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create($this->tableName, function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('parent_entity_id')->nullable();
            $table->unsignedInteger('entity_type_id')->nullable();
            $table->unsignedInteger('entity_class_id');
            $table->unsignedInteger('location_id')->nullable();
            $table->unsignedInteger('manufacturer_id')->nullable();
            $table->unsignedInteger('supplier_id')->nullable();
            $table->unsignedInteger('state_id')->default(1);
            $table->timestamps();

            // Self relation with parent entity (e.g. motherboard has server)
            $table->foreign('parent_entity_id')
                ->references('id')->on($this->tableName)
                ->onDelete('set null')->onUpdate('cascade');

            // Self relation with entity type (e.g. motherboard has motherboard_type)
            $table->foreign('entity_type_id')
                ->references('id')->on($this->tableName)
                ->onDelete('cascade')->onUpdate('cascade');

            // Relation to a states table
            $table->foreign('state_id')
                ->references('id')->on('states')
                ->onUpdate('cascade')->onDelete('restrict');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists($this->tableName);
    }
}
