<?php

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

use App\Models\GoogleCalendar;
use App\Models\ContentElement;

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

        $calendar_ids = DB::table('google_calendars')->get()->pluck('calendar_id', 'id')->toArray();

        Schema::rename('google_calendars', 'calendars');

        Schema::table('calendars', function (Blueprint $table) {
            $table->dropColumn('calendar_id');
        });

        Schema::create('google_calendars', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('calendar_id');
            $table->string('name')->nullable();
            $table->string('google_id')->nullable();
            $table->timestamps();
        });

        foreach($calendar_ids as $calendar_id => $google_id) {
            $google_calendar = new GoogleCalendar;
            $google_calendar->calendar_id = $calendar_id;
            $google_calendar->name = 'Google Calendar';
            $google_calendar->google_id = $google_id;
            $google_calendar->save();
        }

        $content_elements = ContentElement::where('content_type', 'App\\Models\\GoogleCalendar')->get();

        foreach ($content_elements as $content_element) {
            $content_element->content_type = 'App\\Models\\Calendar';
            $content_element->save();
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('calendars');
    }
}
