<?php

namespace App\Http\Controllers;

use App\Models\Issue;
use App\Models\IssueTask;
use App\Models\Project;
use App\Models\Task;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class DashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $cacheKey = "dashboard:{$user->id}:v1";

        $data = Cache::remember($cacheKey, 60, function () use ($user) {
            $projects = Project::accessibleBy($user)
                ->with(['phases' => fn ($q) => $q->select('id', 'project_id', 'progress_percent')])
                ->orderBy('name')->take(8)->get();
            $projectsCount = Project::accessibleBy($user)->count();

            $myTasks = IssueTask::where('assigned_to', $user->id)
                ->where('is_done', false)
                ->with('issue.project')
                ->orderByRaw('due_date IS NULL, due_date ASC')
                ->take(8)->get();

            $myTasksFromTasks = Task::where('assigned_to', $user->id)
                ->where('status', '!=', 'completed')
                ->with('project')
                ->orderByRaw('due_date IS NULL, due_date ASC')
                ->take(8)->get();

            $myTasksCount = IssueTask::where('assigned_to', $user->id)->where('is_done', false)->count()
                + Task::where('assigned_to', $user->id)->where('status', '!=', 'completed')->count();

            $myIssues = Issue::where('assigned_to', $user->id)
                ->whereIn('status', ['open', 'in_review'])
                ->with('project')
                ->latest()->take(6)->get();
            $myIssuesCount = Issue::where('assigned_to', $user->id)->whereIn('status', ['open', 'in_review'])->count();

            $notifications = $user->notifications()->latest()->take(6)->get();
            $unreadCount = $user->unreadNotifications()->count();

            return compact(
                'user', 'projects', 'projectsCount', 'myTasks', 'myTasksFromTasks', 'myTasksCount',
                'myIssues', 'myIssuesCount', 'notifications', 'unreadCount'
            );
        });

        return view('dashboard', $data);
    }
}