<?php

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

class ChangeEntryBlocksRelation extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('block_entry', function (Blueprint $table) {
            DB::statement('ALTER TABLE block_entry CHARACTER SET utf8 COLLATE utf8_general_ci');
            $table->dropForeign(['entry_id']);
            $table->dropForeign(['block_id']);
            $table->dropPrimary();
            $table->string('language_id', 10)->default('en');

            $table->primary(['entry_id', 'block_id', 'language_id'], 'PK_entry_blocks');
            $table->foreign('entry_id')
              ->references('id')->on('entries')
              ->onDelete('CASCADE')->onUpdate('CASCADE');
            $table->foreign('block_id')
              ->references('id')->on('blocks')
              ->onDelete('CASCADE')->onUpdate('CASCADE');
            $table->foreign('language_id')
              ->references('id')->on('languages')
              ->onDelete('CASCADE')->onUpdate('CASCADE');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('block_entry', function (Blueprint $table) {
          $table->dropForeign(['entry_id']);
          $table->dropForeign(['block_id']);
          $table->dropForeign(['language_id']);
          $table->dropPrimary();
          $table->dropColumn('language_id');

          $table->primary(['entry_id', 'block_id']);
          $table->foreign('entry_id')
            ->references('id')->on('entries')
            ->onDelete('CASCADE')->onUpdate('CASCADE');
          $table->foreign('block_id')
            ->references('id')->on('blocks')
            ->onDelete('CASCADE')->onUpdate('CASCADE');
        });
    }
}
