<?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()
    {
        Schema::create('suppliers', function (Blueprint $table)
		{
			$table->id();
			$table->timestamps();
			$table->boolean('active')->default(false);

			$table->string('name')->unique();
			$table->string('address1')->nullable();
			$table->string('address2')->nullable();
			$table->string('city')->nullable();
			$table->string('state')->nullable();
			$table->string('postcode',16)->nullable();

			$table->date('usage_last')->nullable();
        });

		Schema::create('supplier_details', function (Blueprint $table)
		{
			$table->id();
			$table->timestamps();

			$table->text('notes')->nullable();
			$table->string('accounts')->nullable();
			$table->string('support')->nullable();
			$table->string('payments')->nullable();
			$table->jsonb('connections')->nullable();

			$table->integer('site_id')->unsigned();
			$table->foreign('site_id')->references('id')->on('sites');

			$table->integer('supplier_id')->unsigned();
			$table->foreign('supplier_id')->references('id')->on('suppliers');

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

		Schema::create('supplier_user', function (Blueprint $table)
		{
			$table->id();
			$table->timestamps();
			$table->integer('site_id')->unsigned();
			$table->boolean('active')->default(false);

			$table->integer('supplier_id')->unsigned();
			$table->foreign(['supplier_id'])->references(['id'])->on('suppliers');

			$table->integer('user_id')->unsigned();
			$table->foreign(['user_id','site_id'])->references(['id','site_id'])->on('users');

			$table->unique(['id','site_id']);
			$table->unique(['id','supplier_id']);
			$table->unique(['supplier_id','user_id']);
		});
    }

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