<?php
require __DIR__ . '/../vendor/autoload.php';
$app = require_once __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use App\Models\User;

echo "Verificando permisos y roles...\n";

$permissions = Permission::pluck('name')->toArray();
$hasVerColores = in_array('ver colores', $permissions);

echo "Permisos totales: " . count($permissions) . "\n";
echo "Existe permiso 'ver colores': " . ($hasVerColores ? 'si' : 'no') . "\n";

$role = Role::firstOrCreate(['name' => 'Administrador']);
$role->syncPermissions($permissions);

echo "Role 'Administrador' ahora tiene " . $role->permissions->count() . " permisos.\n";

$user = User::where('email', 'info@creacionesheidivers.com')->first();
if (! $user) {
    echo "Usuario info@creacionesheidivers.com no encontrado en la BD.\n";
    exit(0);
}

$user->assignRole($role);

echo "Usuario '" . $user->email . "' roles: " . implode(', ', $user->getRoleNames()->toArray()) . "\n";
echo "Usuario tiene permiso 'ver colores': " . ($user->can('ver colores') ? 'si' : 'no') . "\n";

// Mostrar permisos específicos del role que contengan 'ver'
$verPerms = $role->permissions->pluck('name')->filter(function ($p) { return str_starts_with($p, 'ver '); })->toArray();

echo "Permisos 'ver' asignados al rol Administrador: " . implode(', ', $verPerms) . "\n";

echo "Hecho.\n";
