<?php

namespace App\Http\Controllers\Workflow;

use App\Http\Controllers\Controller;
use App\Models\Workflow;
use App\Models\WorkflowTransition;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MyWorkflowController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        // Get workflows where user is assigned via transition (user_ids or role_ids)
        $workflows = Workflow::whereHas('transitions', function($q) use ($user) {
            $q->whereJsonContains('user_ids', $user->id)
              ->orWhereJsonContains('role_ids', $user->roles->pluck('id')->toArray());
        })->with(['steps', 'transitions'])->distinct()->paginate(15);

        // Get workflow tasks for this user (by role or direct assignment)
                $tasks = \App\Models\WorkflowTask::where(function($q) use ($user) {
                        $q->where('assigned_user', $user->id)
                            ->orWhereIn('assigned_role', $user->roles->pluck('id')->toArray());
                })
                ->with(['document.creator', 'assignedRole', 'assignedUser', 'workflow'])
                ->orderByDesc('created_at')
                ->get();

        // Get all tasks for all documents shown in the user's tasks
        $allDocumentIds = $tasks->pluck('document_id')->unique()->filter();
        $allDocumentTasks = \App\Models\WorkflowTask::whereIn('document_id', $allDocumentIds)
            ->with(['transition'])
            ->get();

        return view('workflow.my', [
            'workflows' => $workflows,
            'tasks' => $tasks,
            'allDocumentTasks' => $allDocumentTasks,
        ]);
    }
}
