<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('shop_customers', function (Blueprint $t) {
            $t->id();
            $t->foreignId('company_id')->constrained()->cascadeOnDelete();
            $t->foreignId('client_id')->nullable()->constrained()->nullOnDelete();
            $t->string('name', 160);
            $t->string('phone', 40);
            $t->string('email', 160)->nullable();
            $t->string('password');
            $t->dateTime('last_login_at')->nullable();
            $t->rememberToken();
            $t->timestamps();
            $t->softDeletes();

            $t->unique(['company_id', 'phone'], 'shop_customers_company_phone_unique');
            $t->index(['company_id', 'email']);
        });

        Schema::table('online_orders', function (Blueprint $t) {
            $t->foreignId('shop_customer_id')->nullable()->after('client_id')
                ->constrained()->nullOnDelete();
            $t->index(['company_id', 'shop_customer_id']);
        });
    }

    public function down(): void
    {
        Schema::table('online_orders', function (Blueprint $t) {
            $t->dropForeign(['shop_customer_id']);
            $t->dropColumn('shop_customer_id');
        });
        Schema::dropIfExists('shop_customers');
    }
};
