<?php

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Seeder;

class RoleSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $roles = [
            "Administrator" => "Administrator",
            "Bruger" => "Bruger",
        ];

        foreach ($roles as $key => $value) {

            try {
                if (\Spatie\Permission\Models\Role::findByName($key))
                    continue;
            } catch (Exception $e) {
                $role = new \Spatie\Permission\Models\Role();

                $role->name = $key;
                $role->description = $value;

                $role->save();
            }
        }

        //Give all permissions to Administrator (id: 1)
        foreach (\Spatie\Permission\Models\Permission::all() as $permission) {
            \Spatie\Permission\Models\Role::query()->find(1)->first()->givePermissionTo($permission);
        }

        //Bruger Permissions
        $brugerPermissions = new Collection();

        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "event.list")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "link.external.list")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "contact.list")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "feedback.create")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "menuplan.list")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "washing.machine.reservation.create")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "washing.machine.reservation.delete")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "washing.machine.reservation.list")->first());
        $brugerPermissions->add(\Spatie\Permission\Models\Permission::query()->where("name", "=", "ownuser.edit")->first());

        //Give permissions to Bruger (id: 2)
        foreach ($brugerPermissions as $permission) {
            \Spatie\Permission\Models\Role::query()->find(2)->givePermissionTo($permission);
        }
    }
}
