<?php

use App\Models\Shift;
use App\Scopes\CompanyScope;
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('shifts', function (Blueprint $table) {
            $table->string('short_name')->nullable()->default(null)->after('name');
            $table->string('color',20)->nullable()->default('#1890ff')->after('short_name');
        });

        Schema::create('shift_assignments', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('company_id')->unsigned()->nullable()->default(null);
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade');
            $table->bigInteger('user_id')->unsigned()->nullable()->default(null);
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->bigInteger('shift_id')->unsigned()->nullable()->default(null);
            $table->foreign('shift_id')->references('id')->on('shifts')->onDelete('cascade')->onUpdate('cascade');
            $table->string('name')->nullable()->default(null);
            $table->string('short_name')->nullable()->default(null);
            $table->longText('remark')->nullable()->default(null);
            $table->date('date')->nullable()->default(null);
            $table->time('clock_in_time')->nullable()->default(null);
            $table->time('clock_out_time')->nullable()->default(null);
            $table->integer('late_mark_after')->nullable()->default(null);
            $table->integer('early_clock_in_time')->nullable()->default(null);
            $table->integer('allow_clock_out_till')->nullable()->default(null);
            $table->timestamps();
        });

        $allShifts =  Shift::withoutGlobalScope(CompanyScope::class)->get();
        if ($allShifts) {
            foreach ($allShifts as $shift) {
                $acronym = collect(explode(' ', $shift->name))
                    ->map(fn($word) => strtoupper(substr($word, 0, 1)))
                    ->implode('');

                $randomColor = sprintf('#%06X', mt_rand(0, 0xFFFFFF));
                $shift->color = $randomColor;
                $shift->save();
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('shift_assignments');

        Schema::table('shifts', function (Blueprint $table) {
            $table->dropColumn('color');
            $table->dropColumn('short_name');
        });
    }
};
