<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Role;
use Illuminate\Http\Request;

class UserRoleController extends Controller
{
    public function index()
    {
        $tenantId = auth()->user()->tenant_id;

        $users = User::with(['roles' => function ($q) use ($tenantId) {
            $q->wherePivot('tenant_id', $tenantId);
        }])->get();

        $roles = Role::where('tenant_id', $tenantId)->get();

        return view('users.roles', compact('users', 'roles', 'tenantId'));
    }

    public function update(Request $request, User $user)
    {
        $request->validate([
            'roles' => 'array',
        ]);

        $tenantId = auth()->user()->tenant_id;

        // sync roles with tenant
        $syncData = collect($request->roles)->mapWithKeys(function ($roleId) use ($tenantId) {
            return [$roleId => ['tenant_id' => $tenantId]];
        })->toArray();

        $user->roles()->sync($syncData);

        return back()->with('success', 'تم تحديث الأدوار بنجاح.');
    }
}
