<?php

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

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

            $table->primary(['blog_post_id', 'block_id', 'language_id']);
            $table->foreign('blog_post_id')
              ->references('id')->on('blog_posts')
              ->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('blog_post_blocks', function (Blueprint $table) {
            $table->dropForeign(['blog_post_id']);
            $table->dropForeign(['block_id']);
            $table->dropForeign(['language_id']);
            $table->dropPrimary();
            $table->dropColumn('language_id');

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