<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
		DB::statement('RENAME TABLE ab_checkout TO checkouts');
		DB::statement('ALTER TABLE checkouts MODIFY active tinyint(1) NOT NULL,MODIFY fee_passon tinyint(1) DEFAULT NULL');

		Schema::table('checkouts', function (Blueprint $table) {
			$table->datetime('created_at')->nullable()->after('id');
			$table->datetime('updated_at')->nullable()->after('created_at');

			$table->dropForeign('ab_checkout_site_id_foreign');
			$table->dropIndex('ab_checkout_id_site_id_index');

			$table->foreign(['site_id'])->references(['id'])->on('sites');
		});

		Schema::table('payments', function (Blueprint $table) {
			$table->foreign(['checkout_id','site_id'])->references(['id','site_id'])->on('checkouts');
		});

		foreach (\App\Models\Checkout::withoutGlobalScope(\App\Models\Scopes\SiteScope::class)->cursor() as $o) {
			if ($x=$o->getRawOriginal('plugin_data')) {
				Config::set('site',$o->site);

				$o->plugin_data = unserialize($x);
			}

			$o->save();
		}
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        abort(500,'Cant go back');
    }
};