<?php

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

/**
 * Class CreateStatesTable
 */
class CreateStatesTable extends Migration
{
    private $tableName = 'states';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create($this->tableName, function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
        });

        Schema::create('state_transitions', function (Blueprint $table) {
            $table->unsignedInteger('from_state_id');
            $table->unsignedInteger('to_state_id');
            $table->unsignedInteger('permission_id');

            $table->foreign('from_state_id')
                ->references('id')->on($this->tableName)
                ->onDelete('cascade')->onUpdate('cascade');

            $table->foreign('to_state_id')
                ->references('id')->on($this->tableName)
                ->onDelete('cascade')->onUpdate('cascade');

            $table->foreign('permission_id')
                ->references('id')->on('permissions')
                ->onDelete('cascade')->onUpdate('cascade');
        });

        DB::transaction(function () {
            $table = DB::table($this->tableName);

            foreach (\App\State::VALID_STATES as $state)
                $table->insert([
                    'name' => $state
                ]);
        });
    }

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

    }
}
