<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

return new class extends Migration
{
    /**
     * Run the migrations.
     * 
     * 新增生產管理權限
     */
    public function up(): void
    {
        $guard = 'web';
        
        // 建立生產管理權限
        $permissions = [
            'production_orders.view' => '檢視生產工單',
            'production_orders.create' => '建立生產工單',
            'production_orders.edit' => '編輯生產工單',
            'production_orders.delete' => '刪除生產工單',
        ];

        foreach ($permissions as $name => $description) {
            Permission::firstOrCreate(
                ['name' => $name, 'guard_name' => $guard],
                ['name' => $name, 'guard_name' => $guard]
            );
        }

        // 授予 super-admin 所有新權限
        $superAdmin = Role::where('name', 'super-admin')->first();
        if ($superAdmin) {
            $superAdmin->givePermissionTo(array_keys($permissions));
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $permissions = [
            'production_orders.view',
            'production_orders.create',
            'production_orders.edit',
            'production_orders.delete',
        ];

        foreach ($permissions as $name) {
            Permission::where('name', $name)->delete();
        }
    }
};
