<?php

namespace App\Http\Controllers\Admin;

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

class TaskController extends Controller
{
    public function index(Request $request)
    {
        $q = $request->string('q')->toString();
        $status = $request->string('status')->toString();
        $dept = $request->integer('department_id');
        $priority = $request->string('priority')->toString();

        $tasks = Task::with(['department','assignees'])
            ->when($q, fn($w)=>$w->where(function($x) use ($q) {
                $x->where('title','like',"%$q%")->orWhere('description','like',"%$q%");
            }))
            ->when($status, fn($w)=>$w->where('status',$status))
            ->when($dept, fn($w)=>$w->where('department_id',$dept))
            ->when($priority, fn($w)=>$w->where('priority',$priority))
            ->orderByDesc('id')
            ->paginate(12)
            ->withQueryString();

        $departments = Department::orderBy('name')->get();

        return view('admin.tasks.index', compact('tasks','departments','q','status','dept','priority'));
    }

    public function create()
    {
        $departments = Department::where('is_active', true)->orderBy('name')->get();
        $todoUsers = User::where('role','todo')->where('is_active',true)->orderBy('name')->get();

        return view('admin.tasks.create', compact('departments','todoUsers'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'department_id' => 'required|exists:departments,id',
            'title' => 'required|string|min:3|max:150',
            'description' => 'nullable|string|max:20000',
            'priority' => 'required|in:low,medium,high,critical',
            'status' => 'nullable|in:backlog,todo,in_progress,blocked,done,cancelled',
            'start_date' => 'nullable|date',
            'due_date' => 'nullable|date',
            'estimate_minutes' => 'nullable|integer|min:0',
            'complexity' => 'nullable|integer|min:1|max:5',
            'assignee_ids' => 'required|array|min:1',
            'assignee_ids.*' => 'exists:users,id',
        ]);

        // Ensure only todo & active in assignees
        $assignees = \App\Models\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.'])->withInput();
        }

        $task = Task::create([
            'department_id'   => $data['department_id'],
            'title'           => $data['title'],
            'description'     => $data['description'] ?? null,
            'priority'        => $data['priority'],
            'status'          => $data['status'] ?? 'todo',
            'start_date'      => $data['start_date'] ?? null,
            'due_date'        => $data['due_date'] ?? null,
            'estimate_minutes'=> $data['estimate_minutes'] ?? null,
            'complexity'      => $data['complexity'] ?? null,
            'created_by'      => auth()->id(),
        ]);

        $attach = [];
        $now = now();
        foreach ($assignees as $uid) {
            $attach[$uid] = ['assigned_by'=>auth()->id(),'assigned_at'=>$now];
        }
        $task->assignees()->sync($attach);

        return redirect()->route('admin.tasks.show', $task)->with('status','Task created & assigned.');
    }

    public function show(Task $task)
    {
        $task->load(['department','assignees']);
        $todoUsers = User::where('role','todo')->where('is_active',true)->orderBy('name')->get();

        return view('admin.tasks.show', compact('task','todoUsers'));
    }

    public function edit(Task $task)
    {
        $departments = Department::where('is_active', true)->orderBy('name')->get();
        return view('admin.tasks.edit', compact('task','departments'));
    }

    public function update(Request $request, Task $task)
    {
        $data = $request->validate([
            'department_id' => 'required|exists:departments,id',
            'title' => 'required|string|min:3|max:150',
            'description' => 'nullable|string|max:20000',
            'priority' => 'required|in:low,medium,high,critical',
            'status' => 'required|in:backlog,todo,in_progress,blocked,done,cancelled',
            'start_date' => 'nullable|date',
            'due_date' => 'nullable|date',
            'estimate_minutes' => 'nullable|integer|min:0',
            'complexity' => 'nullable|integer|min:1|max:5',
        ]);

        $task->update($data);

        return redirect()->route('admin.tasks.show', $task)->with('status','Task updated.');
    }

    public function destroy(Task $task)
    {
        $task->delete(); // soft delete
        return redirect()->route('admin.tasks.index')->with('status','Task deleted.');
    }
}
