<?php

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

class Zones extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
		Schema::create('zones', function (Blueprint $table) {
			$table->id();
			$table->timestamps();

			$table->integer('zone_id');
			$table->boolean('active');
			$table->string('notes')->nullable();

			$table->bigInteger('domain_id');
			$table->foreign('domain_id')->references('id')->on('domains');

			$table->unique(['zone_id','domain_id']);

			$table->bigInteger('system_id');
			$table->foreign('system_id')->references('id')->on('systems');

			$table->string('zt_id',16)->unique()->nullable();

			$table->ipAddress('zt_ipv4')->nullable();
			$table->integer('zt_ipv4_mask')->nullable();
			$table->unique(['zt_ipv4','zt_ipv4_mask']);

			$table->ipAddress('zt_ipv6')->nullable();
			$table->integer('zt_ipv6_mask')->nullable();
			$table->unique(['zt_ipv6','zt_ipv6_mask']);

			$table->boolean('default')->default(FALSE);
		});

		DB::statement('CREATE UNIQUE INDEX default_zones ON zones (zone_id) WHERE "default" = true');

		Schema::create('system_zone', function (Blueprint $table) {
			$table->string('sespass')->nullable();
			$table->string('pktpass',8)->nullable();
			$table->string('ticpass')->nullable();
			$table->string('fixpass')->nullable();

			$table->ipAddress('zt_ipv4')->nullable();
			$table->ipAddress('zt_ipv6')->nullable();

			$table->bigInteger('system_id');
			$table->foreign('system_id')->references('id')->on('systems');

			$table->bigInteger('zone_id');
			$table->foreign('zone_id')->references('id')->on('zones');

			$table->unique(['system_id','zone_id']);

			$table->boolean('default')->nullable();
		});

		DB::statement('CREATE UNIQUE INDEX default_zone ON system_zone (zone_id) WHERE "default" = true');

	}

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