<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Workflow;
use App\Models\WorkflowTask;
use App\Models\Folder;
use App\Models\Document;
use App\Models\User;

class DashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        if ($user->hasAnyRole(['Admin', 'Super Admin'])) {
            // Admin dashboard data
            $workflowCount = Workflow::count();
            $folderCount = Folder::count();
            $documentCount = Document::count();
            $userCount = User::count();
            $activeTaskCount = WorkflowTask::where('status', '!=', 'completed')->count();
            $recentWorkflows = Workflow::latest()->take(5)->get();
            $recentFolders = Folder::latest()->take(5)->get();
            $recentDocuments = Document::latest()->take(5)->get();
            return view('admin.index', compact(
                'workflowCount', 'folderCount', 'documentCount', 'userCount',
                'activeTaskCount', 'recentWorkflows', 'recentFolders', 'recentDocuments'
            ));
        } else {
            // User dashboard data
            $myWorkflows = Workflow::where('created_by', $user->id)->latest()->take(5)->get();

            // Get folders created by the user
            $ownedFolders = Folder::where('created_by', $user->id)->latest()->take(5)->get();

            // Get folders shared with the user via folder_user_permissions
            $sharedFolderIds = \DB::table('folder_user_permissions')
                ->where('user_id', $user->id)
                ->pluck('folder_id');
            $sharedFolders = Folder::whereIn('id', $sharedFolderIds)
                ->latest()
                ->take(5)
                ->get();

            // Merge and remove duplicates
            $myFolders = $ownedFolders->merge($sharedFolders)->unique('id')->sortByDesc('created_at')->take(5);

            $myTasks = WorkflowTask::where('assigned_user', $user->id)->where('status', '!=', 'completed')->latest()->take(5)->get();
            return view('admin.index', compact('myWorkflows', 'myFolders', 'myTasks'));
        }
    }
}
