<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // Add company_id as a foreign key referencing the companies table
            $table->unsignedBigInteger('company_id')->nullable()->after('user_pin');
            $table->foreign('company_id')->references('id')->on('company')->onDelete('cascade');

            // Add branch_id as a foreign key referencing the branches table
            $table->unsignedBigInteger('branch_id')->nullable()->after('company_id');
            $table->foreign('branch_id')->references('id')->on('company_branch')->onDelete('cascade');

            // Add roles column with a default value of 'user'
            $table->string('roles')->default('user')->after('branch_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // Drop the roles column
            $table->dropColumn('roles');

            // Drop the branch_id column and its foreign key
            $table->dropForeign(['branch_id']);
            $table->dropColumn('branch_id');

            // Drop the company_id column and its foreign key
            $table->dropForeign(['company_id']);
            $table->dropColumn('company_id');
        });
    }
};
