<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;

class AddCompanyAndBranchId extends Command
{
    protected $signature   = 'db:add-company-and-branch-id';
    protected $description = 'Add company_id and branch_id columns to specific tables if not already present';

    public function handle()
    {
        $tables = ['complains', 'verbal_warnings', 'performances', 'tardy_notifications', 'tardy_records', 'tardy_requests', 'tardy_rule_assigns', 'deductions'];

        foreach ($tables as $tableName) {
            // Check if the table exists
            if (!Schema::hasTable($tableName)) {
                $this->warn("Skipped table: $tableName (does not exist)");
                continue;
            }

            // Get existing columns in the table
            $columns = Schema::getColumnListing($tableName);
            $missingColumns = [];

            if (!in_array('company_id', $columns)) {
                $missingColumns[] = 'company_id';
            }
            if (!in_array('branch_id', $columns)) {
                $missingColumns[] = 'branch_id';
            }

            // Add only missing columns
            if (!empty($missingColumns)) {
                Schema::table($tableName, function (Blueprint $table) use ($missingColumns) {
                    if (in_array('company_id', $missingColumns)) {
                        $table->unsignedBigInteger('company_id')->default(1)->before('created_at');
                    }

                    if (in_array('branch_id', $missingColumns)) {
                        $table->unsignedBigInteger('branch_id')->default(1)->after('company_id');
                    }
                });

                $this->info("Added columns [" . implode(', ', $missingColumns) . "] to table: $tableName");
            } else {
                $this->info("Skipped table: $tableName (columns already exist)");
            }
        }
    }
}
