<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\User;
use Illuminate\Http\Request;

class AssignmentController extends Controller
{
    public function index(Request $request)
    {
        abort_unless($request->user()->can('assignments.manage'), 403);

        $clients = Client::query()->orderBy('name')->get();

        $users = User::query()
            ->with(['roles', 'assignedClients'])
            ->whereDoesntHave('roles', fn ($q) => $q->where('name', 'Client Viewer'))
            ->orderBy('name')
            ->get();

        return view('admin.assignments.index', [
            'clients' => $clients,
            'users' => $users,
        ]);
    }

    public function update(Request $request)
    {
        abort_unless($request->user()->can('assignments.manage'), 403);

        $data = $request->validate([
            'assignments' => ['array'],
            'assignments.*' => ['array'],
        ]);

        $assignments = $data['assignments'] ?? [];

        foreach ($assignments as $userId => $clientIds) {
            $user = User::query()->find($userId);
            if (!$user) {
                continue;
            }

            $clientIds = array_values(array_filter(array_map('intval', (array) $clientIds)));
            $user->assignedClients()->sync($clientIds);
        }

        return redirect()->route('admin.assignments.index')->with('status', 'Assignments updated.');
    }
}
