2025-10-04 17:55:30 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
|
|
|
|
|
use App\Models\WorkoutSession;
|
2026-08-10 12:44:24 +03:00
|
|
|
use App\Support\Gamification;
|
2025-10-04 17:55:30 +03:00
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
|
use Illuminate\View\View;
|
|
|
|
|
|
|
|
|
|
class DashboardController extends Controller
|
|
|
|
|
{
|
|
|
|
|
public function index(): View
|
|
|
|
|
{
|
|
|
|
|
$user = Auth::user();
|
|
|
|
|
|
|
|
|
|
// Basic counts
|
|
|
|
|
$workoutsCount = $user->workouts()->count();
|
|
|
|
|
$sessionsQuery = WorkoutSession::where('user_id', $user->id);
|
|
|
|
|
$sessionsCount = (clone $sessionsQuery)->count();
|
|
|
|
|
$completedSessions = (clone $sessionsQuery)->whereNotNull('completed_at')->count();
|
|
|
|
|
$completionRate = $sessionsCount > 0 ? round(($completedSessions / $sessionsCount) * 100) : 0;
|
|
|
|
|
|
|
|
|
|
// Recent sessions with progress
|
|
|
|
|
$recentSessions = (clone $sessionsQuery)
|
|
|
|
|
->latest('started_at')
|
|
|
|
|
->latest('id')
|
|
|
|
|
->with(['workout:id,title', 'items:id,session_id,done'])
|
|
|
|
|
->limit(5)
|
|
|
|
|
->get()
|
|
|
|
|
->map(function ($s) {
|
|
|
|
|
$total = $s->items->count();
|
|
|
|
|
$done = $s->items->where('done', true)->count();
|
|
|
|
|
$pct = $total > 0 ? (int) round(($done / $total) * 100) : 0;
|
|
|
|
|
return [
|
|
|
|
|
'id' => $s->id,
|
|
|
|
|
'workout_title' => optional($s->workout)->title ?? 'Workout',
|
|
|
|
|
'started_at' => $s->started_at,
|
|
|
|
|
'completed_at' => $s->completed_at,
|
|
|
|
|
'done' => $done,
|
|
|
|
|
'total' => $total,
|
|
|
|
|
'pct' => $pct,
|
|
|
|
|
];
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Activity in the last 30 days (number of sessions per day)
|
|
|
|
|
$since = now()->subDays(29)->startOfDay();
|
|
|
|
|
$dailyActivity = (clone $sessionsQuery)
|
|
|
|
|
->where('created_at', '>=', $since)
|
|
|
|
|
->get(['id', 'created_at'])
|
|
|
|
|
->groupBy(function ($s) { return $s->created_at->format('Y-m-d'); })
|
|
|
|
|
->map->count();
|
|
|
|
|
|
2026-08-10 12:10:08 +03:00
|
|
|
// Body weight trend
|
|
|
|
|
$weightLogs = $user->weightLogs()->orderBy('logged_at')->get(['id', 'weight_kg', 'logged_at']);
|
|
|
|
|
$weightChange = $weightLogs->count() >= 2
|
|
|
|
|
? round($weightLogs->last()->weight_kg - $weightLogs->first()->weight_kg, 2)
|
|
|
|
|
: null;
|
|
|
|
|
|
2026-08-10 12:44:24 +03:00
|
|
|
// Streaks and badges
|
|
|
|
|
$gamification = Gamification::forUser($user);
|
|
|
|
|
|
2025-10-04 17:55:30 +03:00
|
|
|
return view('dashboard', compact(
|
|
|
|
|
'workoutsCount',
|
|
|
|
|
'sessionsCount',
|
|
|
|
|
'completedSessions',
|
|
|
|
|
'completionRate',
|
|
|
|
|
'recentSessions',
|
2026-08-10 12:10:08 +03:00
|
|
|
'dailyActivity',
|
|
|
|
|
'weightLogs',
|
2026-08-10 12:44:24 +03:00
|
|
|
'weightChange',
|
|
|
|
|
'gamification'
|
2025-10-04 17:55:30 +03:00
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
}
|