<?php

namespace App\Http\Controllers\Admin;

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

class TaskAssignmentController extends Controller
{
    public function assign(Request $request, Task $task)
    {
        $data = $request->validate([
            'assignee_ids' => 'required|array|min:1',
            'assignee_ids.*' => 'exists:users,id',
        ]);

        $assignees = User::whereIn('id', $data['assignee_ids'])
            ->where('role','todo')->where('is_active',true)->pluck('id')->all();

        if (empty($assignees)) {
            return back()->withErrors(['assignee_ids'=>'Select at least one active To-Do user.']);
        }

        $now = now();
        $existing = $task->assignees()->pluck('users.id')->all();
        $attach = [];
        foreach ($assignees as $uid) {
            if (!in_array($uid, $existing, true)) {
                $attach[$uid] = ['assigned_by'=>auth()->id(),'assigned_at'=>$now];
            }
        }
        if ($attach) {
            $task->assignees()->attach($attach);
        }

        return back()->with('status', 'Assignees added.');
    }

    public function unassign(Task $task, User $user)
    {
        // Only allow removing todo role assignees
        if ($user->role !== 'todo') {
            return back()->withErrors(['msg'=>'Only To-Do users can be unassigned here.']);
        }
        $task->assignees()->detach($user->id);

        return back()->with('status', 'Assignee removed.');
    }
}
