<?php

namespace App\Livewire\Partials\Customers;

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

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\{DB, Auth};
use Illuminate\Http\RedirectResponse;

use Livewire\Component;

use Filament\Notifications\Notification;

class AssignRoles extends Component
{
    public $user_id;
    public $selectedRoles = []; // will hold role IDs as strings
    public $roles; // cached list of all roles
    public $user;  // optional: used to display user info

    public function mount($user, $user_id)
    {
        $this->user = $user;

        $this->user_id = $user_id;

        $this->roles = Role::all();

        $this->user = User::with('roles')->findOrFail($this->user_id);

        // IMPORTANT: cast to string because checkbox values are strings in the DOM
        $this->selectedRoles = $this->user->roles
            ->pluck('name')
            ->map(fn($id) => (string) $id)
            ->toArray();

    }
    public function updateRoles()
    {
        $user = User::findOrFail($this->user_id);

        // syncRoles accepts ids or names; we're using ids here
        $user->syncRoles($this->selectedRoles);

        // refresh local user object
        $this->user = $user->fresh('roles');
        Notification::make()
            ->title("Roles assigned successfully")
            ->success()
            ->body('The roles have been assigned to the user.')
            ->color('success') 
            ->send();
        return redirect('/clients/view/'.$this->user->id);
    }
    public function render()
    {
        $user = User::findOrFail($this->user_id);
        return view('livewire.partials.customers.assign-roles',[
            'roles' => $this->roles,
            'user'  => $this->user,
        ]);
    }
}
