<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Support\Facades\DB;

class AddXrayPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Crear el permiso para rayos X si no existe
        $permission = Permission::firstOrCreate([
            'name' => 'xray-edit',
            'display_name' => 'Editor de Rayos X',
            'description' => 'Puede acceder al editor de rayos X'
        ]);

        // Obtener los roles
        $adminRole = Role::where('name', 'admin')->first();
        $rootRole = Role::where('name', 'root')->first();
        $doctorRole = Role::where('name', 'doctor')->first();

        // Asignar el permiso a los roles (evitando duplicados)
        $roles = [$adminRole, $rootRole, $doctorRole];
        
        foreach ($roles as $role) {
            if ($role) {
                // Verificar si el permiso ya está asignado al rol
                $exists = DB::table('permission_role')
                    ->where('permission_id', $permission->id)
                    ->where('role_id', $role->id)
                    ->exists();
                
                if (!$exists) {
                    $role->attachPermission($permission);
                }
            }
        }

        $this->command->info('Permiso de rayos X creado y asignado a roles admin, root y doctor');
    }
} 