<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        $newSlugs = ['attendance.checkout.register', 'attendance.checkout.update'];
        $sourceSlugs = ['attendance.create', 'attendance.manage'];

        $newIds = DB::table('permissions')->whereIn('slug', $newSlugs)->pluck('id', 'slug');
        if ($newIds->isEmpty()) {
            return;
        }

        $sourceIds = DB::table('permissions')->whereIn('slug', $sourceSlugs)->pluck('id');
        if ($sourceIds->isEmpty()) {
            return;
        }

        $roleIds = DB::table('role_permissions')
            ->whereIn('permission_id', $sourceIds)
            ->distinct()
            ->pluck('role_id');

        foreach ($roleIds as $roleId) {
            foreach ($newIds as $permissionId) {
                $exists = DB::table('role_permissions')
                    ->where('role_id', $roleId)
                    ->where('permission_id', $permissionId)
                    ->exists();
                if ($exists) {
                    continue;
                }
                DB::table('role_permissions')->insert([
                    'role_id' => $roleId,
                    'permission_id' => $permissionId,
                ]);
            }
        }
    }

    public function down(): void
    {
        // Non-destructive: leave granted checkout permissions on roles.
    }
};
