<?php

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

class CreateCountriesStructure extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        if (!Schema::hasTable('countries')) {
            Schema::create('countries', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedBigInteger('backend_user_id')->nullable();

                $table->string('code', 10);
                $table->boolean('main_country')->default(0);
                $table->nullableTimestamps();

                $table->foreign('backend_user_id')->references('id')
                    ->on('backend_users')->onDelete('SET NULL')->onUpdate('CASCADE');
                $table->unique('code');
            });
        }

        if (!Schema::hasTable('country_languages')) {
            Schema::create('country_languages', function (Blueprint $table) {
                $table->bigIncrements('translation_id');
                $table->unsignedBigInteger('country_id');
                $table->string('language_id', 10);
                $table->string('title', 150);

                $table->unique(['country_id', 'language_id'], 'idx_country_lang');
                $table->foreign('country_id')
                    ->references('id')
                    ->on('countries')
                    ->onDelete('CASCADE')
                    ->onUpdate('CASCADE');
            });
        }


        if (!Schema::hasColumn('cities', 'country_id')) {
            Schema::table('cities', function (Blueprint $table) {
                $table->unsignedBigInteger('country_id')->nullable();

                $table->foreign('country_id')
                    ->references('id')
                    ->on('countries')
                    ->onDelete('restrict');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::disableForeignKeyConstraints();
        if (Schema::hasColumn('cities', 'country_id')) {
            Schema::table('cities', function (Blueprint $table) {
                $table->dropColumn('country_id');
            });
        }
        Schema::dropIfExists('country_languages');
        Schema::dropIfExists('countries');
        Schema::enableForeignKeyConstraints();
    }
}
