<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Role;
use App\Models\User;
use App\Models\Permission;

class PermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
      //Creo il ruolo admin
      $role = Role::firstOrCreate(['name' => 'administrator', 'display_name' => 'Amministratore']);
      Role::firstOrCreate(['name' => 'user', 'display_name' => 'Utente']);

      // Assegno admin all'utente info@elephantech.it
      $user = User::where('email', config('app.admin_email'))->first();
      if($user != null){
        $user->assignRole($role);
      }

      $dir = base_path('app/Http/Controllers');
      $files = scandir($dir);

      $controllers = array();
      foreach($files as $file) {
        if ($file == '.' || $file == '..' || !preg_match('/\.php/', $file) || !preg_match('/^(?!.*(Has).*$)(......)/xs', $file)) continue;
        $c = preg_replace('/\Controller.php$/', '', $file);
        if($c != '') $controllers[] = $c;
        $class = '\App\Http\Controllers\\'.$c.'Controller';
        if(!isset($class::$permissions)) continue;

        foreach($class::$permissions as $key => $value){
          $permission = Permission::firstOrCreate(['name' => $key, 'display_name' => $value, 'group' => $class::$permission_group, 'guard_name' => 'web']);
          $permission->assignRole($role);
          $permission->save();
        }

      }
    }
}
