<?php

use Illuminate\Database\Migrations\Migration;
use App\Libs\Facades\Localization;

class PopulateBlocksRelationsLanguages extends Migration
{
    const BLOCKS_RELATION_TABLES = [
        'block_entry' => 'entry_id',
        'project_blocks' => 'project_id',
        'solution_blocks' => 'solution_id',
        'blog_post_blocks' => 'blog_post_id',
        'case_study_blocks' => 'case_study_id',
        'event_item_blocks' => 'event_item_id',
        'news_blocks' => 'news_id',
        'publication_blocks' => 'publication_id',
        'sector_blocks' => 'sector_id'
    ];

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $languages = Localization::getAllLanguages();
        $defaultLang = Localization::getDefaultLocale();

        foreach ($this::BLOCKS_RELATION_TABLES as $table => $fk) {
            foreach ($languages as $lang) {
                if ($lang->id != $defaultLang) {
                    DB::statement("INSERT INTO `$table` (`$fk`, `block_id`, `language_id`, `position`) SELECT `$fk`, `block_id`, '$lang->id' as `language_id`, `position` FROM `$table` WHERE `language_id` = '$defaultLang'");
                }
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $defaultLang = Localization::getDefaultLocale();

        foreach ($this::BLOCKS_RELATION_TABLES as $table => $fk) {
            DB::statement("DELETE FROM `$table` WHERE `language_id` != '$defaultLang'");
        }
    }
}
