<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Organizations;

use DefStudio\GameEngine\Enums\Role;
use DefStudio\GameEngine\Models\User;
use DefStudio\WiredTables\WiredTable;
use DefStudio\WiredTables\Enums\Sorting;
use DefStudio\GameEngine\Models\Organization;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use DefStudio\WiredTables\Configurations\TableConfiguration;

class UsersTable extends WiredTable
{
    /** @var Organization */
    public $organization;

    protected $listeners = [
        'user.subscribed' => '$refresh',
    ];

    protected function configure(TableConfiguration $configuration): void
    {
        $configuration
            ->pageSize(10)
            ->groupFilters(false);
    }

    protected function filters(): void
    {
        $this->filter(__('Role'), 'role')
            ->select(collect([Role::admin, Role::master, Role::player])->mapWithKeys(fn(Role $role): array => [$role->value => $role->label(2)]))
            ->placeholder(__('All Roles'))
            ->handle(fn(BelongsToMany $query, string $role) => $query->wherePivot('role', $role));
    }

    protected function query(): BelongsToMany
    {
        return $this->organization->users();
    }

    protected function columns(): void
    {
        $this->column(__('Name'), 'name')->searchable()->sortable();
        $this->column(__('Email'), 'email')->searchable()->sortable();
        $this->column(__('Role'))->sortable(fn(BelongsToMany $query, Sorting $dir) => $query->orderByPivot('role', $dir->value))->view('game-engine::livewire.admin.organizations.users-table.role');
        $this->column(__('Actions'))->view('game-engine::livewire.admin.organizations.users-table.actions', ['organization' => $this->organization]);
    }

    public function detach_user(int $user_id): void
    {
        /** @var User $user */
        $user = $this->organization->users()->findOrFail($user_id);
        $user->unsubscribe_from_organization($this->organization);
    }
}
