<?php

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

class AddServiceGeneric extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
		Schema::create('service__generic', function (Blueprint $table) {
			$table->bigInteger('id',TRUE);
			$table->integer('site_id');
			$table->bigInteger('service_id');
			$table->bigInteger('product_id');

			$table->foreign('site_id')->references('id')->on('ab_setup');
			$table->foreign(['service_id','site_id'])->references(['id','site_id'])->on('ab_service');
			$table->foreign(['product_id','site_id'])->references(['id','site_id'])->on('ab_product');

			$table->unique(['site_id','service_id']);
		});

		foreach (\App\Models\Service::whereNULL('model')->get() as $o) {
			$oo = new \App\Models\Service\Generic;
			$oo->service_id = $o->id;
			$oo->site_id = $o->site_id;
			$oo->product_id = 0;
			$oo->save();

			$o->model = 'App\Models\Service\Generic';
			$o->save();
		}
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
		foreach (\App\Models\Service::where('model','App\Models\Service\Generic')->get() as $o) {
			if ($o->type)
				$o->type->delete();

			$o->model = NULL;
			$o->save();
		}

		Schema::dropIfExists('service__generic');
    }
}